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

import {getCheckItem,getCheckItemTypeList,listAll,delCheckItem,addCheckItem,editCheckItem,
  bindCheckItemAndCheckPoint,addCheckItemCheckResult,getCheckItemCheckResultSelecterList} from "@/api/checkPointManage.js";
// import {getOutpatientList} from "@/api/checkCondition.js";
import { Button,Form,Input,Select,Tag,Tooltip} 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 InputGroup = Input.Group;
const { Search } = Input;


class TableForm extends React.Component {
    

    constructor(props){
         super(props);
         
         this.state = {
          depTypeList:[],
          checkPointList:[],
          checkTypeList:[],
          checkResultList:[],//查核结果配置
          addCheckItemResultSelect:[],
          BindStatus:'',
          BindPointStatus:'',
          checkResultName:'',//
          checkResultCount:'',
         };
    }

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

    handleSelectChange=(value)=>{
      // console.log(value);
      const {id} = this.props.content;
      this.setState({
        BindStatus:'validating'
      },()=>{
          this.bindPoint({
            checkItemId:id,
            checkPointIds:[value]
          });
      })
    }
    //当删除查核结果配置
    onTagClose=(e)=>{
        // console.log('onTagClose',e);
        // console.log(this.state.checkResultList);
        const checkResultListByFilter = this.state.checkResultList.filter(item=>item.attr != e);
        // console.log({checkResultListByFilter});
        this.setState({
          checkResultList:checkResultListByFilter
        })
    }
    //更新查核结果配置
    updateCheckResultList=()=>{
      const {checkResultList,checkResultName,checkResultCount} = this.state;
      this.setState({
        checkResultList:[...checkResultList,{attr:checkResultName,value:checkResultCount}]
      },()=>this.setState({checkResultName:'',checkResultCount:''}))
    }

    bindPoint=(obj)=>{
      bindCheckItemAndCheckPoint(obj).then(res=>{
            // console.log({res});
          if(res.data.msg=="success"){
               this.setState({
                BindStatus:'success'
               })
          }
        })
    }

    onAddCheckItemResultSelectChange=(e)=>{
        // console.log({e});
        this.setState({
          checkResultName:e
        })
    }

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

    componentDidMount(){
      listAll().then(res=>{
        // console.log({res});
        const temp = res.data.data;
        this.setState({
          checkPointList:temp
        })
      });
      //获取添加查核项结果下拉列表
      getCheckItemCheckResultSelecterList().then(res=>{
        const temp = res.data.data;
        // console.log({temp});
        this.setState({
          addCheckItemResultSelect:temp
        })
      });
    
      getCheckItemTypeList().then(res=>{
        const temp = res.data.data;
        this.setState({
          checkTypeList:temp
        })
      });
      
      const {content,edit} = this.props;
      const editCheckItemResultList = JSON.parse(content.itemAttrs);
      // console.log('json',content.itemAttrs);
      if(edit){
         this.setState({
          checkResultList:editCheckItemResultList
         })
      }
    }



