/*
 * @Author: your name
 * @Date: 2021-04-27 08:49:09
 * @LastEditTime: 2021-05-21 17:06:24
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /react-antd-admin-template/src/views/conditionManage/comdition.js
 */

import React,{ useState,useEffect,useRef } from 'react';

import {getCheckConditionList,editCondition,addCondition,delCondition,getOutpatientList,
  conditionBindGroupIdentity,getGroupIdentityList,getConditionParentList
} from "@/api/checkCondition.js";
import {Form,Input,Select,Button} from 'antd';
import EditableFormTable from './table.js';
import ModalWrap from '@/components/Modal/modal.js';
import { filter } from 'jszip';


const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const { Option } = Select;
const {Search} = Input;
// const formTailLayout = {
//   labelCol: { span: 4 },
//   wrapperCol: { span: 8, offset: 4 },
// };

class TableForm extends React.Component {
  state = {
    outpatientList:[],
    BindStatus:'',
    groupIdentityList:[],
    parentList:[],
    loading:false
  }
  handleCommit = () => {
    console.log('开始校验表单');
    return new Promise((resolve,reject)=>{
      this.props.form.validateFields((err,value) => {
        if (!err) {
          // console.info('success',value);
          let data = {
            // ...this.props.content,
            ...value
          };
          resolve(data);
        }
      });
    });
  };
  
  handleSelectChange=(value)=>{
    // console.log(value);
    const {id} = this.props.content;
    this.setState({
      BindStatus:'validating'
    },()=>{
        this.bindGroupIdentity({
          "conditionId": id,  // 追踪条件id
          "deptClassIds": [value] // 单位分类列表
        });
    })
  }

  bindGroupIdentity=(obj)=>{
    conditionBindGroupIdentity(obj).then(res=>{
        if(res.data.msg=="success"){
             this.setState({
              BindStatus:'success'
             })
        }
      })
  }

  onSelectParentFocus=()=>{
    this.setState({loading:true},()=>{
      getConditionParentList().then(data=>{
        this.setState({
          parentList:data.data.data,
          loading:false
         })
      });
    });
    
  }

  componentDidMount(){
    getOutpatientList().then(data=>{
         this.setState({
          outpatientList:data.data.data
         })
    });

    getGroupIdentityList().then(data=>{
      this.setState({
        groupIdentityList:data.data.data
       })
    });

    getConditionParentList().then(data=>{
      this.setState({
        parentList:data.data.data,
       })
    });
 
  }

