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

import {getCheckTypeDictionary,getCheckWays,addCheckDictionary,editCheckDictionary,delCheckDictionary} from "@/api/checkGroupManage.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 = {
            checkTypeList:[]
         };
    }

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


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

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


    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {checkTypeList} = this.state;
        const {itemCode} = 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('itemName',config(itemName,[{required: true,message: '请输入查核方式名!',}]))(<Input />)
                    }
                   </Form.Item> */}
                   <Form.Item label="选择查核方式" >                
                        {
                            getFieldDecorator('itemCode',config(itemCode,[{required: true,}]))(
                                <Select
                                    placeholder="" >
                                    {
                                        checkTypeList.map((v,k)=>{
                                            return (
                                               <Option key={k} value={v.itemCode}>{v.itemName}</Option>
                                            )
                                        })
                                    }
                                </Select>,
                            )
                        }
                   </Form.Item>
            </Form>         
        )
    }
}

const WrappedTableForm = Form.create({ name: 'register' })(TableForm);






const Page = () => {

  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: 'typeCode',
      key: 'typeCode',
      editable: false,
    },
    {
        title: '字典类型名称',
        dataIndex: 'typeName',
        key: 'typeName',
        editable: false,
    },
    {
        title: '字典code',
        dataIndex: 'itemCode',
        key: 'itemCode',
        editable: false,
    },
    {
        title: '字典名称',
        dataIndex: 'itemName',
        key: 'itemName',
        editable: false,
    },
    {
        title: '检索码',
        dataIndex: 'searchCode',
        key: 'searchCode',
        editable: false,
    },
  ];



  const getData = async (pageObj)=>{
    let data = await getCheckTypeDictionary(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('删除');
    delCheckDictionary([record.id]).then(res=>{
        if(res.data.msg=="success"){
                getData();
        }
    })
  }

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else{
      setitem({
        "itemCode": "",   // 下拉款中选择中的key
        "itemName": ""
      });
    }
    
    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();

      const seletedItem = formNodeState.checkTypeList.filter(item=>item.itemCode==formData.itemCode);
      
      if(!ifEdit){
       
        // console.log({seletedItem});
        const param = {
            "itemCode":formData.itemCode , 
            "itemName":seletedItem.length>0?seletedItem[0].itemName:'' 
        }
        addCheckDictionary(param).then(res=>{

          if(res&&res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const editItem = item;
        const param = {
            "id":editItem.id, 
            "itemCode":formData.itemCode , 
            "itemName":seletedItem.length>0?seletedItem[0].itemName:'' 
        }
        // console.log({param});
        editCheckDictionary(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 Page;