import { connect } from 'dva';
import { Form,Button,Upload,Icon,Modal,message } from 'antd';
import { extendRule, initFilter, extendInclude, guid, getOnlyPropertyData } from "../../../utils/common";
import EditComponent from '../../../baseComponents/EditComponent';
import FormPage from '../../FormPage';
import config from "../../../config";
class ProductProcessPage extends EditComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
    };
  };

  onAfterHeadDropDownSelect(params) {
    super.onAfterHeadDropDownSelect(params);
    
    let { colConfig } = params ? params : {};
    if (colConfig.field === 'Nav_Process.NAME') {
      let processId = this.getFieldValue('PROCESS_ID');
      if (processId && this.props.data && this.props.data.isNew) {
        let stateData = this.state.data;
        let json = initFilter(stateData.ORG_ID, '', 'NUM', 1);
        extendRule(json, 'PROCESS_ID', 1, processId);
        extendInclude(json, 'Nav_Procedure');
        extendInclude(json, 'Nav_Unit');
        this.props.dispatch({
          type: 'FMProcess/getProcessDetailList',
          payload: json,
          onComplete: (ret) => {
            const data = [];
            if (ret && ret.length) {
              ret.forEach((t, index) => {
                data.push({
                  ID: guid(),
                  ORG_ID: stateData.ORG_ID,
                  PROCEDURE_ID: t.PROCEDURE_ID,
                  UNIT_ID: t.UNIT_ID,
                  NUM: t.NUM,
                  NAME: t.NAME,
                  CONVERT_RATIO: t.CONVERT_RATIO,
                  ROW_NO: (index + 1),
                  EXT_PROCEDURE_CODE: t.EXT_PROCEDURE_CODE,
                  CONVERT_RATIO_NUMERATOR: t.CONVERT_RATIO_NUMERATOR,
                  CONVERT_RATIO_DENOMINATOR: t.CONVERT_RATIO_DENOMINATOR,
                  PROCEDURE_TYPE: t.PROCEDURE_TYPE,
                  IS_SPIT_PROCEDURE: t.IS_SPIT_PROCEDURE,
                  IS_COMPOSE_PROCEDURE: t.IS_COMPOSE_PROCEDURE,
                  IS_AUTO_BOOKING: t.IS_AUTO_BOOKING,
                  IS_CAN_SN_REWORK:t.IS_CAN_SN_REWORK,
                  ORDER_FIELD: t.ORDER_FIELD,
                  PRO_TYPE: t.PRO_TYPE,
                  STANDARD_TIME: t.STANDARD_TIME,
                  TIME_UNIT: t.TIME_UNIT,
                  IS_PQC: t.IS_PQC,
                  OUTSIDE: t.OUTSIDE,
                  PQC_TYPE: t.PQC_TYPE,
                  PQC_WORKSTAGE_ID: t.PQC_WORKSTAGE_ID,
                  PQC_AUTO_INSPEC: t.PQC_AUTO_INSPEC,
                  PQC_INSPEC_TYPE: t.PQC_INSPEC_TYPE,
                  PQC_INSPEC_QTY: t.PQC_INSPEC_QTY,
                  PQC_INSPEC_QTY_OVER: t.PQC_INSPEC_QTY_OVER,
                  REMARK: t.REMARK,
                  BOOK_BAD: t.BOOK_BAD,
                  Nav_Procedure: {
                    NAME: t.Nav_Procedure && t.Nav_Procedure.NAME ? t.Nav_Procedure.NAME : '',
                    CODE: t.Nav_Procedure && t.Nav_Procedure.CODE ? t.Nav_Procedure.CODE : ''
                  },
                  Nav_Unit: {
                    NAME: t.Nav_Unit && t.Nav_Unit.NAME ? t.Nav_Unit.NAME : ''
                  }
                })
              });
            }

            this.setEditTableData({ editCode: 'productProcessDetail', data: data, isAppend: false });
          }
        });
      }
    }
  }
  onBeforeEdit(params){
    super.onBeforeEdit(params);
    const {isNew,isCopy,copySrcData}=params?params:{};
    const updateLoadFileList=[];
    if(this.state.data&&this.state.data.Nav_Files){ 
      this.state.data.Nav_Files.forEach(t=>{ 
          updateLoadFileList.push({
            uid: t.ID,
            name: t.name?t.name:(t.Nav_ImgFile?t.Nav_ImgFile.FILE_NAME:'未知文件'),
            status: t.status?t.status:'done',
            response: {Data:t.IMG_FILE_ID,file:t},
          }); 
      });
    } 
    this.setState({
      updateLoadFileList,
    })
  }
  
  onBeforeSaveHandleRecord(params){
    super.onBeforeSaveHandleRecord(params);
    const {editCode,record,srcRecord}=params?params:{};
    if(editCode==='1'){
      if(!record.Nav_Files){
        record.Nav_Files=[];
      }
      if(srcRecord.Nav_Files){
        srcRecord.Nav_Files.forEach(t=>{
          record.Nav_Files.push(getOnlyPropertyData(t));
        })
      }
      if(this.state.updateLoadFileList) {
        this.state.updateLoadFileList.forEach(t => {
          if (t.response) {
            if (record.Nav_Files.filter(t1 => t1.IMG_FILE_ID === t.response.Data).length == 0) {
              record.Nav_Files.push({
                ID: guid(),
                IMG_FILE_ID: t.response.Data,
                ORG_ID: this.props.login.OrgId,
                PROCESS_SOP_ID:  this.state.data?this.state.data.ID:null,
                name: t.name,
                status: t.status,
              });
            }
          }
        });
      }
      if(record.Nav_Files)
        record.Nav_Files.forEach(t1=>{
        if(!this.state.updateLoadFileList|| this.state.updateLoadFileList.filter(t=>t.response&&t1.IMG_FILE_ID===t.response.Data).length==0){
          t1.IS_DELETED=true;
        }
      });
    }
  }

  handleSopClick= async function (recordId,ids){
    await this.props.dispatch({
      type: 'custom/save',
      payload: {
        ['sopViewClick'+recordId]:true,
      },
    });
  };

  handleSopShowModal = (file) => {
    this.setState({
      sopData:{ids:file.response.Data,id:file.response.Data},
      sopVisible: true
    },()=>{
      this.handleSopClick(file.response.Data,file.response.Data);
    });
  };
  handleSopCloseModal = () => {
    this.setState({
      sopVisible: false
    });
  };
  
  onRenderHeadControl(params){
    const {colConfig,record}=params;
    if(colConfig.field==='Nav_Files.Nav_ImgFile.FILE_NAME'){
      const that=this;
      const uploadSopProps = {
        name: 'file',
        action: config.serviceHost('api/PF/File/UploadFileToImage'),
        data:{OrgId:this.props.login.OrgId},
        fileList:this.state.updateLoadFileList,
        onPreview:function(file){
          that.handleSopShowModal(file);
        },
        onChange(info) {
          that.setState({
            updateLoadFileList:info.fileList,
          });
      
          if (info.file.status !== 'uploading') {
            // that.setState({
            //   updateLoadFileList:info.fileList,
            // });
        
          }
          if (info.file.status === 'done') {
            message.success(`${info.file.name} file uploaded successfully`);
          } else if (info.file.status === 'error') {
            message.error(`${info.file.name} file upload failed.`);
          }
        },
      };
      return <>
          <Modal visible={this.state.sopVisible} maskClosable={false} onCancel={this.handleSopCloseModal} footer={false} width={"86%"}>
              <FormPage formCode={'WO012'} data={this.state.sopData}/>
          </Modal>
       <Upload {...uploadSopProps}>
        <Button>
          <Icon type="upload" /> 上传SOP文件
        </Button>
      </Upload>
      </>
    }
    return super.onRenderHeadControl(params);
  }
}


export default connect(({ login, loading, editPage, custom, app }) => ({ login, loading, editPage, custom, app }))(Form.create()(ProductProcessPage));