  render() {
    
    const { getFieldDecorator } = this.props.form;
    const {outpatientList,BindStatus,groupIdentityList,parentList,loading} = this.state;
    const {edit,content} = this.props;
    const {name,depType,conditionType,description,id} = content;
    const getKeyName = (id)=>{
      const keyItem = parentList.filter(item=>item.id == id);
      console.log({keyItem,parentList,id});
      return keyItem.length>0?keyItem[0].name:''
    }
    const config =(key,rules)=>{
      return {
        initialValue:edit?key:'',
        rules: [
          ...rules
        ],
      }
    }
    // console.log(this.state);
    return (
       <div>
        <Form.Item {...formItemLayout} label="条件名">
          {getFieldDecorator('name',config(name,[{required: true,message: '请输入条件名',}]))(<Input  placeholder="请输入条件名" />)}
        </Form.Item>
        <Form.Item {...formItemLayout} label="门诊">
          {getFieldDecorator('depType',config((depType==1||depType=='门诊')?'门诊':'急诊',[{required: true,message: '选择门急诊类型',}]))(
            <Select
              placeholder="选择门急诊类型"
              style={{ width: '100%' }}
              // onChange={this.handleSelectOutpatientChange}
            >
              
              {
                outpatientList.map((v,k)=>{
                    return (
                      <Option key={k} value={v.code}>{v.msg}</Option>
                    )
                })
              }
            </Select>
          )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="选择父级条件">
          {getFieldDecorator('parentId',config(getKeyName(id),[{required:false,message: '选择父级条件',}]))(
            <Select
              placeholder="选择父级条件"
              style={{ width: '100%' }}
              loading={loading}
              // open={!loading}
              onFocus={this.onSelectParentFocus}
              onChange={this.handleSelectParentChange}
            >
              
              {
                parentList.map((v,k)=>{
                    return (
                      <Option key={k} value={v.id}>{v.name}</Option>
                    )
                })
              }
            </Select>
          )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="条件类型">
          {getFieldDecorator('conditionType',config(conditionType,[{required: true,message: '选择条件类型',}]))(
            <Select
              placeholder="选择条件类型"
              style={{ width: '100%' }}
              // onChange={this.handleSelectChange}
            >
              <Option value="0">个案</Option>
              <Option value="1">系统</Option>
            </Select>
          )}
        </Form.Item>
        <Form.Item {...formItemLayout} label="说明">
          {getFieldDecorator('description',config(description,[{required: false,message: '请输入说明',}]))(<Input  placeholder="请输入说明" />)}
        </Form.Item>
        <Form.Item label="绑定单位分类"
            hasFeedback
            style={{display:edit?'block':'none'}}
            validateStatus={BindStatus}   //validating,success,warning
        >
        {
            getFieldDecorator('bindGroup',config('',[{required: false,}]))(
              <Select
                  placeholder=""
                  onChange={this.handleSelectChange}
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
              >
                  {
                    groupIdentityList.map((v,k)=>{
                        return (
                          <Option key={k} value={v.id}>{v.name}</Option>
                        )
                    })
                  }
              </Select>,
            )
        }
        </Form.Item>
      </div>
    );
  }
}
const WrappedTableForm = Form.create({ name: 'register' })(TableForm);






const PermissionMaintenance = () => {

  let [arr,setarr] = useState([]);
  let [pages,setpages] = useState({});
  let [ifUpdateList,setifUpdateList]=useState(false);
  let [ifRender,setifRender] = useState(false);
  let [ifShowDialog,setifShowDialog] = useState(false);
  const [item,setitem]=useState({});
  const [ifEdit,setifEdit]=useState(false);
  const modalNode = useRef(null);
  const formNode = useRef(null);
  const thisForm = useRef(null);
  const [searchKey,setsearchKey] = useState('');
//   let [editingKey,seteditingKey] = useState('');

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      render: text => <a>{text}</a>,
    },
    {
      title: '条件名',
      dataIndex: 'name',
      key: 'name',
      editable: true,
    },
    {
      title: '门诊',
      dataIndex: 'depType',
      key: 'depType',
      editable: true,
    },
    {
      title: '条件类型',
      dataIndex: 'conditionType',
      key: 'conditionType',
      editable: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      editable: true,
    },
  ];

 

  const getData = async (pageObj)=>{
    let data = await getCheckConditionList(pageObj);
    const renderData = data.data.data.list.map((item,index)=>{
          return {
              ...item,
              key:item['id'],
            //   editable: true,
          }
    })
    setarr(renderData);
    thisForm.current&&thisForm.current.resetFields();
    setpages({
      'currPage':data.data.data.currPage,
      'totalPage':data.data.data.totalPage,
      'totalCount':data.data.data.totalCount,
    });
    setifRender(false);
    setifRender(true);
  }

  const callbackFromChild = (data)=>{
    setitem(data);
    setifEdit(true);
    thisForm.current&&thisForm.current.resetFields();
    modalNode.current.showModal();
  }

