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

export default {

  namespace: 'qualify',

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

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

  effects: {

    * query({ payload }, { call, put, select }) {
      const formData = yield call(qualifyService.getSingle, payload);
      //const currentUser = yield select(({ app }) => app.user);
      if (formData.success) {

        //const partList = yield call(qualifyService.getSingle, { faultCode: formData.data.faultCode });
        // for (let key in formData.data.addrQualifys) {
        //   const repo = formData.data.addrQualifys[key].attachRepo;
        //   const data = yield call(qualifyService.fetchData, repo);
        //   const fileList = data.data;
        //   if (fileList.length > 0) {
        //     formData.data.addrQualifys[key].viewFiles = data.data;
        //     formData.data.addrQualifys[key].hisFiles = data.data;
        //     formData.data.addrQualifys[key].file = data.data[0]['fileName'];
        //   }
        // }

        const currentUser = yield select(({ app }) => app.user);
        formData.data.authField = currentUser.user.authField;

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

      } else {
        throw formData;
      }
    },

    * queryItem({ payload }, { call, select, put }) {
      const data = yield call(qualifyService.getItem, { ...payload });
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            items: data.data,
          },
        });
      } else {
        throw data;
      }
    },

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

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

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

      if (edpPbSupp.approveStatus === '01') {
        message.error('该供应商当前状态不能提交');
        return 0;
      }

      edpPbSupp.approveDate = '';

      const newData = {
        addrQualifys: addrQualifys,
        addrContacts: addrContacts,
        edpPbSupp: {
          ...formUtils.standardiseFormData(edpPbSupp),
        },
        srmSuppAdd: {
          ...formUtils.standardiseFormData(srmSuppAdd),
          ...formUtils.standardiseFormData(payload),
        },
      };

      const data = yield call(qualifyService.update, newData);

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

    * qualify({ }, { call, put, select }) {
      const edpPbSupp = yield select(({ qualify }) => qualify.edpPbSupp);
      const addrQualifys = yield select(({ qualify }) => qualify.addrQualifys);
      const gysxzList = edpPbSupp.gysxz;
      const data = yield call(qualifyService.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',
        });
      } else {
        throw data;
      }
    },

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

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          modalVisible: false,
          qualifyVisible: false,
          qualifyItem: [],
          mode: 'create',
          filterParams: {},
        },
      });
    },

    * qualifyModal({ payload }, { call, put, select }) {
      const edpPbSupp = yield select(({ qualify }) => qualify.edpPbSupp);
      const data = yield call(qualifyService.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, total } = state;
      const newList = addrQualifys.slice();
      // newList.unshift(payload)
      newList.push(payload);
      return {
        ...state,
        addrQualifys: newList,
      };
    },

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

    deleteAddrRow(state, { payload }) {
      let { addrContacts, total } = 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;
      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,
      };
    },

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

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

  },

};