    shouldComponentUpdate(nextProps,nextState){
    
          return true;
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {depTypeList,BindStatus,checkPointList,checkTypeList,checkResultList,checkResultName,checkResultCount,addCheckItemResultSelect} = this.state;
        const {checkItemName,rightAnswerText,relatedRules,checkModelList,score,itemAttr} = content;
        // const bindGroupDefault = groupManaList.length>0?groupManaList[0].name:'bindGroupDefault';
        console.log({content,edit});
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span:6 },
            },
            wrapperCol: {
              xs: { span: 12 },
              sm: { span: 12 },
            },
        };
        const config =(key,rules)=>{
          console.log({key});
          return {
            initialValue:edit?key:'',
            rules: [
              ...rules
            ],
          }
        }

        return (
            <Form {...formItemLayout}  >
                   <Form.Item label="查核项">
                    {
                        getFieldDecorator('checkItemName',config(checkItemName,[{required: true,message: '请输入查核项名!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="查核方式">
                    {
                        getFieldDecorator('checkModeList',config(checkModelList,[{required: true,message: '请选择查核方式!',}]))(
                          <Select
                              placeholder=""
                          >
                              {
                                checkTypeList.map((v,k)=>{
                                    return (
                                      <Option key={k} value={v.itemCode}>{v.itemName}</Option>
                                    )
                                })
                              }
                          </Select>,
                        )
                    }
                   </Form.Item>
                   <Form.Item label="查核项分数" style={{display:edit?'block':'none'}}>
                    {
                        getFieldDecorator('score',config(score,[{required: true,message: '请输入查核分数!',}]))(<Input />)
                    }
                   </Form.Item>
                   <Form.Item label="查核项查核结果配置" style={{display:edit?'block':'none'}}>
                    {
                        getFieldDecorator('itemAttr',config(itemAttr,[{required: false,message: '请输入配置查核结果！',}]))(
                          <div style={{borderRadius:'4px',minHeight:'70px'}}>
                               <InputGroup compact>
                                  <Tooltip title="请选择查核结果名">
                                  <Select
                                    showSearch
                                    style={{ width:'50%' }}
                                    placeholder="请选择查核结果名"
                                    optionFilterProp="children"
                                    onChange={this.onAddCheckItemResultSelectChange}
                                    // onFocus={onFocus}
                                    // onBlur={onBlur}
                                  >
                                    {
                                      addCheckItemResultSelect.map((item,index)=>{
                                           return (
                                              <Option key={index} value={item}>{item}</Option>
                                           )
                                      })
                                    }
                                  </Select>
                                  </Tooltip>
                                  <Tooltip title="请定义查核结果对应的分值占比，如：50">
                                      <Input style={{ width: '30%' }} onChange={(e)=>{this.setState({checkResultCount:e.target.value})}} value={checkResultCount} placeholder="如：50" />
                                  </Tooltip>
                                  <Button type="primary" onClick={this.updateCheckResultList}>添加</Button>
                               </InputGroup>
                               <Form.Item >
                               {
                                 getFieldDecorator('score',config(score,[{required: true,message: '请输入查核分数!',}]))(
                                      <div>
                                           {
                                            checkResultList.map((item,index)=>{
                                              // return(
                                              //        <Tag  closable key={index} onClose={this.onTagClose.bind(this,item.attr)} style={{padding:0,border:'none'}}>
                                              //              <InputGroup compact>
                                              //                 <Tooltip title="请定义查核结果名">
                                              //                       <Input style={{ width: '70%' }} onChange={(e)=>{this.setState({checkResultName:e.target.value})}}  defaultValue={item.attr} placeholder="如：缺失"  />
                                              //                 </Tooltip>
                                              //                 <Tooltip title="请定义查核结果对应的分值占比，如：50">
                                              //                       <Input style={{ width: '30%' }} onChange={(e)=>{this.setState({checkResultCount:e.target.value})}} defaultValue={item.value} placeholder="如：50" />
                                              //                 </Tooltip>
                                              //              </InputGroup>
                                              //        </Tag>
                                              // );
                                              const tagName = item.attr;
                                              return (
                                                <Tag color="#4E78FF"  closable key={index} onClose={this.onTagClose.bind(this,tagName)}>
                                                    {`${item.attr}｜${item.value}%`}
                                                </Tag>
                                              )
                                            })
                                          }
                                      </div>
                                 )
                               }
                               </Form.Item>
                          </div>
                        )
                    }
                   </Form.Item>
                   <Form.Item label="应知应会文字">
                    {
                        getFieldDecorator('rightAnswerText',config(rightAnswerText,[{required: false,message: '!',}]))(<Input.TextArea autoSize={{minRows:5}} />)
                    }
                   </Form.Item>
                   <Form.Item label="相关条文">
                    {
                        getFieldDecorator('relatedRules',config(relatedRules,[{required: false,message: '!',}]))(<Input.TextArea autoSize={{minRows:5}} />)
                    }
                   </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);
  const [searchKey,setsearchKey] = useState('');
//   let [editingKey,seteditingKey] = useState('');

  const columns = [
    {
      title: 'id',
      dataIndex: 'checkItemId',
      width:'10%',
      key: 'checkItemId',
      render: text => <a>{text}</a>,
    },
    {
      title: '查核项',
      dataIndex: 'checkItemName',
      key: 'checkItemName',
      editable: true,
      width:'15%'
    },
    {
      title: '查核方式',
      dataIndex: 'checkModelList',
      key: 'checkModelList',
      editable: true,
      width:'10%'
    },
    {
      title: '拥有查核结果',
      key: 'itemAttrs',
      width:'20%',
      dataIndex: 'itemAttrs',
      render: tags =>{
        const newTags = JSON.parse(tags);
        console.log({newTags});
        return (
          <span>
          {newTags&&newTags.map(tag => {
            return (
              <Tag  key={tag.attr}>
                  {tag.attr}
              </Tag>
            );
          })}
          </span>
        )
      },
    },
    {
        title: '应知应会文字',
        dataIndex: 'rightAnswerText',
        key: 'rightAnswerText',
        editable: true,
        width:'20%'
    },
   
    {
        title: '应知应会图片url',
        dataIndex: 'rightAnswerImage',
        key: 'rightAnswerImage',
        editable: false,
        width:'20%'
    },
    {
        title: '相关条文',
        dataIndex: 'relatedRules',
        key: 'relatedRules',
        editable: false,
        width:'20%'
    },
  ];



  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,// 正确答案文字  
            // "score":formData.score,//查核项分数
        }
        addCheckItem(param).then(res=>{
          if(res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const paramForCheckItemresult = {
          "checkItemId":item.checkItemId,   // 查核项id
          "score":parseInt(formData.score),  // 分数
          "itemAttr":formData.itemAttr,
        }
        const param = {
            "id":item.checkItemId,
            "checkModeList": formData.checkModeList, // 查核方式
            "name":formData.checkItemName, // 名称必填
            "relatedRules":formData.relatedRules, // 相关条文
            "rightAnswerImage":item.rightAnswerImage,// 应知应会图片url
            "rightAnswerText":formData.rightAnswerText, // 应知应会文字
        }
        // console.log({param,paramForCheckItemresult});
        //

        addCheckItemCheckResult(paramForCheckItemresult).then(res=>{
              if(res&&res.data.msg=="success"){
                console.log('查核项结果配置成功');
                editCheckItem(param).then(res=>{
                  if(res&&res.data.msg=="success"){
                    getData({page:pages.currPage});
                   }
                });
                // 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} paginationCallback={paginationCallback} pages={pages}  data={arr} deleteCallback={deleteCallback} callbackFromChild={callbackFromChild}  ifUpdateList={ifUpdateList}/>
          }
    </div>
  );
}




 
export default CheckItem;