import * as supplierDetailService from '../../services/supplier/suppliers';
import * as bpmService from '../../services/common/bpm';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { message } from 'antd';
import { dataUtils, formUtils, enums } from '@utils';
import { Modal } from 'antd';
import { batchDownload } from '../../services/common/file';

const { customMsg, viewMode, } = enums;

export default {
  namespace: 'supplierAdjust',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    mode: 'create',
    modalVisible: false,
    modalItem: [],
    qualifyVisible: false,
    qualifyItem: [],
    filterParams: {},
    formData: {},
    addrContacts: [],
    addrQualifys: [],
    edpPbSupp: {
      gysylsx: [],
    },
    srmSuppAdd: {
    },
    items: [],
    advice: '',
    taskId: '',
    currentSuppId: 0,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(() => {
        const match = pathToRegexp('/lifecycle/supp-mgmt/adjust/:id').exec(location.pathname);
        if (match) {
          dispatch({ type: 'clean' });
          dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
          dispatch({ type: 'queryItem' });
          dispatch({ type: 'query', payload: match[1] });
        }
      });
    },
  },

  effects: {

    * query({ payload }, { call, put, select }) {
      let { mode, currentSuppId } = yield select(({ supplierAdjust }) => supplierAdjust);
      const formData = yield call(supplierDetailService.getSingle, payload);

      const { id: suppId, approveStatus } = formData.data.edpPbSupp;

      if (formData.success) {

        formData.data.edpPbSupp.approveTime = dataUtils.dtm(formData.data.edpPbSupp.approveDate);
        formData.data.edpPbSupp.approveDate = '';

        yield put({
          type: 'updateState',
          payload: {
            formData: formData.data,
            addrContacts: formData.data.addrContacts || [],
            addrQualifys: formData.data.addrQualifys || [],
            edpPbSupp: formData.data.edpPbSupp || {},
            srmSuppAdd: formData.data.srmSuppAdd || {},
            mode,
          },
        });
      } else {
        throw formData;
      }
    },

    * queryItem({ payload }, { call, select, put }) {
      const seItem = JSON.parse(sessionStorage.getItem(`udc_ITEM`));
      if (seItem) {
        yield put({
          type: 'updateState',
          payload: {
            items: seItem,
          },
        });
      } else {
        const data = yield call(supplierDetailService.getItem, { ...payload });
        if (data.success) {
          yield put({
            type: 'updateState',
            payload: {
              items: data.data,
            },
          });
          sessionStorage.setItem(`udc_ITEM`, JSON.stringify(data.data));
        } else {
          throw data;;
        }
      }
    },

    * save({ payload }, { select, call, put }) {

      const edpPbSupp = yield select(({ supplierAdjust }) => supplierAdjust.edpPbSupp);
      const srmSuppAdd = yield select(({ supplierAdjust }) => supplierAdjust.srmSuppAdd);
      const addrQualifys = yield select(({ supplierAdjust }) => supplierAdjust.addrQualifys);
      const addrContacts = yield select(({ supplierAdjust }) => supplierAdjust.addrContacts);
      const { mode } = yield select(({ supplierAdjust }) => supplierAdjust);

      for (let qualify of addrQualifys) {
        if (qualify.id < 0) {
          qualify.attachRepo = Math.abs(qualify.id);
          qualify.id = '';
        }
      }

      const newData = {
        addrQualifys,
        addrContacts,
        edpPbSupp: {
          ...formUtils.standardiseFormData(edpPbSupp),
          prcType: mode === 'updateQualify' ? '1' : '0'
        },
        srmSuppAdd: {
          ...formUtils.standardiseFormData(srmSuppAdd),
          ...formUtils.standardiseFormData(payload),
        },
        submitted: payload.submitted
      };

      const callApi = mode === 'adjust' ? supplierDetailService.adjust : supplierDetailService.update;
      const data = yield call(callApi, newData);

      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'cancel' });
      } else {
        throw data;
      }
    },

    * approve({ payload }, { put, call, select }) {
      const formData = yield select(({ supplierAdjust }) => supplierAdjust.formData);
      const advice = yield select(({ supplierAdjust }) => supplierAdjust.advice);
      // if(!advice.trim()){
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
      if (data.success) {
        yield put({ type: 'cancel' });
      } else {
        throw data;
      }
    },

    * reject({ payload }, { put, call, select }) {
      const formData = yield select(({ supplierAdjust }) => supplierAdjust.formData);
      const edpPbSupp = yield select(({ supplierAdjust }) => supplierAdjust.edpPbSupp);
      const advice = yield select(({ supplierAdjust }) => supplierAdjust.advice);
      if(!advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(bpmService.doReject, { taskId: formData.taskId, advice });
      if (data.success) {
        const rejectedData = yield call(supplierDetailService.reject, edpPbSupp.id);
        if (rejectedData.success) {
          yield put({ type: 'cancel' });
        } else {
          throw data;
        }
      } else {
        throw data;

      }
    },

    * cancel({ payload }, { put }) {
      yield put(routerRedux.goBack());
    },

    * clean({ payload }, { select, put }) {
      const { user } = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          mode: 'create',
          modalVisible: false,
          modalItem: [],
          qualifyVisible: false,
          qualifyItem: [],
          filterParams: {},
          formData: {},
          addrContacts: [],
          addrQualifys: [],
          edpPbSupp: {
            gysylsx: [],
          },
          srmSuppAdd: {
          },
          items: [],
          advice: '',
          taskId: '',
          currentSuppId: user.entId,
        },
      });
    },

    * qualify({ }, { call, put, select }) {
      const edpPbSupp = yield select(({ supplierAdjust }) => supplierAdjust.edpPbSupp);
      const addrQualifys = yield select(({ supplierAdjust }) => supplierAdjust.addrQualifys);
      const gysxzList = edpPbSupp.gysxz;
      const data = yield call(supplierDetailService.requireQualifys, { gysxzList });
      if (data.success) {
        for (let i in data.data) {
          let hadAddrQualifys = false;
          for (let key of addrQualifys) {
            if (data.data[i] == key.qualifyType) {
              hadAddrQualifys = true;
            }
          }
          if (!hadAddrQualifys) {
            let newData = {
              id: dataUtils.getRandomInt(-99999999, -1),
              qualifyType: data.data[i]
            };
            yield put({
              type: 'addRow',
              payload: { ...newData },
            });
            message.error('缺少资质类型');
            return;
          }
        };
        yield put({
          type: 'save',
          payload: { submitted: true }
        });
      } else {
        throw data;
      }
    },

    * modal({ payload }, { call, put, }) {
      const data = yield call(supplierDetailService.getStaffs, payload.id);
      if (data.success) {
        yield put({
          type: 'showModal',
          payload: {
            modalItem: data.data.rows,
          },
        });
      } else {
        throw data;
      }
    },

    * qualifyModal({ payload }, { call, put, select }) {
      const edpPbSupp = yield select(({ supplierAdjust }) => supplierAdjust.edpPbSupp);
      const data = yield call(supplierDetailService.getQualifys, edpPbSupp.addrNo);
      if (data.success) {
        yield put({
          type: 'showQualifyModal',
          payload: {
            qualifyItem: data.data,
          },
        });
      } else {
        throw data;
      }
    },

    * download({ payload }, { call }) {
      const data = yield call(supplierDetailService.pack, payload.downloadData);
      if (data.success) {
        yield call(batchDownload, data.response)
      } else {
        throw data;
      }
    },
  },

  reducers: {
    addRow(state, { payload }) {
      const { addrQualifys } = state;
      const newList = addrQualifys.slice();
      // newList.unshift(payload)
      newList.push(payload);
      return {
        ...state,
        addrQualifys: newList,
      };
    },

    deleteRow(state, { payload }) {
      const { addrQualifys } = state;
      const newList = addrQualifys.slice().filter(item => item.id !== payload);
      return {
        ...state,
        addrQualifys: newList,
      };
    },

    deleteAddrRow(state, { payload }) {
      const { addrContacts } = state;
      const newAddrContacts = addrContacts.slice().filter(item => item.id !== payload);
      return {
        ...state,
        addrContacts: newAddrContacts,
      };
    },

    updateCell(state, { payload }) {
      const { addrQualifys } = state;
      const newList = addrQualifys.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      if (key === 'relateItem') {
        newList[index]['relateToItemId'] = value.id;
        newList[index]['itemCode'] = value.code;
        newList[index]['itemName'] = value.name;
      }
      return {
        ...state,
        addrQualifys: newList,
      };
    },

    addAddrRow(state, { payload }) {
      const { addrContacts } = state;
      const newAddrContacts = addrContacts.slice();
      // newList.unshift(payload)
      newAddrContacts.push(payload);
      return {
        ...state,
        addrContacts: newAddrContacts,
      };
    },

    updateUploadState(state, { payload }) {
      const { addrQualifys } = state;
      const { index, file, attachChangeFlag } = payload;
      addrQualifys[index].viewFiles = file;
      addrQualifys[index].attachRepo = `supplierQualify${addrQualifys[index].id}`;
      addrQualifys[index].attachChangeFlag = attachChangeFlag;
      return {
        ...state,
        addrQualifys,
      };
    },

    deleteUploadState(state, { payload }) {
      const { addrQualifys } = state;
      const { index, file } = payload;
      addrQualifys[index].viewFiles = file;
      addrQualifys[index].attachRepo = '';
      return {
        ...state,
        addrQualifys,
      };
    },

    updateAddrCell(state, { payload }) {
      const { addrContacts } = state;
      const newAddrContacts = addrContacts.slice();
      const { key, index, value } = payload;
      newAddrContacts[index][key] = value;
      return {
        ...state,
        addrContacts: newAddrContacts,
      };
    },

    querySuccess(state, action) {
      const { addrQualifys, total, filterParams } = action.payload;
      return {
        ...state,
        addrQualifys,
        total,
        filterParams,
      };
    },

    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    updateForm(state, { payload }) {
      const { key, value } = payload;
      const edpPbSupp = state.edpPbSupp;
      const newEdpPbSupp = Object.assign({}, edpPbSupp);
      newEdpPbSupp[key] = value;
      return {
        ...state,
        edpPbSupp: newEdpPbSupp,
      };
    },

    updateAddForm(state, { payload }) {
      const { key, value } = payload;
      const srmSuppAdd = state.srmSuppAdd;
      const newSrmSuppAdd = Object.assign({}, srmSuppAdd);
      newSrmSuppAdd[key] = value;
      return {
        ...state,
        srmSuppAdd: newSrmSuppAdd,
      };
    },

    showModal(state: object, { payload }) {
      return { ...state, ...payload, modalVisible: true };
    },

    hideModal(state: object, { payload }) {
      return {
        ...state, ...payload, modalVisible: false, modalItem: [],
      };
    },

    showQualifyModal(state: object, { payload }) {
      return { ...state, ...payload, qualifyVisible: true };
    },

    hideQualifyModal(state: object, { payload }) {
      return {
        ...state, ...payload, qualifyVisible: false, qualifyItem: [],
      };
    },

  },

};
