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

import {getCheckPointList,addCheckPoint,delCheckPointList,bindCheckPointAndGroup,
  editCheckPointList,
  getCheckItemForBind,bindCheckPointAndCheckItem,getCheckGroupForBind,checkPointBindCheckGroup} from "@/api/checkPointManage.js";
import {listAll} from "@/api/groupManage.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 = {
          checkItemList:[],
          groupList:[],
          checkGroupList:[],
          BindGroupStatus:'',
          BindCheckItemStatus:'',
          BindCheckGroupStatus:''
         };
    }

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

    handleSelectGroupChange=(value)=>{
      // console.log(value);
      const {id,checkPointName} = this.props.content;
      const cpGroupList = this.state.groupList;
      const selectedItem = cpGroupList.filter(item=>item.id==value);
      // console.log({value,selectedItem});
      // console.log(this.state.groupList);
      this.setState({
        BindGroupStatus:'validating'
      },()=>{
          this.bindGroup({
            "checkPointId":id, // 查核点id 必填
            "checkPointName":checkPointName, // 查核点名称 
            "list": [  // 部门列表
              {
                "id":value, // 部门id 必填
                "name":selectedItem.name // 部门名称
              }
            ]
          });
      })
    }

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

    handleSelectCheckItemChange=value=>{
      const {id,checkPointName} = this.props.content;
      // const selectedItem = this.state.groupList.filter(item=>item.id=id);
      this.setState({
        BindCheckItemStatus:'validating'
      },()=>{
          this.bindCheckItem({
            "checkItemIds": [value], // 查核项id列表
            "checkPointId": id // 查核点id
          });
      })
    }

    bindCheckItem=(obj)=>{
      bindCheckPointAndCheckItem(obj).then(res=>{
          if(res.data.msg=="success"){
               this.setState({
                BindCheckItemStatus:'success'
               })
          }
        })
    }

    handleSelectCheckGroupChange=(value)=>{
      // console.log(value);
      const {id,checkPointName} = this.props.content;
      const selectedItem = this.state.checkGroupList.filter(item=>item.id==value);
      this.setState({
        BindCheckGroupStatus:'validating'
      },()=>{
          this.bindCheckGroup({
            "checkGroupDTOList": [
              {
                "checkGroupId":value,  // 查核组id
                "checkGroupName":selectedItem.name
              }
            ], 
            "checkPointId":id, // 查核点id
            "checkPointName":checkPointName
          });
      })
    }

    bindCheckGroup=(obj)=>{
      checkPointBindCheckGroup(obj).then(res=>{
        if(res.data.msg=="success"){
             this.setState({
              BindCheckGroupStatus:'success'
             })
        }
      })
    }

    componentDidMount(){
      //单位列表
      listAll().then(data=>{
        this.setState({
          groupList:data.data.data
        },()=>{
            // console.log('groupList',this.state.groupList);
        })
      });
      getCheckItemForBind().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
          checkItemList:temp
        })
      });

      getCheckGroupForBind().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
          checkGroupList: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 {checkItemList,BindGroupStatus,groupList,BindCheckItemStatus,BindCheckGroupStatus,checkGroupList} = 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="绑定单位"
                       hasFeedback
                       style={{display:edit?'block':'none'}}
                       validateStatus={BindGroupStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindGroupOne',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectGroupChange}
                             showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                            {/* <Option  value={1}>1</Option>
                            <Option  value={2}>2</Option> */}
                             {
                                groupList.map((v,k)=>{
                                    return (
                                      <Option key={k+v.name}  value={v.id}>{v.name}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item>
                   <Form.Item label="绑定查核项"
                       hasFeedback
                       style={{display:edit?'block':'none'}}
                       validateStatus={BindCheckItemStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindCheckItem',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectCheckItemChange}
                             showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                             {
                                checkItemList.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={BindCheckGroupStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindCheckGroup',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             onChange={this.handleSelectCheckGroupChange}
                             showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                          >
                             {
                                checkGroupList.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 PointManage = () => {

  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: 'sort',
      key: 'sort',
      editable: true,
    },
    {
      title: '单位分类名',
      dataIndex: 'name',
      key: 'name',
      editable: true,
    },
  ];



  const getData = async (pageObj)=>{
    let data = await getCheckPointList(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);
    modalNode.current.showModal();
  }


  const deleteCallback = (record)=>{
    delCheckPointList([record.id]).then(res=>{
        if(res.data.msg=="success"){
                getData();
        }
    })
  }

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else{
      setitem({
        "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();
      modalNode.current.handleCancel();
      thisForm.current&&thisForm.current.resetFields();
      formNode.current.state.BindGroupStatus='';
      formNode.current.state.BindCheckItemStatus='';
      formNode.current.state.BindCheckGroupStatus='';

      if(!ifEdit){
        const param = {
          "name": formData.name // 要点名称
        }
        addCheckPoint(param).then(res=>{
          if(res&&res.data.msg=="success"){
           getData({currPage:pages.currPage});
          }
        })
      }
      if(ifEdit){
        const param = {
          "id":formData.id,
          "name": formData.name // 要点名称
        }
        editCheckPointList(param).then(res=>{
          if(res&&res.data.msg=="success"){
            getData({page:pages.currPage});
          }
        })
      }
  }
  //cell里直接更新数据
  const updateFromTableCell = (row)=>{
      const {sort,id,name} = row;
      const param = {
        sort,id,name
      }
      editCheckPointList(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} paginationCallback={paginationCallback} 
             pages={pages}  data={arr}  deleteCallback={deleteCallback} callbackFromChild={callbackFromChild} 
             ifUpdateList={ifUpdateList} updateFromTableCell={updateFromTableCell}
             />
          }
    </div>
  );
}




 
export default PointManage;