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

import {getCheckItem,getCheckItemTypeList,listAll,delCheckItem,addCheckItem,editCheckItem,
  bindCheckItemAndCheckPoint,addCheckItemCheckResult,getCheckItemCheckResultSelecterList,} from "@/api/checkPointManage.js";
import {addCheckItemAttr} from "@/api/checkItem.js";
import {uploadFile} from "@/api/common.js";
import { Button,Form,Input,Select,Tag,Tooltip,message,Upload, Icon} from 'antd';
import EditableFormTable from './table';
import ModalWrap from '@/components/Modal/modal.js';
import { getToken } from "@/utils/auth";
// 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:[],
          fileList:[],
          checkTypeList:[],
          checkResultList:[],//查核结果配置
          addCheckItemResultSelect:[],
          BindStatus:'',
          ifClear:false,
          BindPointStatus:'',
          checkResultName:'',//
          checkResultCount:'',
         };
    }

    handleCommit = () => {
        console.log('开始校验表单');
        return new Promise((resolve,reject)=>{
          this.props.form.validateFields((err,values) => {
            if (!err) {
              const imgUrls = this.state.fileList.map(item=>item.url);
              let data = {
                ...this.props.content,
                ...values,
                // checkModelList
                itemAttrs:this.state.checkResultList,
                rightAnswerImage:imgUrls.join(',')
              }
              // console.log({data,values,imgUrls});        
              resolve(data);
            }
        });
        })
      
    };

    handleSelectChange=(value)=>{
      const {checkItemId} = this.props.content;
      this.setState({
        BindStatus:'validating'
      },()=>{
          this.bindPoint({
            checkItemId:checkItemId,
            checkPointIds:[value]
          });
      })
    }
    //当删除查核结果配置
    onTagClose=(e)=>{
        const checkResultListByFilter = this.state.checkResultList.filter(item=>item.attr != e);
        this.setState({
          checkResultList:checkResultListByFilter
        })
    }
    //更新查核结果配置
    updateCheckResultList=()=>{
      const {checkResultList,checkResultName,checkResultCount} = this.state;
      if(checkResultCount<0||checkResultCount>1){
        message.warning('抱歉，配置项占比只能是0~1之间！');
        return;
      }
      if(checkResultName&&checkResultCount){
        this.setState({
          checkResultList:[...checkResultList,{attr:checkResultName,value:checkResultCount}],
        },()=>this.setState({checkResultName:'',checkResultCount:''}))
      }else {
        message.warning('抱歉，未填写配置项！');
      }
      
    }

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

    initData(){
      const {content,edit} = this.props;

      if(edit&&content.itemAttrs){
        const editCheckItemResultList = JSON.parse(content.itemAttrs);
        console.log({editCheckItemResultList});
        this.setState({
          checkResultList:editCheckItemResultList
        })
      
      }

      if(content.rightAnswerImage&&content.rightAnswerImage.split(',').length>0){
            const imgList = content.rightAnswerImage.split(',');
            const hasUploadFiles = imgList.map((item,index)=>{
                  return {
                    uid: `-${index}`,
                    name: 'image.png',
                    status: 'done',
                    url: item
                  }
            })
             this.setState({
               fileList:hasUploadFiles
             })

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

    clearData(){
      this.setState({
        checkResultName:'',
        checkResultList:[],
        checkResultCount:''
      })
    }

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

    componentDidMount(){
      // console.log(process.env)
      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
        })
      });

      this.initData();
    }
    
    //图片变化回调
    handleUploadChange = ({file,fileList}) => {

        console.log({file,fileList});
        if (file.status == 'removed') {
             this.setState({
              fileList
             })
        }
  
    };

    // 图片上传
    imgUpload = (options) => {
      const { onSuccess, onError, file, onProgress } = options;

      // start：进度条相关
      // 伪装成 handleChange里面的图片上传状态
      const key = new Date().getTime();
      const imgItem = {
        uid: `-${key}`, // 注意，这个uid一定不能少，否则上传失败
        name: 'image.png',
        status: 'uploading',
        url: '',
        percent: 99, // 注意不要写100。100表示上传完成
      };

      this.setState(prevState=>{
        return {
          fileList:prevState.fileList.concat([imgItem]),
        }
      }); // 更新 imgList
      // end：进度条相关
      const formData = new FormData();
      formData.append('file',file);
    
      uploadFile(formData)
        .then((res) => {
          console.log('imgUpload:',res);
          const imgItem = {
            status: 'done',
            url: res.data.data, // url 是展示在页面上的绝对链
          };

          const tempFileList = this.state.fileList;
          const index = tempFileList.findIndex(item=>item.uid == -key);
          tempFileList[index] = {
            ...tempFileList[index],
            ...imgItem
          }
          console.log({tempFileList});
          this.setState({
            fileList:tempFileList,
          }); // 更新 imgList
        })
        .catch((e) => {
          console.log('图片上传失败:' + JSON.stringify(e || ''));
          message.error('图片上传失败，请重试');
        });
  
  };

    shouldComponentUpdate(nextProps,nextState){
          // console.log({nextProps,nextState})  
          return true;
    }

    componentDidUpdate(prevProps) {
      const {content} = this.props;
      // console.log('start_diff_itemAttr',prevProps.content.itemAttr,content);
      if (content.itemAttr != prevProps.itemAttr) {
          // console.log('update_checkResultList');
           this.initData();
      }
    }
    
    render(){
        
        const { getFieldDecorator } = this.props.form;
        const {content,edit} = this.props;
        const {depTypeList,BindStatus,checkPointList,checkTypeList,ifClear,checkResultList,checkResultName,checkResultCount,addCheckItemResultSelect,fileList} = this.state;
        const {checkItemName,rightAnswerText,relatedRules,checkModelList,score,itemAttr,rightAnswerImage} = 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,option)=>{
          // console.log({key});
          return {
            initialValue:edit?key:'',
            rules: [
              ...rules
            ],
            ...option
          }
        }

        const uploadButton = (
          <div>
            <Icon type="plus" />
            <div className="ant-upload-text">上传图片</div>
          </div>
        );

        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>
                   {
                     edit&&<Form.Item label="查核项分数" style={{display:edit?'block':'none'}}>
                     {
                         getFieldDecorator('score',config(score,[{required:false,message: '请输入查核分数!'}],{
                          validator:(rule, value, callback)=>{
                               if(value<=0){
                                callback('分数必需大于0！')
                               }
                               callback();
                          }
                         }))(<Input placeholder="" />)
                     }
                     </Form.Item>
                   }


                   
                   <Form.Item label="查核项查核结果配置" style={{display:edit?'block':'none'}}>
                    {
                        getFieldDecorator('itemAttr',config('',[{required: false,message: '请输入配置查核结果！',}]))(
                          <div style={{borderRadius:'4px',minHeight:'70px',display:ifClear?'none':'block'}}>
                               <InputGroup compact>
                                  <Tooltip title="请选择查核结果名">
                                  <Select
                                    style={{ width:'50%'}}
                                    placeholder="请选择查核结果名"
                                    value={checkResultName}
                                    onChange={this.onAddCheckItemResultSelectChange}
                                    // // onFocus={onFocus}
                                    // // onBlur={onBlur}
                                  >
                                    {
                                      addCheckItemResultSelect.map((item,index)=>{
                                           return (
                                              <Option key={index} value={item}>{item}</Option>
                                           )
                                      })
                                    }
                                  </Select>
                                  </Tooltip>
                                  <Tooltip title="请定义查核结果对应的分值占比，如：0.5表示占比50%">
                                      <Input style={{ width: '35%' }} onChange={(e)=>{this.setState({checkResultCount:e.target.value})}} value={checkResultCount} placeholder="输入0～1之间，如：0.5" />
                                  </Tooltip>
                                  <Button type="primary" onClick={this.updateCheckResultList}>添加</Button>
                               </InputGroup>
                               <Form.Item >
                               {
                                 getFieldDecorator('score',config(score,[{required: false,message: '请输入查核分数!',}]))(
                                      <div>
                                           {
                                            checkResultList&&checkResultList.map((item,index)=>{
                                              const tagName = item.attr;
                                              return (
                                                <Tag color="#4E78FF"  closable key={index} onClose={this.onTagClose.bind(this,tagName)}>
                                                    {`${item.attr}｜${Number(item.value*100).toFixed(2)}%`}
                                                </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="应知应会图片">
                          <Upload
                              // action={()=>{
                              //        const {REACT_APP_BASE_API} = process.env;
                              //        return Promise.resolve(`${REACT_APP_BASE_API}/upload/file`);
                              // }}
                              // headers={{
                              //   token:getToken()
                              // }}
                              customRequest={this.imgUpload}
                              withCredentials={true}
                              listType="picture-card"
                              fileList={fileList}
                              onRemove={()=>{console.log('onRemove')}}
                              onChange={this.handleUploadChange}
                          >
                              {fileList.length >= 8 ? null : uploadButton}
                         </Upload>
                        
                   </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('');
  const [ifRenderModal,set_ifRenderModal] = useState(true);
//   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 = tags?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);
    if(data.data.data){
      const renderData = data.data.data.list.map((item,index)=>{
        return {
            ...item,
            key:item['id'],
          //   editable: true,
        }
      })
      setarr(renderData);
    }else {
      console.log('data为null');
      return
    }
    setpages({
        'currPage':data.data.data.currPage,
        'totalPage':data.data.data.totalPage,
        'totalCount':data.data.data.totalCount,
    });
    setifRender(false);
    setifRender(true);
  }

  const callbackFromChild = (data)=>{
        set_ifRenderModal(true);
        setitem(data);
        setifEdit(true);
        thisForm.current&&thisForm.current.resetFields();
        modalNode.current&&modalNode.current.showModal();
  }

  const deleteCallback = (record)=>{
    // console.log({record});
    delCheckItem([record.checkItemId]).then(res=>{
        if(res&&res.data.msg=="success"){
                getData();
        }
    })
  }

  const handleAdd=()=>{
    set_ifRenderModal(true);
    setifEdit(false);
    //初始化表单
    if(arr.length>0){
      setitem(arr[0]);
    }else{
      setitem({
        "checkModeList": "", // 查核方式 必填（暂时写死，需要考虑（下拉框选择））
        "checkItemName": "",// 查核项目名称 必填
        "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();
      //清空表单缓存
      // resetForm();
  

      if(!ifEdit){
        const param = {
            "checkModeList":formData.checkModeList, // 查核方式 必填（暂时写死，需要考虑（下拉框选择））
            "name":formData.checkItemName,// 查核项目名称 必填
            "relatedRules":formData.relatedRules, // 相关条文
            "rightAnswerImage":formData.rightAnswerImage, // 正确答案图片url 上传图片接口待定
            "rightAnswerText": formData.rightAnswerText,// 正确答案文字  
            // "score":formData.score,//查核项分数
        }
        addCheckItem(param).then(res=>{
          if(res&&res.data.msg=="success"){
           getData();
          }
        })
      }
      if(ifEdit){
        const currentEditItem = item;
        console.log({currentEditItem});
        const paramForCheckItemresult = {
          "checkItemId":item.checkItemId,   // 查核项id
          "id":item.attrId,
          "score":parseFloat(formData.score),  // 分数
          "itemAttrs":formData.itemAttrs,
        }
        const param =/^[a-zA-Z]+$/.test(formData.checkModeList)?{
           //checkModeList为code的情况下
            "id":item.checkItemId,
            "checkModeList": formData.checkModeList, // 查核方式
            "name":formData.checkItemName, // 名称必填
            "relatedRules":formData.relatedRules, // 相关条文
            "rightAnswerImage":formData.rightAnswerImage,// 应知应会图片url
            "rightAnswerText":formData.rightAnswerText, // 应知应会文字
        }:{
            "id":item.checkItemId,
            "name":formData.checkItemName, // 名称必填
            "relatedRules":formData.relatedRules, // 相关条文
            "rightAnswerImage":formData.rightAnswerImage,// 应知应会图片url
            "rightAnswerText":formData.rightAnswerText, // 应知应会文字
        }

        // console.log({param,item,paramForCheckItemresult})
        // return;
        const editCheckItemFunc = ()=>{
          editCheckItem(param).then(res=>{
            if(res&&res.data.msg=="success"){
              getData({page:pages.currPage});
             }
          });
        }
      
        //不存在查核属性id时，调用查核属性新增
        if(item.attrId){ 
          addCheckItemCheckResult(paramForCheckItemresult).then(res=>{
            if(res&&res.data.msg=="success"){
              console.log('查核项结果配置成功');
              editCheckItemFunc();
              // getData({page:pages.currPage});
            }
          });
        }else {
          const param = {
            'checkItemId':item.checkItemId,
            'itemAttr':formData.itemAttrs,
            'score':formData.score
          }
          addCheckItemAttr(param).then(res=>{
            if(res&&res.data.msg=="success"){
              editCheckItemFunc();
            }
          });
        }
      }
  }

  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:''
       });
  }

  const resetForm = ()=>{
      thisForm.current.resetFields();
      formNode.current.state.BindStatus='';
      formNode.current.state.BindPointStatus='';
      formNode.current.clearData();
      // set_ifRenderModal(false);
  }

  const handleCancelCallback = ()=>{
      console.log('modal_closed');
      resetForm();
      set_ifRenderModal(false);
      // set_ifRenderModal(true);

  }


  
  useEffect(()=>{
    getData();
  },[]);

  return ( 
    <div className="app-container">
          <h1>查核项管理</h1>
          <ModalWrap width={1000} ref={modalNode} show={ifShowDialog} handleOkCallback={commitForm} handleCancelCallback={handleCancelCallback} >
           {
            ifRenderModal&&<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;