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

import {getGroupIdentityList,addGroupIdentity,editGroupIdentity,delGroupIdentity,bindGroup,listAll,
  groupIdentityBindCondition,conditionList} from "@/api/groupManage.js";
import {getOutpatientList} from "@/api/checkCondition.js";
import { Button,Form,Input,Select} from 'antd';
import EditableFormTable from './table';
import ModalWrap from '@/components/Modal/modal.js';

const { Option } = Select;

const {Search} = Input;

class TableForm extends React.Component {
    

    constructor(props){
         super(props);
         
         this.state = {
          conditionList:[],
          groupManaList:[],
          depTypeList:[], //部门
          BindStatus:'',
          BindConditionStatus:''
         };
    }

    handleCommit = () => {
        console.log('开始校验表单');
        return new Promise((resolve,reject)=>{
          this.props.form.validateFields((err,values) => {
            if (!err) {
              // console.log({'success':values});
              let data = {
                ...this.props.content,
                ...values
              }
              resolve(data);
            }
          });
        });
    };

    handleSelectChange=(value)=>{
      // console.log(value);
      const {id} = this.props.content;
      this.setState({
        BindStatus:'validating'
      },()=>{
          this.bindGroup({
            deptId:value,
            deptClassIds:[id]
          });
      })
    }

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

    handleSelectConditionChange=(value)=>{
      const {id} = this.props.content;
      this.setState({
        BindConditionStatus:'validating'
      },()=>{
          this.bindCondition({
            deptClassId:id,
            conditionIds:[value]
          });
      })
    }

    bindCondition=(obj)=>{
      groupIdentityBindCondition(obj).then(res=>{
        if(res.data.msg=="success"){
             this.setState({
              BindConditionStatus:'success'
             })
        }
      })
    }


    componentDidMount(){

      conditionList().then(data=>{
        // console.log({data});
        this.setState({
          conditionList:data.data.data
        })
      });

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

      listAll().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
          groupManaList:temp
        })
      })
    }

    // componentDidUpdate(prevProps,prevState){
    //     console.log({prevProps,prevState});
    // }

    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {depTypeList,BindStatus,groupManaList,BindConditionStatus,conditionList} = this.state;
        const {name,depType} = content;
        // const bindGroupDefault = groupManaList.length>0?groupManaList[0].name:'bindGroupDefault';
        // console.log({content});
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span:6 },
            },
            wrapperCol: {
              xs: { span: 12 },
              sm: { span: 12 },
            },
        };
        const config =(key,rules)=>{
          return {
            initialValue:edit?key:'',
            rules: [
              ...rules
            ],
          }
        }

        return (
            <Form {...formItemLayout}  >
                   <Form.Item label="单位分类名">
                   {
                        getFieldDecorator('name',config(name,[{required: true,message: '请输入单位分类名!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="门急诊类型">
                   {getFieldDecorator('depType',config(depType==1||depType=='门诊'?'门诊':'急诊',[{required: true,message: '请输入门急诊类型!',}]) 
                   )(
                      <Select
                        placeholder=""
                        // onChange={this.handleSelectChange}
                      >
                       {
                          depTypeList.map((v,k)=>{
                              return (
                                <Option key={k} value={v.code}>{v.msg}</Option>
                              )
                          })
                        }
                      </Select>,
                    )}
                   </Form.Item>
                   <Form.Item label="绑定单位"
                       hasFeedback
                       validateStatus={BindStatus}   //validating,success,warning
                       style={{display:edit?'block':'none'}}
                   >
                    {
                        getFieldDecorator('bindGroup',config('',[{required: false,}]))(
                          <Select
                            style={{ width: 200 }}
                            placeholder=""
                            optionFilterProp="children"
                            onChange={this.handleSelectChange}
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                            {
                                groupManaList.map((v,k)=>{
                                    return (
                                      <Option key={k} value={v.id}>{v.name}</Option>
                                    )
                                })
                            }
                          </Select>,
                        )
                    }
                   </Form.Item>
                   <Form.Item label="绑定条件"
                       hasFeedback
                       validateStatus={BindConditionStatus}   //validating,success,warning
                       style={{display:edit?'block':'none'}}
                   >
                    {
                        getFieldDecorator('bindCondition',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectConditionChange}
                             showSearch
                             optionFilterProp="children"
                             filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                             {
                                conditionList.map((v,k)=>{
                                    return (
                                      <Option key={k+v} value={v.id}>{v.name}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item>
          </Form>         
        )
    }
}

const WrappedTableForm = Form.create({ name: 'register' })(TableForm);






const GroupIdentity = () => {

  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('');
  const [selectRowObj,setselectRowObj] = useState(null);
//   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,
    },
  ];



  const getData = async (pageObj)=>{
    let data = await getGroupIdentityList(pageObj);
    const renderData = data.data.data.list.map((item,index)=>{
          return {
              ...item,
              key:item['id'],
            //   editable: true,
          }
    });
    modalNode.current.handleCancel();
    
    setarr(renderData);
    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);
        modalNode.current.showModal();
        thisForm.current&&thisForm.current.resetFields();
  }

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

  const handleAdd=()=>{
    setifEdit(false);
    //初始化表单
    if(arr.length>0){
        setitem(arr[0]);
    }else {
      setitem({
        "depType":'',  // 门急诊类型
        "name": "" // 单位分类名称
      }); 
    }
    modalNode.current.showModal();
  }

  // const bindGroup=(record)=>{
  //   // bindGroup
  //   getGroupManaList().then(res=>{
  //     if(res.data.msg=="success"){
           
  //     }
  //   })
  // }

  const commitForm = async ()=>{  //表单提交
      console.log('提交表单');
      console.log({formNode});
      const formData = await formNode.current.handleCommit();
      // console.log({formData});
      formNode.current.state.BindConditionStatus='';
      formNode.current.state.BindStatus='';
      thisForm.current.resetFields();
      if(!ifEdit){
        const param = {
          "depType":formData.depType,  // 门急诊类型
          "name": formData.name // 单位分类名称
        }
        addGroupIdentity(param).then(res=>{
          if(res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const param = {
          "id":item['id'],
          "depType":(formData['depType']=='门诊'||formData['depType']==1)?1:2, // 门急诊类型 1.门诊，2.急诊 必须为1或2
          "name": formData['name']
        }
        // console.log({param});
        editGroupIdentity(param).then(res=>{
          if(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 selectRowObj={selectRowObj} columns={columns} pages={pages} paginationCallback={paginationCallback}  data={arr}  deleteCallback={deleteCallback} callbackFromChild={callbackFromChild} ifUpdateList={ifUpdateList}/>
          }
    </div>
  );
}




 
export default GroupIdentity;