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

// import {getGroupManaList,addGroupMana,delGroupMana,
//   editGroupMana,getPersonList,groupBindPerson,getCheckPointList,groupBindCheckPoint

// } from "@/api/groupManage.js";
import {getPersonnelInfoList,addUser,editUser,deleteUsers} from "@/api/personnelManagement.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:'',
        groupList:[],
        checkPointList:[]
    }
    handleCommit = () => {
        console.log('开始校验表单');
        // let data;
        
        
        return new Promise((resolve,reject)=>{
          this.props.form.validateFields((err,values) => {
            // console.log({err,values});
            if (!err) {
              console.log({'success':values});
              let data = {
                ...this.props.content,
                ...values
              }
              // this.props.form.resetFields();
              resolve(data);
            }
        });
        });
        
    };

    

    shouldComponentUpdate(nextProps,nextState){
      // this.props.form.resetFields();
          return true;
    }

    componentDidMount(){
      
      // getGroupListForBind().then(data=>{
      //     this.setState({
      //       groupList:data.data.data
      //     })
      //   });
      //   getCheckPointList().then(data=>{
      //     this.setState({
      //       checkPointList:data.data.data
      //     })
      //   });
    }
    
    render(){
        
        const { getFieldDecorator,resetFields } = this.props.form;
        const {content,edit} = this.props;
        // const {BindStatus,groupList,BindCheckPointStatus,checkPointList} = this.state;
        const {name,telPhone,password,code} = content;
        // console.log({content,edit});
        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>
                   {
                     !edit&&<Form.Item label="账号">
                     {getFieldDecorator('code',config(code,[{required:true,message: '请输入账号!',}]) 
                     )(<Input />)}
                     </Form.Item>
                   }
                   <Form.Item label="密码">
                   {getFieldDecorator('password',config(password,[{required: true,message: '请输入密码!',}]) 
                   )(<Input />)}
                   </Form.Item>
                   <Form.Item label="电话号码">
                   {getFieldDecorator('telPhone',config(telPhone,[{required: false,message: '请输入号码!',}]) 
                   )(<Input />)}
                   </Form.Item>
                   {/* <Form.Item label="绑定单位"
                       hasFeedback
                       validateStatus={BindStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindGroup',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectChange}
                          >
                             {
                                groupList.map((v,k)=>{
                                    return (
                                      <Option key={k} value={v.id}>{v.name}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item> */}
                   {/* <Form.Item label="绑定查核要点"
                       hasFeedback
                       validateStatus={BindCheckPointStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindCheckPoint',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectCheckPointChange}
                          >
                             {
                                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('');
//   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: 'telPhone',
        key: 'telPhone',
        editable: true,
    },
    // {
    //     title: '门诊管理员',
    //     dataIndex: 'deptManagerName',
    //     key: 'deptManagerName',
    //     editable: true,
    // },
  ];



  const getData = async (pageObj)=>{
    let data = await getPersonnelInfoList(pageObj);
    const renderData = data.data.data.list.map((item,index)=>{
          return {
              ...item,
              key:item['id'],
            //   editable: true,
          }
    });
    setifEdit(false);
    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('删除');
    deleteUsers([record.id]).then(res=>{
        if(res&&res.data.status==200){
                getData();
        }
    })
  }

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    setitem(arr[0]);
    modalNode.current.showModal();
  }

  const commitForm = async ()=>{  //表单提交
      console.log('提交表单');
      // console.log({formNode});
      const formData = await formNode.current.handleCommit()
      // console.log({ifEdit,formData,formNode});
      thisForm.current.resetFields();
        if(!ifEdit){
          const param = {
            "code":formData.code,    // 登录账号  必填
            "headUrl":'url', // 头像url 
            "name":formData.name,    // 昵称 必填
            "password":formData.password,  // 密码 必填
            "permissions": "", // 权限相关 必填 e.g.（admin,editor,guest,group-leader,company-manager）
            "telPhone":formData.telPhone   // 电话 
          }
          addUser(param).then(res=>{
            if(res&&res.data.status==200){
                modalNode.current.handleCancel();
                getData();
            }
          })
        }
        if(ifEdit){
          const param = {
            "id":item.id,    // 需要编辑的人员ID
            "name":formData.name,  // 需要编辑的人员名称
            "password":formData.password, // 密码
            "permissions": "", // 权限 e.g. admin,editor,guest,group-leader,company-manager
            "telPhone":formData.telPhone //
          }
          // console.log({param});
          editUser(param).then(res=>{
            if(res&&res.data.status==200){
              modalNode.current.handleCancel();
              getData({page:pages.currPage});
             }
          });
        }
      

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

  const onSearch = (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',marginBottom:16}}>
          <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 GroupMana;