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

import {getGroupManaList,addGroupMana,delGroupMana,getGroupIdentityList,
  editGroupMana,getPersonList,groupBindPerson,getCheckPointList,groupBindCheckPoint,
  getDeptManager,
} 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 {
    
    state = {
        BindStatus:'',
        BindCheckPointStatus:'',
        personList:[],
        checkPointList:[],
        groupManageList:[]
    }
    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.bindPerson({
                "deptId": id, // 部门主键
                "empIds": [value] // 人员主键列表
            });
        })
    }
  
    bindPerson=(obj)=>{
      groupBindPerson(obj).then(res=>{
          if(res.data.msg=="success"){
                this.setState({
                   BindStatus:'success'
                })
          }
        })
    }

    handleSelectCheckPointChange=value=>{
        const {id,deptName} = this.props.content;
        const selectedItem = this.state.checkPointList.filter(item=>item.id==value);
        console.log({selectedItem});
        this.setState({
          BindCheckPointStatus:'validating'
        },()=>{
            this.bindCheckPoint({
              "checkPointDTOList": [   // 查核点列表
                {
                  "checkPointId": value,  // 查核点id 必填
                  "checkPointName":selectedItem[0].name // 查核点名称
                }
              ],
              "deptId":id,  // 部门id 必填
              "deptName":deptName // 部门名称
            });
        })
    }
    bindCheckPoint=(obj)=>{
      groupBindCheckPoint(obj).then(res=>{
          if(res.data.msg=="success"){
                this.setState({
                  BindCheckPointStatus:'success'
                })
          }
        })
    }

    shouldComponentUpdate(nextProps,nextState){
          return true;
    }

    componentDidMount(){
        getPersonList().then(data=>{
          this.setState({
            personList:data.data.data
          })
        });
        getCheckPointList().then(data=>{
          this.setState({
            checkPointList:data.data.data
          })
        });

        //单位管理员列表
        getDeptManager().then(data=>{
          this.setState({
            groupManageList:data.data.data
          })
        });
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {BindStatus,personList,BindCheckPointStatus,checkPointList,groupManageList} = this.state;
        const {name,deptManagerId,deptManagerName} = content;
        
        // console.log({content});
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span:6 },
            },
            wrapperCol: {
              xs: { span: 12 },
              sm: { span: 12 },
            },
        };
        const config =(key,rules)=>{
          // console.log({key});
          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('deptManagerId',config(deptManagerName,[{required:true}]))(
                          <Select
                             placeholder=""
                            //  onChange={this.handleSelectChange}
                          >
                             {
                                groupManageList.map((v,k)=>{
                                    return (
                                      <Option key={k} value={v.id}>{v.name}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item>
                   {/* <Form.Item label="单位管理员ID">
                   {getFieldDecorator('deptManagerId',config(deptManagerId,[{required: true,message: '请输入单位管理员ID!',}]) 
                   )(<Input />)}
                   </Form.Item> */}
                   <Form.Item label="绑定员工"
                       hasFeedback
                       validateStatus={BindStatus}   //validating,success,warning
                       style={{display:edit?'block':'none'}}
                   >
                    {
                        getFieldDecorator('bindGroup',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectChange}
                             showSearch
                             optionFilterProp="children"
                             filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                             }
                          >
                             {
                                personList.map((v,k)=>{
                                    return (
                                      <Option key={k} value={v.id}>{v.name}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item>
                   <Form.Item label="绑定查核要点"
                       hasFeedback
                       style={{display:edit?'block':'none'}}
                       validateStatus={BindCheckPointStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindCheckPoint',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectCheckPointChange}
                             showSearch
                             optionFilterProp="children"
                             filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                             }
                             
                          >
                             {
                                checkPointList.map((v,k)=>{
                                    return (
                                      <Option key={k} value={v.id}>{v.name}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item>
            </Form>
        )
    }
}

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


const GroupMana = () => {

  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);
  const [checkedBox,set_checkedBox] = useState([]);
  const [groupIdentity,set_groupIdentity] = useState([]);


  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '展示排序',
      dataIndex: 'sort',
      key:'sort',
      width:'15%',
      editable:true,
    },
    {
      title: '单位名',
      dataIndex: 'name',
      key: 'name',
    },
    {
        title: '管理员ID',
        dataIndex: 'deptManagerId',
        key: 'deptManagerId',
    },
    {
        title: '管理员',
        dataIndex: 'deptManagerName',
        key: 'deptManagerName',
    },
  ];


  //获取表格数据
  const getData = async (pageObj)=>{
    let data = await getGroupManaList(pageObj);
    const renderData = data.data.data.list.map((item,index)=>{
          return {
              ...item,
              key:item['id'],
            //   editable: true,
          }
    })
    setarr(renderData);
    setpages({
        'currPage':data.data.data.currPage,
        'totalPage':data.data.data.totalPage,
        'totalCount':data.data.data.totalCount,
    });
    setifRender(false);
    setifRender(true);
  }
  //获取绑定下拉列表
  const getBindSelectData= async (obj)=>{
    let data = await getGroupIdentityList(obj);
    set_groupIdentity(data.data.data.list);
    // console.log('getBindSelectData',data)
  }

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

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

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else {
      setitem({
        "deptManagerId": 0, // 部门主管id
        "deptManagerName": "", // 部门主管名称 
        "name": ""  // 必填
      });
    }
    
    modalNode.current.showModal();
  }


  //更新单条表格数据
  const updateFormRowData = (param)=>{
    if(!param.id)return;
    editGroupMana(param).then(res=>{
      if(res&&res.data.msg=="success"){
        getData({page:pages.currPage});
       }
    });
  }

  const commitForm = async ()=>{  //表单提交
      console.log('提交表单');
      // console.log({formNode});
      const formData = await formNode.current.handleCommit();
      const formState = formNode.current.state;
      const deptManagerName = formState.groupManageList.filter(item=>isNaN(formData.deptManagerId)?item.name==formData.deptManagerId:item.id==formData.deptManagerId);
      // console.log({deptManagerName,formState,formData});
      modalNode.current.handleCancel();
      formNode.current.state.BindStatus='';
      formNode.current.state.BindCheckPointStatus='';
      thisForm.current.resetFields();
      // console.log({ifEdit,formData,formNode});
      if(!ifEdit){
        const param = {
            'deptManagerId':formData.deptManagerId,
            'deptManagerName':formData.deptManagerName,
            'name':formData.name
        }
        addGroupMana(param).then(res=>{
          if(res&&res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const param = {
            "deptManagerId":deptManagerName[0].id,
            "deptManagerName":deptManagerName[0].name,
            "id":formData.id,
            "name":formData.name
        }
        // console.log({param});
        updateFormRowData(param);
      }
  }
  
  
  const paginationCallback = (obj)=>{
    const {currPage} = obj;
    getData({page:currPage,pageSize:10,keyword:searchKey});
  }

  const updateFromTableCell = (row)=>{
    const {sort,id,name,deptManagerId,deptManagerName} = row;
    const param = {
      sort,id,name,deptManagerId,deptManagerName
    }
    updateFormRowData(param);
  }
  
  

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

  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 set_checkedBox={set_checkedBox} columns={columns} pages={pages} 
             paginationCallback={paginationCallback}  
             data={arr} 
             deleteCallback={deleteCallback} 
             callbackFromChild={callbackFromChild} 
             ifUpdateList={ifUpdateList}
             updateFormRowData={updateFormRowData}
             updateFromTableCell={updateFromTableCell}
             />
          }
    </div>
  );
}




 
export default GroupMana;