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

import {getCheckItemResultPopList,getCheckItemListForSelect,editCheckItemListForSelect,addCheckItemListForSelect,delCheckItemListForSelect} from "@/api/checkItem.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 = {
            checkItemListForSelect:[]
         };
    }

    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(){
        getCheckItemListForSelect().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
            checkItemListForSelect:temp
        })
      });
    }


    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {checkItemListForSelect} = this.state;
        const {resultName,checkItemName} = 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('resultName',config(resultName,[{required: true,message: '请输入查核结果!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="选择查核项" >                
                        {
                            getFieldDecorator('checkItemId',config(checkItemName,[{required: true,message: '请选择查核项!'}]))(
                                <Select
                                    showSearch
                                    placeholder="" 
                                    optionFilterProp="children"
                                    // onChange={onChange}
                                    // onFocus={onFocus}
                                    // onBlur={onBlur}
                                    // onSearch={onSearch}
                                    filterOption={(input, option) =>
                                         option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                    
                                >
                                    {
                                        checkItemListForSelect.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 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: 'checkItemName',
      key: 'checkItemName',
      editable: false,
      width:'40%',
    },
    {
        title: '查核结果',
        dataIndex: 'resultName',
        key: 'resultName',
        width:'30%',
        editable: false,
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width:'20%',
        editable: false,
    }
  ];



  const getData = async (pageObj)=>{
    let data = await getCheckItemResultPopList(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('删除');
    delCheckItemListForSelect([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.checkItemListForSelect.filter(item=>item.id==formData.itemCode);
      
      if(!ifEdit){
       
        // console.log({seletedItem});
        const param = {
             "checkItemId": formData.checkItemId,
             "resultName":formData.resultName
        }
        addCheckItemListForSelect(param).then(res=>{

          if(res&&res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const editItem = item;
        const param = {
            "id":editItem.id,
            "resultName":formData.resultName

        }
        // console.log({param});
        editCheckItemListForSelect(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;