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

import {getCheckGroupList,addCheckGroup,delCheckGroup,editCheckGroup,bindCheckGroupAndCheckPoint,
  listAll,bindCheckGroupAndEmp,getPersonListForBind,getCheckGroupManager} from "@/api/checkGroupManage.js";
// import {getPersonnelInfoList} from "@/api/personnelManagement.js";
import { Button,Form,Input,Select,Radio} 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 = {
          depTypeList:[],
          checkPointList:[],
          personnelInfoList:[],
          groupManageList:[],
          BindStatus:'',
          BindPersonStatus:''
         };
    }

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

    handleSelectChange=(value)=>{
    //   console.log(value);
      const {id,name} = this.props.content;
      this.setState({
        BindStatus:'validating'
      },()=>{
          this.bindCheckPoint({
            "checkGroupId": id,    // 查核组id 必填
            "checkGroupName":name,  // 查核组名称 
            "checkPointDTOList": [ // 查核点列表 必填
              {
                "checkPointId":value, // 查核id
                "checkPointName": "" // 查核名称
              }
            ]
          });
      })
    }

    handleSelectPersonChange=(value)=>{
        const isManager = this.props.form.getFieldValue('isManager');
        const selected = this.state.personnelInfoList.filter(item=>item.id==value);
        // console.log({isManager,selected});
        const {id,name} = this.props.content;
        this.setState({
            BindPersonStatus:'validating'
        },()=>{
            this.bindPerson({
                "checkGroupId":id,  // 查核组id
                "checkGroupName":name, // 查核组名称
                "empDTOList": [ // 职工列表
                    {
                    "empId":value, // 职工id
                    "empName": selected[0].name, // 职工名称
                    "isManager":isManager == 1?isManager:0// 是否是组长 1，是；0不是
                    }
                ]
            });
        })
    }
    
    bindPerson=(obj)=>{
        bindCheckGroupAndEmp(obj).then(res=>{
            // console.log({res});
          if(res&&res.data.msg=="success"){
               this.setState({
                BindPersonStatus:'success'
               })
          }
        })
    }

    bindCheckPoint=(obj)=>{
        bindCheckGroupAndCheckPoint(obj).then(res=>{
            // console.log({res});
          if(res&&res.data.msg=="success"){
               this.setState({
                BindStatus:'success'
               })
          }
        })
    }

    componentWillUnmount(){
        this.props.form.resetFields();
    }

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

      //员工表
      getPersonListForBind().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
            personnelInfoList:temp
        })
      });

      //组长表
      getCheckGroupManager().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
            groupManageList:temp
        })
      })
    }


    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {personnelInfoList,BindStatus,checkPointList,BindPersonStatus,groupManageList} = this.state;
        const {name,groupManagerName,isManager} = 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="选择查核组管理员" style={{display:edit?'none':'block'}}>                
                    {
                        getFieldDecorator('groupManagerId',config(groupManagerName,[{required: false,}]))(
                          <Select
                             placeholder="" >
                             {
                                groupManageList.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={BindStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindCheckPoint',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectChange}
                             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.Item name="isManager" label="是否为管理者" rules={[{ required: true, message: '请选择!' }]} style={{display:!edit?'none':'block'}}>
                        {
                        getFieldDecorator('isManager',config(isManager,[{required: false,}]))(
                            <Radio.Group>
                              <Radio value={1}>是</Radio>
                              <Radio value={0}>否</Radio>
                            </Radio.Group>
                        )
                       }
                   </Form.Item>
                   <Form.Item label="绑定员工"
                       hasFeedback
                       style={{display:edit?'block':'none'}}
                       validateStatus={BindPersonStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindPerson',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectPersonChange}
                             showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                             {
                                personnelInfoList.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 CheckGroupManage = () => {

  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',
      width:'10%',
      render: text => <a>{text}</a>,
    },
    {
      title: '查核组',
      dataIndex: 'name',
      key: 'name',
      editable: true,
    },
    {
        title: '查核组管理员',
        dataIndex: 'groupManagerName',
        key: 'groupManagerName',
        editable: true,
    },
  ];



  const getData = async (pageObj)=>{
    let data = await getCheckGroupList(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 callbackFromChild = (data)=>{
        setitem(data);
        setifEdit(true);
        thisForm.current&&thisForm.current.resetFields();
        modalNode.current.showModal();
  }

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

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else{
      setitem({
        "name": "" , // 查核组名称 必填
        "groupManagerId": 1, // 组长id 必填
        "groupManagerName": "" // 组长名称，非必填
      });
    }
    
    modalNode.current.showModal();
  }



  const commitForm = async ()=>{  //表单提交
      console.log('提交表单');
      // console.log({formNode});
      const formData = await formNode.current.handleCommit();
      const formNodeState = formNode.current.state;
      
      modalNode.current.handleCancel();
      thisForm.current.resetFields();
      formNode.current.state.BindStatus='';
      formNode.current.state.BindPersonStatus='';

      if(!ifEdit){
        const seletedItem = formNodeState.groupManageList.filter(item=>item.id==formData.groupManagerId);
        // console.log({seletedItem});
        const param = {
            "name":formData.name , // 查核组名称 必填
            "groupManagerId":formData.groupManagerId, // 组长id 必填
            "groupManagerName":seletedItem.length>0?seletedItem[0].name:'' // 组长名称，非必填
        }
        addCheckGroup(param).then(res=>{

          if(res&&res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const param = {
            "id":item.id,
            "name":formData.name // 查核组名称
        }
        // console.log({param});
        editCheckGroup(param).then(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 columns={columns}  pages={pages} paginationCallback={paginationCallback}  data={arr} deleteCallback={deleteCallback} callbackFromChild={callbackFromChild}  ifUpdateList={ifUpdateList}/>
          }
    </div>
  );
}




 
export default CheckGroupManage;