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

import {getCheckItem,bindCheckPointAndCheckItem,listAll,delCheckItem,addCheckItem,editCheckItem,bindCheckItemAndCheckPoint} from "@/api/checkPointManage.js";
// import {getOutpatientList} from "@/api/checkCondition.js";
import { Button,Form,Input,Select} from 'antd';
import EditableFormTable from './table';
import ModalWrap from '@/components/Modal/modal.js';
// import { TAGSVIEW_EMPTY_TAGLIST } from '../../../store/action-types';

const { Option } = Select;

const { Search } = Input;

class TableForm extends React.Component {
    

    constructor(props){
         super(props);
         
         this.state = {
          depTypeList:[],
          checkPointList:[],
          BindStatus:'',
          BindPointStatus:'',
         };
    }

    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} = this.props.content;
      this.setState({
        BindStatus:'validating'
      },()=>{
          this.bindPoint({
            checkItemId:id,
            checkPointIds:[value]
          });
      })
    }

    bindPoint=(obj)=>{
      bindCheckItemAndCheckPoint(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
        })
      })
    }

    // componentDidUpdate(prevProps,prevState){
    //     console.log({prevProps,prevState});
    // }

    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {depTypeList,BindStatus,checkPointList,BindPointStatus} = this.state;
        const {name,rightAnswerText,relatedRules,checkModeList} = 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="应知应会文字">
                   {
                        getFieldDecorator('rightAnswerText',config(rightAnswerText,[{required: true,message: '请输入单位分类名!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="相关条文">
                   {
                        getFieldDecorator('relatedRules',config(relatedRules,[{required: true,message: '请输入单位分类名!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="查核方式">
                   {
                        getFieldDecorator('checkModeList',config(checkModeList,[{required: true,message: '请输入单位分类名!',}]))(<Input />)
                    }
                   </Form.Item>
                   
                   <Form.Item label="绑定查核要点"
                       hasFeedback
                       style={{display:edit?'block':'none'}}
                       validateStatus={BindStatus}   //validating,success,warning
                   >
                    {
                        getFieldDecorator('bindPoint',config('',[{required: false,}]))(
                          <Select
                             placeholder=""
                             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 CheckItem = () => {

  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);
//   let [editingKey,seteditingKey] = useState('');

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      render: text => <a>{text}</a>,
    },
    {
      title: '查核项',
      dataIndex: 'name',
      key: 'name',
      editable: true,
      width:'15%'
    },
    {
        title: '应知应会文字',
        dataIndex: 'rightAnswerText',
        key: 'rightAnswerText',
        editable: true,
        width:'20%'
    },
   
    {
        title: '应知应会图片url',
        dataIndex: 'rightAnswerImage',
        key: 'rightAnswerImage',
        editable: true,
        width:'20%'
    },
    {
        title: '相关条文',
        dataIndex: 'relatedRules',
        key: 'relatedRules',
        editable: true,
    },
  ];



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

  const handleAdd=()=>{

    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else{
      setitem({
        "checkModeList": "", // 查核方式 必填（暂时写死，需要考虑（下拉框选择））
        "name": "",// 查核项目名称 必填
        "relatedRules": "", // 相关条文
        "rightAnswerImage": "", // 正确答案图片url 上传图片接口待定
        "rightAnswerText": "" // 正确答案文字 
      });
    }
    
    modalNode.current.showModal();
  }



  const commitForm = async ()=>{  //表单提交
      console.log('提交表单');
      
      const formData = await formNode.current.handleCommit();
      // console.log({formNode,thisForm});
      modalNode.current.handleCancel();
      thisForm.current&&thisForm.current.resetFields();
      formNode.current.state.BindStatus='';
      formNode.current.state.BindPointStatus='';

      

      if(!ifEdit){
        const param = {
            "checkModeList":formData.checkModeList, // 查核方式 必填（暂时写死，需要考虑（下拉框选择））
            "name":formData.name,// 查核项目名称 必填
            "relatedRules":formData.relatedRules, // 相关条文
            "rightAnswerImage":'', // 正确答案图片url 上传图片接口待定
            "rightAnswerText": formData.rightAnswerText// 正确答案文字  
        }
        addCheckItem(param).then(res=>{
          if(res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const param = {
            "id":item.id,
            "checkModeList": formData.checkModeList, // 查核方式
            "name":formData.name, // 名称必填
            "relatedRules":formData.relatedRules, // 相关条文
            "rightAnswerImage":item.rightAnswerImage,// 应知应会图片url
            "rightAnswerText":formData.rightAnswerText // 应知应会文字
        }
        // console.log({param});
        editCheckItem(param).then(res=>{
          if(res.data.msg=="success"){
            getData();
           }
        });
      }
  }

  const paginationCallback = (obj)=>{
    const {currPage} = obj;
    getData({page:currPage,pageSize:10});
  }

  const onSearch = (searchKey)=>{
      //  console.log({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}/>
          }
    </div>
  );
}




 
export default CheckItem;