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

import {getPersonnelInfoList,editUser} from "@/api/personnelManagement.js";
import { Checkbox,Form,Input} from 'antd';
import EditableFormTable from '@/components/EditableCell/editableCell.js';
import ModalWrap from '@/components/Modal/modal.js';

const CheckboxGroup = Checkbox.Group;
const plainOptions = ['admin','editor','guest','group-leader','company-manager'];
// const defaultCheckedList = ['Apple', 'Orange'];

const { Search } = Input;

class TableForm extends React.Component {
    
    constructor(props){
        super(props);
        this.state = {
            checkedList: props.permissionList,
            indeterminate: true,
            checkAll: false,
            plainOptions:plainOptions,
        };
    }

    onChange = checkedList => {
        let plainOptions = this.state.plainOptions;
        this.setState({
          checkedList,
          indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
          checkAll: checkedList.length === plainOptions.length,
        });
      };
    
      onCheckAllChange = e => {
        let plainOptions = this.state.plainOptions;
        this.setState({
          checkedList: e.target.checked ? plainOptions : [],
          indeterminate: false,
          checkAll: e.target.checked,
        });
      };

    handleCommit = () => {
        console.log('开始校验表单');
        return Promise.resolve(this.state.checkedList)
    };

 
    
    render(){
    

        return (
            <div>
                <div style={{ borderBottom: '1px solid #E9E9E9' }}>
                <Checkbox
                    indeterminate={this.state.indeterminate}
                    onChange={this.onCheckAllChange}
                    checked={this.state.checkAll}
                >
                    全选
                </Checkbox>
                </div>
                <br />
                <CheckboxGroup
                options={this.state.plainOptions}
                value={this.state.checkedList}
                onChange={this.onChange}
                />
            </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 [permissionList,setpermissionList] = useState([]);
  const [editItem,seteditItem] = useState({});
  const modalNode = useRef(null);
  const formNode = 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,
    },
  ];

  const config = {
    action:{
        deleteBtn:false,
        editBtn:false,  
        editPermissionBtn: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,
          }
    })
    setarr(renderData);
    setpages({
        'currPage':data.data.data.currPage,
        'totalPage':data.data.data.totalPage,
        'totalCount':data.data.data.totalCount,
    });
    setifRender(false);
    setifRender(true);
    // console.log({data});
  }

  


  const commitForm = ()=>{  //表单提交

    //   console.log({formNode});
    modalNode.current.handleCancel();
      formNode.current.handleCommit().then(data=>{
              console.log({'表{单提交数据':data});
              const newData = {
                   ...editItem,
                   permissions:data.join(',')
              }
              editUser(newData).then(data=>{
                //    console.log({'修改后的数据':data});
                getData({page:pages.currPage});
             });
      });

  }

  const editPermissionFunc = (item)=>{
    //   console.log(item.permissions.split(','));
        let temp = item.permissions.split(',');
        seteditItem(item);
        setpermissionList(permissionList.concat(temp));
        modalNode.current.showModal();
  }

  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 permissionList={[...permissionList]}  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} callbackFromChild={editPermissionFunc} config={config} data={arr}  ifUpdateList={ifUpdateList}/>
          }
    </div>
  );
}




 
export default PermissionMaintenance;