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

import {listAll} from "@/api/checkGroupManage.js";
import {getProvisionsList,addProvisions,delProvisions,editProvisions,provisionsBindCheckPoint} from "@/api/provisionsManage.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 = {
          depTypeList:[],
          checkPointList:[],
          personnelInfoList:[],
          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({
            "articleId": id,  
            "checkPointIds": [ 
                value
            ]
          });
      })
    }

  
    bindCheckPoint=(obj)=>{
        provisionsBindCheckPoint(obj).then(res=>{
            // console.log({res});
          if(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
        })
      });
    }

  

    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }

    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {BindStatus,checkPointList} = this.state;
        const {articleName,articleVersion,id,ruleName} = content;
        // const bindGroupDefault = groupManaList.length>0?groupManaList[0].name:'bindGroupDefault';
       
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span:4 },
            },
            wrapperCol: {
              xs: { span: 12 },
              sm: { span: 20 },
            },
        };
        const config =(key,rules)=>{
          return {
            initialValue:edit?key:'',
            rules: [
              ...rules
            ],
          }
        }

        return (
            <Form {...formItemLayout}  >
                   <Form.Item label="条文条款版本">
                   {
                        getFieldDecorator('articleVersion',config(articleVersion,[{required: true,message: '请输入条文条款版本!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="条文条款">
                   {
                        getFieldDecorator('articleName',config(articleName,[{required: true,message: '请输入条文条款!',}]))(<Input.TextArea autoSize={{minRows:5}} />)
                    }
                   </Form.Item>
                   
                   <Form.Item label="制度名称">
                   {
                        getFieldDecorator('ruleName',config(ruleName,[{required: true,message: '请输入制度名称!',}]))(<Input.TextArea autoSize={{minRows:5}} />)
                    }
                   </Form.Item>
                   {
                       id&&<Form.Item label="绑定查核要点"
                       hasFeedback
                       style={{display:edit?'block':'none'}}
                       validateStatus={BindStatus}   //validating,success,warning
                        >
                            {
                                getFieldDecorator('bindCheckPoint',config('',[{required: false,}]))(
                                <Select
                                    placeholder=""
                                    style={{width:'25%'}}
                                    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>         
        )
    }
}

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: 'articleName',
      key: 'articleName',
      editable: true,
      width:'30%',
    },
    {
        title: '条文条款版本',
        dataIndex: 'articleVersion',
        key: 'articleVersion',
        editable: true,
        width:'10%',
    },
    {
        title: '制度类型',
        dataIndex: 'ruleType',
        key: 'ruleType',
        editable: true,
        width:'10%',
    },
    {
        title: '制度名',
        dataIndex: 'ruleName',
        key: 'ruleName',
        editable: true,
        // width:'10%',
    },
  ];



  const getData = async (pageObj)=>{
    let data = await getProvisionsList(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();
        thisForm.current&&thisForm.current.resetFields();
  }

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

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr[0]){
        setitem(arr[0]);
    }else {
        setitem({
            "articleName":"", // 条文条款名称
            "articleVersion": "", // 条文条款版本
            "ruleName": "", // 制度名称
            "ruleType": 0  // 制度类型 暂时定死为0
        });
    }
    
    modalNode.current.showModal();
  }



  const commitForm = async ()=>{  //表单提交
      console.log('提交表单');
      // console.log({formNode});
      const formData = await formNode.current.handleCommit();
      modalNode.current.handleCancel();
      thisForm.current.resetFields();
      formNode.current.state.BindStatus="";
      // console.log({formData});
      if(!ifEdit){
        const param = {
            "articleName":formData.articleName, // 条文条款名称
            "articleVersion":formData.articleVersion, // 条文条款版本
            "ruleName":formData.ruleName, // 制度名称
            "ruleType": 0  // 制度类型 暂时定死为0
        }
        addProvisions(param).then(res=>{
          if(res&&res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const param = {
            "id":item.id,
            "articleName":formData.articleName, // 条文条款名称
            "articleVersion":formData.articleVersion, // 条文条款版本
            "ruleName":formData.ruleName, // 制度名称
            "ruleType": 0  // 制度类型 暂时定死为0
        }
        // console.log({param});
        editProvisions(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 width={1000} 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;