import { connect } from 'dva';
import { Button, Row, Col, Form, Radio, Select, Table, Checkbox } from 'antd';
import { extendRule, initFilter, extendInclude, guid } from "../../../utils/common";
import EditComponent from '../../../baseComponents/EditComponent';
import _ from "lodash";

class ReworkPdtOrderPage extends EditComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
    };
  };
  onAfterHeadDropDownSelect(params) {
    super.onAfterHeadDropDownSelect(params);

    let { value, record, colConfig, thisRef } = params ? params : {};
    if (colConfig.field === 'Nav_PdtOrder.PDT_CODE') {
      const pdtOrderId = this.getFieldValue('PDT_ORDER_ID');
      if (pdtOrderId) {
        const stateData = this.state.data;
        let json = initFilter(stateData.ORG_ID, '', 'CREATE_TIME', 1);
        extendRule(json, 'PDT_ORDER_ID', 1, pdtOrderId);
        extendRule(json, 'STATE', 1, 13);
        this.props.dispatch({
          type: 'reworkPdtOrder/GetReworkSN',
          payload: json,
          onComplete: (ret) => {
            const data = [];
            if (ret && ret.length) {
              ret.forEach((t, index) => {
                data.push({
                  ID: guid(),
                  SN_ID: t.ID,
                  Nav_SN: t,
                  ORG_ID: stateData.ORG_ID,
                  ROW_NO: (index + 1)
                })
              });
            }

            this.setREWORK_QTY(data);
            this.setEditTableData({ editCode: 'sn', data: data, isAppend: false });
          }
        });

        _.remove(json.FilterGroup.Rules, (o) => { return o.Field === "STATE" });
        extendInclude(json, 'Nav_Line.Nav_LineStages.Nav_Workstage');
        this.props.dispatch({
          type: 'reworkPdtOrder/GetReworkJobEntities',
          payload: json,
          onComplete: (ret) => {
            const data = [];
            if (ret && ret.length) {
              ret = _.uniqBy(ret, 'LINE_ID');
              ret.forEach((t, index) => {
                if (t.LINE_ID) {
                  let temp = data.filter(t1 => t1.EXT_PROCEDURE_CODE === t.Nav_Line.EXT_PROCEDURE_CODE)[0];
                  if (!temp) {
                    temp = {
                      ID: guid(),
                      ORG_ID: stateData.ORG_ID,
                      ROW_NO: (index + 1),
                      IS_SELECTED: false
                    }

                    data.push(temp)
                  }

                  let tempLines = temp.CAN_SELECT_LINES ? temp.CAN_SELECT_LINES : '';
                  if (tempLines !== '') {
                    tempLines += ',';
                  }
                  temp.CAN_SELECT_LINES = tempLines + (t.Nav_Line.ID + ':' + t.Nav_Line.NAME);
                }

              });
            }

            this.setEditTableData({ editCode: 'workline', data, isAppend: false });
          }
        });

        this.setEditTableData({ editCode: 'workstage', data: [], isAppend: false });
      }
    }
  }

  onRenderRowControl(params) {
    if (this.props.data && this.props.data.isReview) {
      params.colConfig.disabled = true;
    }
    else {
      params.colConfig.disabled = false;
    }

    const { editCode, colConfig, record, text, parentId, parentRecord } = params ? params : {};
    if (editCode === 'workstage' && colConfig.field === 'Workstage') {
      if (record.Nav_Line && record.Nav_Line.Nav_LineStages && record.Nav_Line.Nav_LineStages.length) {
        const options = [];
        record.Nav_Line.Nav_LineStages.forEach(t => {
          options.push({ label: t.Nav_Workstage.NAME, value: t.STAGE_ID });
        });

        const values = record.DETAIL ? record.DETAIL.split(',') : [];
        return <Checkbox.Group
          options={options}
          value={values}
          disabled={params.colConfig.disabled}
          onChange={(e) => {
            if (e) {
              record.DETAIL = e.join(',');
            }
            else {
              record.DETAIL = null;
            }
            this.saveRowRecord({ record, editCode });
          }}
        />
      }
      return null;
    } else if (editCode === 'workline' && colConfig.field === 'Nav_Line.NAME') {
      if (record.CAN_SELECT_LINES) {
        const temps = record.CAN_SELECT_LINES.split(',');
        const options = [];
        temps.forEach(t => {
          if (t) {
            options.push({ label: t.split(':')[1], value: t.split(':')[0] });
          }
        });

        //const values = record.LINE_ID ? record.DETAIL.split(',') : [];
        return <Radio.Group
          options={options}
          value={record.LINE_ID}
          disabled={params.colConfig.disabled}
          onChange={(e) => {
            const v = e.target.value;
            const oldV = record.LINE_ID;
            record.IS_SELECTED = true;
            record.LINE_ID = v;
            this.saveRowRecord({
              record, editCode, onComplete: () => {
                if (oldV) {
                  const workstageData = this.getEditTableData({ editCode: 'workstage' });
                  const tempData = [];
                  workstageData.forEach(t => {
                    if (t.LINE_ID !== oldV) {
                      tempData.push(t);
                    }
                  });
                  this.setEditTableData({
                    editCode: 'workstage', data: tempData, isAppend: false, onComplete: () => {
                      if (v) {
                        this.getWorkstageByLine(v);
                      }
                    }
                  });
                }
                else if (v) {
                  this.getWorkstageByLine(v);
                }
              }
            });
          }}
        />
      }
      return null;
    }

    return super.onRenderRowControl(params);
  }

  getWorkstageByLine = (lineId) => {
    const stateData = this.state.data;
    let json = initFilter(stateData.ORG_ID, '', '', 1);
    extendRule(json, 'ID', 1, lineId);
    extendInclude(json, 'Nav_LineStages.Nav_Workstage');
    this.props.dispatch({
      type: 'reworkPdtOrder/getWorkstageByLine',
      payload: json,
      onComplete: (ret) => {
        if (ret && ret.Nav_LineStages && ret.Nav_LineStages.length) {

          const stateData = this.state.data;
          const data = [];
          data.push({
            ID: guid(),
            LINE_ID: ret.ID,
            REWORK_PDT_ORDER_ID: stateData.ID,
            ORG_ID: stateData.ORG_ID,
            Nav_Line: ret
          })
          this.setEditTableData({ editCode: 'workstage', data, isAppend: true });
        }

      }
    });
  }

  getEditConfig(params) {
    var config = super.getEditConfig(params);
    if (this.props && this.props.data && this.props.data.isEdit) {
      if (config.columns && config.columns.length > 0) {
        var pdrOrderColumn = _.find(config.columns, (o) => {
          return o.field === "Nav_PdtOrder.PDT_CODE"
        })

        if (pdrOrderColumn) {
          pdrOrderColumn.disabled = 'disabled';
        }
      }
    }

    if (this.props.data && this.props.data.isReview) {
      if (config.btns && config.btns.length > 0) {
        _.forEach(config.btns, (btn) => {
          btn.disabled = 'disabled';
        })
      }

      if (config.columns && config.columns.length > 0) {
        _.forEach(config.columns, (column) => {
          column.disabled = 'disabled';
        })
      }
    }

    if ((config.editCode === 'work' || config.editCode === 'processDetail') && !this.props.data.isReview) {
      return {};
    }
    return config;
  }

  onAfterAddRow(params) {
    super.onAfterAddRow(params);
    if (params.editCode === 'sn') {
      this.state.data.REWORK_QTY = this.state.data.REWORK_QTY + 1;
    }
  }

  onAfterDeleteRow(params) {
    super.onAfterDeleteRow(params);
    if (params.editCode === 'sn') {
      let sns = params.data;
      this.setREWORK_QTY(sns);
    }
  }

  setREWORK_QTY(data) {
    let newData = _.cloneDeep(this.state.data);
    newData.REWORK_QTY = data.length;

    let self = this;
    self.setState({ data: newData })
  }
}


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