import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input, Select, Modal, message, Tree, Spin, Tabs, Switch, Upload, Icon, InputNumber } from 'antd';
import {
  extendRule,
  initFilter,
  getOnlyPropertyData,
  extendInclude,
  getDataFieldValue,
  setDataFieldValue,
  guid,
  empty,
} from "../../../utils/common";
import DropDownPagination from '../../common/DropDownPaginationEx';
import FormPage from '../../FormPage';
import Editor from 'react-umeditor';
import config from '../../../config';

const Option = Select.Option;
const { TextArea } = Input;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;

class EmOrderEditPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: '工程确认单编辑',
      data: {},
      oldData: {},
      btns: [],
      processDetail: {},
      hiddenFields: {},
      treeData: [],
      treeSelectedKeys: [],
      isProcessChange: false,
      expandedKeys: [],
      sopVisible: false,
    };
  };

  componentDidMount() {
    this.props.form.resetFields();
    this.loadData();
  }

  componentWillReceiveProps(NextProps) {
    if (NextProps.custom.emOrderEditClick) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          emOrderEditClick: false
        },
      });
    }
  }

  loadData = () => {
    const { data, formId } = this.props;
    const { id } = data ? data : {};

    if (id) {
      const json = initFilter(this.props.login.OrgId);
      extendRule(json, 'ID', 1, id);
      extendInclude(json, 'Nav_Mould');
      extendInclude(json, 'Nav_TestFixture');
      extendInclude(json, 'Nav_Product');
      extendInclude(json, 'Nav_EmOrderProcess.Nav_Process');
      extendInclude(json, 'Nav_EmOrderProcess.Nav_FQCWorkStage');
      extendInclude(json, 'Nav_EmOrderProcess.Nav_PQCWorkStage');
      extendInclude(json, 'Nav_EmOrderProcess.Nav_Details.Nav_Procedure');
      extendInclude(json, 'Nav_EmOrderProcess.Nav_Details.Nav_Unit');
      extendInclude(json, 'Nav_EmOrderProcess.Nav_Details.Nav_PQCWorkStage');
      extendInclude(json, 'Nav_EmOrderSopFiles.Nav_ImgFile');
      this.props.dispatch({
        type: 'EMemOrder/getEmOrder',
        payload: json,
        onComplete: (ret) => {
          if (ret) {
            const updateLoadFileList = [];
            if (ret.Nav_EmOrderSopFiles) {
              ret.Nav_EmOrderSopFiles.map(t => {
                updateLoadFileList.push({
                  uid: t.ID,
                  name: t.Nav_ImgFile ? t.Nav_ImgFile.FILE_NAME : '未知文件',
                  status: 'done',
                  response: { Data: t.IMG_FILE_ID, file: t },
                });
              });
            }
            this.setState({
              data: ret,
              oldData: { ...ret },
              isProcessChange: false,
              processDetail: {},
              treeSelectedKeys: [],
              expandedKeys: [],
              treeData: [],
              hiddenFields: {},
              updateLoadFileList: updateLoadFileList,
              selectedTreeNode: {}
            }, () => {
              this.setPdtProcesFieldVisiable();
              this.getTreeData();
            });
          }
        }
      });
    }
    if (this.props.data.isShow) {
      this.setState({
        title: '工程确认单查看',
      })
    }

    if (formId) {
      const btnJson = initFilter(this.props.login.OrgId, '', 'NUM', 0);
      extendRule(btnJson, 'PAGE_CUSTOM_FORM_ID', 1, formId);
      this.props.dispatch({
        type: 'EMemOrder/getBtnList',
        payload: btnJson,
        onComplete: (ret) => {
          if (ret) {
            this.setState({
              btns: ret,
            });
          }
        }
      });
    }
  };


  getBtns = (code) => {
    if (this.props.data.isShow) return;
    if (this.state.btns) {
      return this.state.btns.map(item => {
        if (item.CODE === code) {
          if (item.BTN_TYPE == 1) {
            return <Button type={item.CSS} icon={item.ICON} style={{ 'marginLeft': '10px' }} key={item.ID} onClick={() => this.handleOk()}>{item.LABEL}</Button>;
          }
          else if (item.BTN_TYPE == 7) {
            if (item.CLICK_EVENT == 'addNode') {
              return <Button type="primary" style={{ 'marginLeft': '10px' }} key={item.ID} onClick={() => this.addTreeNode()}>{item.LABEL}</Button>;
            }
            else if (item.CLICK_EVENT == 'removeNode') {
              return <Button type="danger" style={{ 'marginLeft': '10px' }} key={item.ID} onClick={() => this.removeTreeNode()}>{item.LABEL}</Button>;
            }

            else if (item.CLICK_EVENT == 'clearSelect') {
              return <Button type="primary" style={{ 'marginLeft': '10px' }} key={item.ID} onClick={() => this.doSelectTreeNode(null)}>{item.LABEL}</Button>;
            }

          }
        }
      });
    }
  };

  getUpdateData = () => {
    const data = { ...this.state.data };
    if (this.state.processDetail && this.state.processDetail.ID) {
      if (!data.Nav_EmOrderProcess) {
        data.Nav_EmOrderProcess = {
          ORG_ID: this.props.login.OrgId,
          ID: guid(),
          Nav_Details: [],
        };
      };
      if (!data.Nav_EmOrderProcess.Nav_Details) {
        data.Nav_EmOrderProcess.Nav_Details = [];
      };
      let details = [];
      data.Nav_EmOrderProcess.Nav_Details.map(t => {
        if (t.ID != this.state.processDetail.ID) {
          details.push(t);
        };
      });
      if (this.state.processDetail.ID) {
        details.push(this.state.processDetail);
      }
      data.Nav_EmOrderProcess.Nav_Details = details;
    };
    let updateData = getOnlyPropertyData(data);
    if (data.Nav_EmOrderProcess) {
      updateData.Nav_EmOrderProcess = getOnlyPropertyData(data.Nav_EmOrderProcess);
      if (data.Nav_EmOrderProcess.Nav_Details) {
        updateData.Nav_EmOrderProcess.Nav_Details = [];
        data.Nav_EmOrderProcess.Nav_Details.map(t => {
          let tmp = getOnlyPropertyData(t);
          updateData.Nav_EmOrderProcess.Nav_Details.push(tmp);
        });
      }
    }
    if (data.Nav_PdtBOMs) {
      updateData.Nav_PdtBOMs = [];
      data.Nav_PdtBOMs.map(t => {
        let tmp = getOnlyPropertyData(t);
        updateData.Nav_PdtBOMs.push(tmp);
      });
    };

    if (this.state.updateLoadFileList) {
      updateData.Nav_EmOrderSopFiles = [];
      this.state.updateLoadFileList.map(t => {
        if (t.response) {
          if (t.response.file) {
            updateData.Nav_EmOrderSopFiles.push(getOnlyPropertyData(t.response.file));
          } else if (t.response.Data) {
            updateData.Nav_EmOrderSopFiles.push({
              IMG_FILE_ID: t.response.Data,
              ORG_ID: this.props.login.OrgId,
            });
          }
        }
      });
    }
    return updateData;
  }

  handleOk = () => {
    const { form, dispatch, data } = this.props;
    const { validateFieldsAndScroll } = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let updateData = this.getUpdateData();

      let isError = false;

      if (!updateData.Nav_EmOrderProcess || !updateData.Nav_EmOrderProcess.Nav_Details || updateData.Nav_EmOrderProcess.Nav_Details.length == 0) {
        message.error('请填写工艺路线信息');
        isError = true;
      };

      if (updateData.Nav_EmOrderProcess) {
        if (empty(getDataFieldValue(updateData, 'Nav_EmOrderProcess.NAME', ''))) {
          message.error('请填写工艺路线名称');
          isError = true;
        }
        if (empty(getDataFieldValue(updateData, 'Nav_EmOrderProcess.CODE', ''))) {
          message.error('请填写工艺路线编号');
          isError = true;
        }
        if (getDataFieldValue(updateData, 'Nav_EmOrderProcess.FQC_AUTO_INSPEC', false) && getDataFieldValue(updateData, 'Nav_EmOrderProcess.FQC_INSPEC_TYPE', 0) == 1 && getDataFieldValue(updateData, 'Nav_EmOrderProcess.FQC_INSPEC_QTY', 0) == 0) {
          message.error('请填写送检数量');
          isError = true;
        }

        if (updateData.Nav_EmOrderProcess.Nav_Details) {
          updateData.Nav_EmOrderProcess.Nav_Details.map(t => {
            if (t.PROCEDURE_ID === undefined || t.PROCEDURE_ID === null || t.PROCEDURE_ID == '') {
              message.error('请填写工序' + t.NAME + '工序');
              isError = true;
            };
            if (t.UNIT_ID === undefined || t.UNIT_ID === null || t.UNIT_ID == '') {
              message.error('请填写工序' + t.NAME + '单位');
              isError = true;
            };
            if (getDataFieldValue(t, 'PROCEDURE_TYPE', 0) == 1 && empty(getDataFieldValue(t, 'ORDER_FIELD', 0))) {
              message.error('请填写工序' + t.NAME + '对应字段');
              isError = true;
            };
            if (getDataFieldValue(t, 'PQC_AUTO_INSPEC', false) && getDataFieldValue(t, 'PQC_INSPEC_TYPE', 0) == 1
              && getDataFieldValue(t, 'PQC_INSPEC_QTY', 0) == 0) {
              message.error('请填写工序' + t.NAME + '送检数量');
              isError = true;
            };
            if (getDataFieldValue(t, 'PROCEDURE_TYPE', 0) == 0 && getDataFieldValue(t, 'CONVERT_RATIO', 0) == 0) {
              message.error('请填写工序' + t.NAME + '换算比率');
              isError = true;
            };

          });
        }

      }

      if (isError) return;


      dispatch({
        type: 'EMemOrder/fullUpdate',
        payload: updateData,
        onComplete: (ret) => {
          if (ret) {
            if (data.close) {
              data.close();
            }
            message.success('执行成功');
          }
        }
      });
    })
  };


  getInnerControl = ({ fieldType, data, field, defaultValue, extendData, enumsName, inputDataApi, onSelectValue, onChange, inpuNavField, onFilter, disabled }) => {
    if (fieldType == 1) {//文本
      if (inputDataApi) {
        return <DropDownPagination inputDataApi={inputDataApi} fieldName={field} inpuNavField={inpuNavField}
          data={data} onSelect={onSelectValue} disabled={this.props.data.isShow} onFilter={onFilter} />
      }
      return <Input value={getDataFieldValue(data, field, defaultValue)} onChange={(e) => { onChange(e, field) }} disabled={this.props.data.isShow || disabled} />
    }
    else if (fieldType == 2) {//时间
    }

    else if (fieldType == 3) {//下拉
      let options = extendData ? extendData.split(',') : [];
      if (enumsName) {
        const allEnums = this.props.app.enums;
        if (allEnums && allEnums[enumsName] && allEnums[enumsName].options) {
          allEnums[enumsName].options.forEach((n, i) => {
            options.push(n.label + ':' + n.value);
          })
        }
      }
      return <Select value={getDataFieldValue(data, field, defaultValue)} onChange={(e) => { onChange(e, field) }} disabled={this.props.data.isShow || disabled}>
        {
          options.map((item, key) => {
            let paris = item.split(":");
            return <Option key={key} value={+paris[1]}>{paris[0]}</Option>
          })
        }
      </Select>
    }

    else if (fieldType == 4) {//单选
    }

    else if (fieldType == 5) {//多选
      return <Switch checkedChildren="是" unCheckedChildren="否" checked={getDataFieldValue(data, field, defaultValue)} onChange={(e) => { onChange(e, field) }} disabled={this.props.data.isShow || disabled} />
    }
    else if (fieldType == 6) {//长文本
      return <TextArea rows={4} value={getDataFieldValue(data, field, defaultValue)} onChange={(e) => { onChange(e, field) }} disabled={this.props.data.isShow || disabled} />
    }
    else if (fieldType == 7) {//数值
      return <InputNumber value={getDataFieldValue(data, field, defaultValue)} min={0} onChange={(e) => { onChange(e, field) }} disabled={this.props.data.isShow || disabled} />
    }
    else if (fieldType == 8) {//富文本编辑
      return (<Editor ref="editor" icons={[" undo redo |  underline | ", "forecolor backcolor "]}
        value={getDataFieldValue(data, field, defaultValue)}
        onChange={(e) => { onChange(e, field) }} />)
    }

    return <Input value={getDataFieldValue(data, field, defaultValue)} onChange={(e) => { onChange(e, field) }} disabled={this.props.data.isShow || disabled} />
  }


  getControl = (params) => {
    if (this.state.hiddenFields && this.state.hiddenFields[params.field]) return;
    const formItemLayout = params.formItemLayout ? params.formItemLayout : {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    return <Col key={params.field} span={params.span ? params.span : 12}>
      <Form.Item
        label={<>{params.isRequery ? <span style={{ color: 'red' }}>*</span> : null}{params.label}</>}
        {...formItemLayout}
      >
        {this.getInnerControl(params)}
      </Form.Item>
    </Col>
  };

  showFields = (data) => {
    if (data) {
      return data.map(item => {
        return this.getControl(item);
      });
    }
  };

  showTreeNode = (data) => {
    if (!data || data.length == 0)
      return;
    return data.map((item) => {
      if (item) {
        let title = item.title;
        return (
          <TreeNode title={title} key={item.ID.toString()} data={item} isLeaf={!(item.Children && item.Children.length)}>
            {this.showTreeNode(item.Children)}}
          </TreeNode>
        );
      };
    });
  };

  showSelectedTreeNode = () => {
    const node = this.state.selectedTreeNode;
    if (node) {
      return node.title;
    }
    return '空';
  };


  doSelectTreeNode = (node) => {
    let processDetail = {};
    const data = { ...this.state.data };
    if (this.state.processDetail && this.state.processDetail.ID) {
      if (!data.Nav_EmOrderProcess) {
        data.Nav_EmOrderProcess = {
          ORG_ID: this.props.login.OrgId,
          ID: guid(),
          Nav_Details: [],
        };
      };
      if (!data.Nav_EmOrderProcess.Nav_Details) {
        data.Nav_EmOrderProcess.Nav_Details = [];
      };
      let details = [];
      data.Nav_EmOrderProcess.Nav_Details.map(t => {
        if (t.ID != this.state.processDetail.ID) {
          details.push(t);
        };
      });
      details.push(this.state.processDetail);
      data.Nav_EmOrderProcess.Nav_Details = details;
    };
    if (data.Nav_EmOrderProcess && data.Nav_EmOrderProcess.Nav_Details && node) {
      data.Nav_EmOrderProcess.Nav_Details.map(t => {
        if (t.ID === node.ID) {
          processDetail = t;
        }
      });
    }
    this.setState({
      selectedTreeNode: node,
      data: data,
      processDetail: processDetail,
      treeSelectedKeys: node ? [node.ID.toString()] : [],
    }, () => {
      this.setPdtProcesDetailFieldVisiable();
    });
  };

  onSelectTreeNode = (selectedKeys, e) => {
    const node = e.node.props.data;
    this.doSelectTreeNode(this.state.selectedTreeNode && node.ID == this.state.selectedTreeNode.ID ? null : node);
  };


  doSelectNodeById = (data, id) => {
    if (data) {
      data.map(t => {
        if (t.ID === id) {
          this.doSelectTreeNode(t);
        }
        else if (t.Children) {
          this.doSelectNodeById(t.Children, id);
        }
      });
    }
  };


  addTreeNode = () => {
    const data = { ...this.state.data };
    const processDetailData = {
      ORG_ID: this.props.login.OrgId,
      ID: guid(),
      NAME: '新增节点',
      NUM: 99999,
      TYPE: 0,
      PRO_TYPE: 0,
      PARENT_ID: this.state.selectedTreeNode && this.state.selectedTreeNode.ID ? this.state.selectedTreeNode.ID : null,
    };
    if (!data.Nav_EmOrderProcess) {
      data.Nav_EmOrderProcess = {
        ORG_ID: this.props.login.OrgId,
      };
    };
    if (!data.Nav_EmOrderProcess.Nav_Details) {
      data.Nav_EmOrderProcess.Nav_Details = [];
    }
    let num = 0;
    data.Nav_EmOrderProcess.Nav_Details.forEach((n, i) => {
      if (n.NUM && n.NUM > num) {
        num = n.NUM;
      }
    });
    num++;
    processDetailData.NUM = num;
    data.Nav_EmOrderProcess.Nav_Details.push(processDetailData);
    this.setState({
      data: data,
      isProcessChange: true,
      expandedKeys: [processDetailData.PARENT_ID],
    }, () => {
      this.getTreeData(() => {
        this.doSelectNodeById(this.state.treeData, processDetailData.ID);
        this.setState({
          expandedKeys: [],
        });
      });
    });
  };

  removeTreeNode = () => {
    if (this.state.selectedTreeNode) {
      const tmp = { ...this.state.data };
      if (tmp.Nav_EmOrderProcess && tmp.Nav_EmOrderProcess.Nav_Details) {
        const result = [];
        tmp.Nav_EmOrderProcess.Nav_Details.map(t => {
          if (t.ID != this.state.selectedTreeNode.ID) {
            result.push(t);
          };
        });
        tmp.Nav_EmOrderProcess.Nav_Details = result;
      };
      this.setState({
        data: tmp,
        isProcessChange: true,
        processDetail: {},
      }, () => {
        this.getTreeData(() => {
          if (this.state.treeData && this.state.treeData.length > 0) {
            this.doSelectTreeNode(this.state.treeData[0]);
          }
          else {
            this.doSelectTreeNode(null);
          }
        });
      });
    };
  };


  doGetTreeNode = (data, parentNode, list, parentId) => {
    if (data) {
      let tmp = [];
      data.map(item => {

        if (item.PARENT_ID === parentId) {
          if (this.state.processDetail && this.state.processDetail.ID && item.ID == this.state.processDetail.ID) {
            tmp.push(this.state.processDetail);
          }
          else {
            tmp.push(item);
          }
        };
      });
      if (tmp.length > 0) {
        tmp.sort((x, y) => (parseInt(x.NUM) > parseInt(y.NUM)) ? 1 : -1);
        const result = [];
        tmp.map(t => {
          const node = {
            title: t.NAME ? (t.NUM + '/' + t.NAME) : (t.Nav_Procedure == null ? '新增节点' : (t.NUM + '/' + t.Nav_Procedure.NAME)),
            ID: t.ID,
          };
          result.push(node);
          this.doGetTreeNode(data, node, list, t.ID);
        });
        if (parentNode) {
          parentNode.Children = result;
        } else {
          result.map(t => {
            list.push(t);
          });
        };
      };
    };
  };


  getTreeData = (complete) => {
    const treeData = [];
    if (this.state.data.Nav_EmOrderProcess && this.state.data.Nav_EmOrderProcess.Nav_Details) {
      this.doGetTreeNode(this.state.data.Nav_EmOrderProcess.Nav_Details, null, treeData, null);
    };
    this.setState({
      treeData: treeData,
    }, () => {
      if (typeof complete === 'function') {
        complete(treeData);
      };
    });
  };


  setPdtProcesFieldVisiable = () => {
    const data = this.state.data;
    const hiddenFields = { ...this.state.hiddenFields };
    const isFqc = getDataFieldValue(data, 'Nav_EmOrderProcess.IS_FQC', false);
    const autoInspec = getDataFieldValue(data, 'Nav_EmOrderProcess.FQC_AUTO_INSPEC', false);
    hiddenFields['Nav_EmOrderProcess.FQC_TYPE'] = !isFqc;
    hiddenFields['Nav_EmOrderProcess.Nav_FQCWorkStage.NAME'] = !isFqc;
    hiddenFields['Nav_EmOrderProcess.FQC_AUTO_INSPEC'] = !isFqc;
    hiddenFields['Nav_EmOrderProcess.FQC_INSPEC_TYPE'] = !(isFqc && autoInspec);
    hiddenFields['Nav_EmOrderProcess.FQC_INSPEC_QTY'] = !(isFqc && autoInspec);
    hiddenFields['Nav_EmOrderProcess.FQC_INSPEC_QTY_OVER'] = !(isFqc && autoInspec);
    this.setState({
      hiddenFields: hiddenFields,
    });
  };

  setPdtProcesDetailFieldVisiable = () => {
    const data = this.state.processDetail;
    const hiddenFields = { ...this.state.hiddenFields };
    const type = getDataFieldValue(data, 'PROCEDURE_TYPE', 0);
    const isPqc = getDataFieldValue(data, 'IS_PQC', false);
    const autoInspec = getDataFieldValue(data, 'PQC_AUTO_INSPEC', false);
    const isProType = getDataFieldValue(data, 'PRO_TYPE', 0);
    hiddenFields['PQC_TYPE'] = !isPqc;
    hiddenFields['Nav_PQCWorkStage.NAME'] = !isPqc;
    hiddenFields['PQC_AUTO_INSPEC'] = !isPqc;
    hiddenFields['PQC_INSPEC_TYPE'] = !(isPqc && autoInspec);
    hiddenFields['PQC_INSPEC_QTY'] = !(isPqc && autoInspec);
    hiddenFields['PQC_INSPEC_QTY_OVER'] = !(isPqc && autoInspec);
    hiddenFields['ORDER_FIELD'] = type != 1;
    hiddenFields['PRO_TYPE'] = type != 0;
    hiddenFields['TIME_UNIT'] = type != 0;
    hiddenFields['CONVERT_RATIO'] = type != 0;
    hiddenFields['STANDARD_TIME'] = type != 0;
    hiddenFields['IS_PQC'] = type != 0;
    hiddenFields['BOOK_BAD'] = type != 0 || isProType == 0;


    this.setState({
      hiddenFields: hiddenFields,
    });
  };

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


  render() {
    const { form, location, dispatch, match, loading } = this.props;
    const { getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue } = form;
    const { data, processDetail } = this.state;

    const onHeadRowChange = (e, field) => {
      if (e == null || e == undefined) return;
      const value = e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e);
      const tmp = { ...this.state.data };
      setDataFieldValue(tmp, field, value);
      this.setState({
        data: tmp,
      }, () => {
        if (field == 'Nav_EmOrderProcess.IS_FQC' || field == 'Nav_EmOrderProcess.FQC_AUTO_INSPEC') {
          this.setPdtProcesFieldVisiable();
        }
      });
    };

    const onProcessDetailChange = (e, field) => {
      if (e == null || e == undefined) return;
      const value = e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e);
      let tmp = { ...this.state.processDetail };
      setDataFieldValue(tmp, field, value);
      this.setState({
        processDetail: tmp,
      }, () => {
        if (field == 'NUM') {
          this.getTreeData();
        };

        if (field == 'IS_PQC' || field == 'PQC_AUTO_INSPEC' || field == 'PROCEDURE_TYPE') {
          this.setPdtProcesDetailFieldVisiable();
        };

      });
    };


    const onWorkstageFilter = ({ params }) => {
      extendRule(params, 'TYPE', 1, 2);
    };



    const onSelectFQCWorkstage = (param) => {
      const paramData = param.data;
      if (paramData && paramData.length > 0 || param.isClear) {
        const tmp = { ...this.state.data };
        const workstageId = paramData && paramData.length > 0 ? paramData[0] : null;
        const workstageName = paramData && paramData.length > 0 ? paramData[1] : '';
        setDataFieldValue(tmp, 'Nav_EmOrderProcess.FQC_WORKSTAGE_ID', workstageId);
        setDataFieldValue(tmp, 'Nav_EmOrderProcess.Nav_FQCWorkStage.NAME', workstageName);
        this.setState({
          data: tmp,
        });
      };
    };

    const onSelectPQCWorkstage = (param) => {
      const paramData = param.data;
      if (paramData && paramData.length > 0 || param.isClear) {
        let tmp = { ...this.state.processDetail };
        const workstageId = paramData && paramData.length > 0 ? paramData[0] : null;
        const workstageName = paramData && paramData.length > 0 ? paramData[1] : '';
        setDataFieldValue(tmp, 'PQC_WORKSTAGE_ID', workstageId);
        setDataFieldValue(tmp, 'Nav_PQCWorkStage.NAME', workstageName);
        this.setState({
          processDetail: tmp,
        });
      };
    };

    const onSelectPQCProdure = (param) => {
      const paramData = param.data;
      const record = param.record;
      if (paramData && paramData.length > 0 || param.isClear) {
        let tmp = { ...this.state.processDetail };
        const prcedureId = paramData && paramData.length > 0 ? paramData[0] : null;
        const prcedureName = paramData && paramData.length > 0 ? paramData[1] : '';
        setDataFieldValue(tmp, 'PROCEDURE_ID', prcedureId);
        setDataFieldValue(tmp, 'Nav_Procedure.NAME', prcedureName);
        setDataFieldValue(tmp, 'NAME', prcedureName);
        if (record) {
          const fields = ['PROCEDURE_TYPE', 'ORDER_FIELD', 'PRO_TYPE', 'BOOK_BAD', 'CONVERT_RATIO', 'STANDARD_TIME', 'TIME_UNIT', 'UNIT_ID', 'Nav_Unit.NAME',
            'PQC_AUTO_INSPEC', 'PQC_INSPEC_TYPE', 'PQC_INSPEC_QTY', 'PQC_INSPEC_QTY_OVER', 'IS_PQC', 'PQC_TYPE', 'PQC_WORKSTAGE_ID', 'REMARK',
            'Nav_PQCWorkStage.NAME', 'EXT_PROCEDURE_CODE'];
          fields.forEach((n, i) => {
            setDataFieldValue(tmp, n, getDataFieldValue(record, n));
          });
        }
        this.setState({
          processDetail: tmp,
        }, () => {
          this.setPdtProcesDetailFieldVisiable();
        });
      };
    };
    const onSelectUnit = (param) => {
      const paramData = param.data;
      const record = param.record;
      if (paramData && paramData.length > 0 || param.isClear) {
        let tmp = { ...this.state.processDetail };
        const unitId = paramData && paramData.length > 0 ? paramData[0] : null;
        const unitName = paramData && paramData.length > 0 ? paramData[1] : '';
        setDataFieldValue(tmp, 'UNIT_ID', unitId);
        setDataFieldValue(tmp, 'Nav_Unit.NAME', unitName);
        this.setState({
          processDetail: tmp,
        }, () => {
          this.setPdtProcesDetailFieldVisiable();

        });
      };
    };
    const onSelectMould = ({ record }) => {
      let tmp = { ...this.state.data };
      setDataFieldValue(tmp, 'Nav_Mould.NAME', getDataFieldValue(record, 'NAME'));
      setDataFieldValue(tmp, 'MOULD_ID', getDataFieldValue(record, 'ID'));
      this.setState({
        data: tmp,
      });
    };

    const onSelectTestFixture = ({ record }) => {
      let tmp = { ...this.state.data };
      setDataFieldValue(tmp, 'Nav_TestFixture.NAME', getDataFieldValue(record, 'NAME'));
      setDataFieldValue(tmp, 'TEST_FIXTURE_ID', getDataFieldValue(record, 'ID'));
      this.setState({
        data: tmp,
      });
    };

    const pdtOrderFields = [
      { fieldType: 1, data: data, label: '工程确认单', field: 'CODE', defaultValue: '', disabled: true },
      { fieldType: 1, data: data, label: '交期', field: 'DUE_TIME', defaultValue: '', disabled: true },
      { fieldType: 1, data: data, label: '数量', field: 'QTY', defaultValue: '', disabled: true },
      { fieldType: 1, data: data, label: '品号', field: 'Nav_Product.CODE', defaultValue: '', disabled: true },
      { fieldType: 1, data: data, label: '品名', field: 'Nav_Product.NAME', defaultValue: '', disabled: true },
      { fieldType: 7, data: data, label: '交货方式', field: 'Nav_Product.SPLIT_QTY', disabled: true },
      { fieldType: 1, data: data, label: '单PCS尺寸', field: 'Nav_Product.PCS_SIZE', disabled: true },
      { fieldType: 7, data: data, label: '拼版长', field: 'Nav_Product.SPLIT_LENGTH', disabled: true },
      { fieldType: 7, data: data, label: '拼版宽', field: 'Nav_Product.SPLIT_WIDTH', disabled: true },
      { fieldType: 1, data: data, label: '工艺路线', field: 'Nav_EmOrderProcess.Nav_Process.NAME', defaultValue: '', disabled: true },
      {
        fieldType: 1, data: data, label: '模具', field: 'Nav_Mould.NAME', defaultValue: '', inputDataApi: 'FM/Product/OrderPaged',
        onSelectValue: onSelectMould, onFilter: ({ params }) => { extendRule(params, 'PRODUCT_TYPE', 1, 4); extendRule(params, 'ENABLE_STATUS', 1, 0); }
      },
      {
        fieldType: 1, data: data, label: '测试架', field: 'Nav_TestFixture.NAME', defaultValue: '', inputDataApi: 'FM/Product/OrderPaged',
        onSelectValue: onSelectTestFixture, onFilter: ({ params }) => { extendRule(params, 'PRODUCT_TYPE', 1, 5); extendRule(params, 'ENABLE_STATUS', 1, 0); }
      },
      { fieldType: 3, data: data, label: '紧急程度', field: 'EMERGENCY_DEGREE_TYPE', defaultValue: null, enumsName: 'WOPdtOrderEmergencyDegreeTypeEnum', onChange: onHeadRowChange },
    ]


    const pdtProcessFields = [
      { fieldType: 1, data: data, label: '工艺路线名称', field: 'Nav_EmOrderProcess.NAME', defaultValue: '', isRequery: true, onChange: onHeadRowChange },
      { fieldType: 1, data: data, label: '工艺路线代码', field: 'Nav_EmOrderProcess.CODE', defaultValue: '', isRequery: true, onChange: onHeadRowChange },
      { fieldType: 5, data: data, label: '成品检验', field: 'Nav_EmOrderProcess.IS_FQC', defaultValue: false, onChange: onHeadRowChange },
      { fieldType: 3, data: data, label: '检验方式', field: 'Nav_EmOrderProcess.FQC_TYPE', defaultValue: null, extendData: '全检:0,抽检:1', onChange: onHeadRowChange },
      { fieldType: 1, data: data, label: '成检中心', field: 'Nav_EmOrderProcess.Nav_FQCWorkStage.NAME', defaultValue: '', inputDataApi: 'FM/WorkStage/OrderPaged', onSelectValue: onSelectFQCWorkstage, inpuNavField: 'ID,NAME', onFilter: onWorkstageFilter },
      { fieldType: 5, data: data, label: '自动送检', field: 'Nav_EmOrderProcess.FQC_AUTO_INSPEC', defaultValue: false, onChange: onHeadRowChange },
      { fieldType: 3, data: data, label: '自动送检方式', field: 'Nav_EmOrderProcess.FQC_INSPEC_TYPE', defaultValue: null, extendData: '全部:0,批量:1', onChange: onHeadRowChange },
      { fieldType: 7, data: data, label: '送检数量', field: 'Nav_EmOrderProcess.FQC_INSPEC_QTY', defaultValue: 0, onChange: onHeadRowChange },
      { fieldType: 5, data: data, label: '是否检验溢出', field: 'Nav_EmOrderProcess.FQC_INSPEC_QTY_OVER', defaultValue: null, onChange: onHeadRowChange },
      { fieldType: 5, data: data, label: 'QA检验', field: 'Nav_EmOrderProcess.IS_QA', defaultValue: false, onChange: onHeadRowChange },
    ]

    const pdtProcessDetailFields = [
      { fieldType: 1, data: processDetail, label: '工序', field: 'Nav_Procedure.NAME', defaultValue: '', inputDataApi: 'FM/Procedure/OrderPaged', onSelectValue: onSelectPQCProdure, inpuNavField: 'ID,NAME,Nav_Unit.NAME' },
      { fieldType: 3, data: processDetail, label: '工序类型', field: 'PROCEDURE_TYPE', defaultValue: 0, onChange: onProcessDetailChange, extendData: '实际工序:0,显示工序:1,打印工序:2' },
      { fieldType: 3, data: processDetail, label: '工序类别', field: 'PRO_TYPE', defaultValue: false, onChange: onProcessDetailChange, extendData: '计划工序:0,报工工序:1,计划且报工:2' },
      { fieldType: 1, data: processDetail, label: '显示字段', field: 'ORDER_FIELD', defaultValue: '', onChange: onProcessDetailChange },
      { fieldType: 7, data: processDetail, label: '换算比率', field: 'CONVERT_RATIO', defaultValue: 1, isRequery: true, onChange: onProcessDetailChange },
      { fieldType: 7, data: processDetail, label: '标准工时', field: 'STANDARD_TIME', defaultValue: 1, onChange: onProcessDetailChange },
      { fieldType: 5, data: processDetail, label: '可报异常', field: 'BOOK_BAD', defaultValue: false, onChange: onProcessDetailChange },
      { fieldType: 3, data: processDetail, label: '工时单位', field: 'TIME_UNIT', defaultValue: 0, onChange: onProcessDetailChange, extendData: '小时:0,分钟:1,秒:2' },
      { fieldType: 1, data: processDetail, label: '单位', field: 'Nav_Unit.NAME', defaultValue: '', inputDataApi: 'FM/Unit/OrderPaged', isRequery: true, onSelectValue: onSelectUnit, inpuNavField: 'ID,NAME' },
      { fieldType: 5, data: processDetail, label: 'PQC检验', field: 'IS_PQC', defaultValue: false, onChange: onProcessDetailChange },
      { fieldType: 3, data: processDetail, label: '检验方式', field: 'PQC_TYPE', defaultValue: null, extendData: '全检:0,抽检:1', onChange: onProcessDetailChange },
      { fieldType: 1, data: processDetail, label: '检验中心', field: 'Nav_PQCWorkStage.NAME', defaultValue: '', inputDataApi: 'FM/WorkStage/OrderPaged', onSelectValue: onSelectPQCWorkstage, inpuNavField: 'ID,NAME', onFilter: onWorkstageFilter },
      { fieldType: 5, data: processDetail, label: '自动送检', field: 'PQC_AUTO_INSPEC', defaultValue: false, onChange: onProcessDetailChange },
      { fieldType: 3, data: processDetail, label: '自动送检方式', field: 'PQC_INSPEC_TYPE', defaultValue: null, extendData: '全部:0,批量:1', onChange: onProcessDetailChange },
      { fieldType: 7, data: processDetail, label: '送检数量', field: 'PQC_INSPEC_QTY', defaultValue: 0, onChange: onProcessDetailChange },
      { fieldType: 5, data: processDetail, label: '是否检验溢出', field: 'PQC_INSPEC_QTY_OVER', defaultValue: null, onChange: onProcessDetailChange },
      { fieldType: 1, data: processDetail, label: '外部工序编号', field: 'EXT_PROCEDURE_CODE', defaultValue: '', onChange: onProcessDetailChange },
      { fieldType: 7, data: processDetail, label: '工艺顺序', field: 'NUM', defaultValue: 0, onChange: onProcessDetailChange },
      {
        fieldType: 8, data: processDetail, label: '备注', field: 'REMARK', defaultValue: '', onChange: onProcessDetailChange, span: 24, formItemLayout: {
          labelCol: { span: 3 },
          wrapperCol: { span: 17 },
        }
      },
    ]

    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.`);
        }
      },
    };



    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };





    return (
      <Spin spinning={loading.global}>
        <div>
          <Form>
            <Modal visible={this.state.sopVisible} maskClosable={false} onCancel={this.handleSopCloseModal} footer={false} width={"86%"}>
              <FormPage formCode={'WO012'} data={this.state.sopData} />
            </Modal>
            <Row style={{ 'marginTop': '20px' }}>
              {
                this.showFields(pdtOrderFields)
              }
              <Col span={12}>
                <Form.Item
                  label={'SOP'}
                  {...formItemLayout}
                >
                  <Upload {...uploadSopProps}>
                    <Button disabled={this.props.data.isShow}>
                      <Icon type="upload" /> 上传SOP文件
                    </Button>
                  </Upload>
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label={'备注'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('REMARK', {
                    initialValue: data.REMARK,
                  })(<TextArea rows={4} placeholder={'请输入备注'} disabled={this.props.data.isShow} onChange={(e) => { onHeadRowChange(e, 'REMARK'); }} />)}
                </Form.Item>
              </Col>
            </Row>

            <Row style={{ 'marginTop': '20px' }}>
              <Col style={{ textAlign: 'right' }}>
                {
                  this.getBtns('save')
                }

              </Col>
            </Row>
            <Row style={{ 'marginTop': '20px' }}>
              <Tabs defaultActiveKey="1" >
                <TabPane tab="工艺路线明细" key="1">
                  <Row style={{ 'marginTop': '10px' }}>
                    {
                      this.showFields(pdtProcessFields)
                    }
                  </Row>
                  <Row style={{ 'marginTop': '10px' }}>
                    <Col span={8}>
                      <div>
                        {
                          this.getBtns('addNode')
                        }
                        {
                          this.getBtns('removeNode')
                        }

                      </div>
                      <div style={{ 'marginTop': '10px', 'marginBottom': '10px' }}>
                        <label >当前选中：<span style={{ 'fontSize': 'large' }}>{this.showSelectedTreeNode()}</span></label>
                      </div>
                      <div>
                        <Tree showLine onSelect={this.onSelectTreeNode} selectedKeys={this.state.treeSelectedKeys} >
                          {this.showTreeNode(this.state.treeData)}
                        </Tree>
                      </div>
                    </Col>
                    <Col span={16}>
                      {
                        this.state.processDetail.ID && this.showFields(pdtProcessDetailFields)
                      }
                    </Col>
                  </Row>
                </TabPane>

              </Tabs>
            </Row>

          </Form>
        </div>
      </Spin>
    );
  }

}

EmOrderEditPage.propTypes = {
};

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