    const deleteCallback = (record)=>{
    // console.log('删除');
      delCondition([record.id]).then(res=>{
          if(res.data.msg==="success"){
                  getData();
          }
      })
    }

  
  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else {
      setitem({
        "conditionType": "0",  // 条件类型：0个案 1系统
        "depType": 1, // 门急诊类型 1-门诊 2-急诊
        "description": "", // 说明
        "name": "", // 条件名称
        "parentId": 0, // 父级条件id
        "parentName": "0", // 父级条件id，没有选择0
        "sortNo": 0 // 顺序号,默认 非必填项
      });
    }
    modalNode.current.showModal();
  }


  const commitForm = async ()=>{  //表单提交
    console.log('提交表单');
    // console.log({formNode});
    const formData = await formNode.current.handleCommit();
    const formNodeState = formNode.current.state;
    const selectedParent = formNodeState.parentList.filter(item=>isNaN(formData.parentId)?item.name == formData.parentId:item.id == formData.parentId);
    modalNode.current.handleCancel();
    thisForm.current.resetFields();
    formNode.current.state.BindStatus="";
    console.log({formData});
    // console.log({formData,formNodeState,selectedParent,});
    if(!ifEdit){
      //新增
      const param = {
        "conditionType":(formData.conditionType=='个案'||formData.conditionType=='0')?'0':'1',  // 条件类型：0个案 1系统
        "depType": (formData.depType=='门诊'||formData.depType==1)?1:2, // 门急诊类型 1-门诊 2-急诊
        "description":formData.description, // 说明
        "name":formData.name, // 条件名称
        "parentId":formData.parentId?formData.parentId:0, // 父级条件id
        "parentName": formData.name?formData.name:'0', // 父级条件id，没有选择0
        "sortNo":formData.sortNo
      }
      addCondition(param).then(res=>{
        if(res&&res.data.msg==="success"){
         getData();
        }
      })
    }
    if(ifEdit){
      //编辑
      const param = {
        "id":parseInt(item.id),
        ...formData,
        "depType": (formData.depType=='门诊'||formData.depType==1)?1:2, // 门急诊类型 1-门诊 2-急诊
        "conditionType":(formData.conditionType=='个案'||formData.conditionType=='0')?'0':'1',  // 条件类型：0个案 1系统
        "parentId":selectedParent.length>0?selectedParent[0].id:0, // 父级条件id
        // "depType": formData.depType=='急诊'?1:2, // 门急诊类型 1-门诊 2-急诊
        // "description":formData.description, // 说明
        // "name":formData.name, // 条件名称
        // "parentId":formData.parentId, // 父级条件id
        // "sortNo":formData.sortNo
        // "parentName": formData.parentName, // 父级条件id，没有选择0
      }
      // console.log({param});
      editCondition(param).then(res=>{
        // console.log({res});
        if(res&&res.data.msg==="success"){
          getData({page:pages.currPage});
        }
      });
    }
  }

  const paginationCallback = (obj)=>{
    const {currPage} = obj;
    getData({page:currPage,pageSize:10,keyword:searchKey});
  }

  const onSearch = (searchKey)=>{
    //  console.log({searchKey});
    setsearchKey(searchKey);
     getData({
       'keyword':searchKey?searchKey:''
     });
  }
  
  useEffect(()=>{
    getData();
  },[]);

  return ( 
    <div className="app-container">
          <h1>查核条件维护</h1>
          <ModalWrap ref={modalNode} show={ifShowDialog} handleOkCallback={commitForm} >
                <WrappedTableForm edit={ifEdit} content = {item} ref={thisForm}  wrappedComponentRef={formNode} />
          </ModalWrap>
    
          <div style={{display:'flex',flexDirection:'row'}}>
          <Button onClick={handleAdd} type="primary" style={{ marginBottom: 16,marginRight:20 }}>
             新增条件
          </Button>
          <Search style={{ width: 200 }} allowClear placeholder="请输入条件名"  onSearch={onSearch} enterButton />
          </div>
          {
             ifRender&& <EditableFormTable paginationCallback={paginationCallback} deleteCallback={deleteCallback} pages={pages} columns={columns} callbackFromChild={callbackFromChild}  data={arr}  ifUpdateList={ifUpdateList}/>
          }
    </div>
  );
}




 
export default PermissionMaintenance;