import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { dataUtils, enums, formUtils } from '@utils';
import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import * as bpmService from '../../../services/common/bpm';
import * as tenderService from '../../../services/source/tenders';

const { entType, resultCode, customMsg, viewMode ,approveStatus} = enums;
export default {

  namespace: 'tenderDetails',

  state: {
    formData: {},
    list: [],
    mlist: [],
    mode: 'create',
    suppFlag: false,
    from: '',
    taskKey: '',
    taskId: '',
    readOnly: false,
    advice: '',
    remoteCfg: null,
    user: null,
    saveBtnFlag: false,
    bidBtnFlag: false,
    attachRepo:null,
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen(() => {
        const match = pathToRegexp('/source-mgmt/bid-mgmt/tenders/tenders/:id').exec(location.pathname);
        // console.log('match==>',match);
        if (match) {
          if (match[1] === 'create') {
            dispatch({ type: 'clean' });
            dispatch({ type: 'newCreate' });
            return 0;
          }
          dispatch({ type: 'readonly', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
          dispatch({ type: 'query', payload: { id: match[1] } });
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // console.log("payload==>", payload)
      // 角色判断 soum_bm_ts_save/      soum_bm_ts_bid
      let { saveBtnFlag, bidBtnFlag} = yield select(({ tenderDetails }) => tenderDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_ts_save';
          })) {
          saveBtnFlag = true;
        }
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_ts_bid';
          })) {
          bidBtnFlag = true;
        }
      }
      const formData = yield call(tenderService.getSingle, payload.id);
      let { mode } = yield select(({ tenderDetails }) => tenderDetails);
      if (formData.success) {
        // console.log('formData==>',formData)
        const currentUser = yield select(({ app }) => app.user);

        if (formData.data.prcId && mode === 'approval') {
          //判断登录用户是否为当前处理人
          const status = yield call(bpmService.doCheckActived, formData.data.prcId);
          if (!(status.success && status.data)) {
            Modal.error({
              title: customMsg.NOT_ACTIVE_HANDLER,//您不是当前处理人
            });
            mode = viewMode.VIEW;
          }
        }

        let suppFlag = entType.SUPP === currentUser.user.entType;
        yield put({
          type: 'updateState',
          payload: {
            suppFlag,
            user: currentUser.user,
            saveBtnFlag,
            bidBtnFlag
          },
        });
        // 初始配置文件参数
        const params = {
          defId: 'Bidding:',
          nodeId: suppFlag ? 'supp' : (formData.data.prcId ? (mode === viewMode.VIEW ? 'initiator' : formData.data.taskKey) : 'initiator'),
          mode: suppFlag ? viewMode.VIEW : (mode === viewMode.UPDATE ? 'edit' : mode),
        };
        // console.log('param==>',params)
        // 远程文件配置
        const cfgData = yield call(bpmService.getFormCfg, params);
        // console.log('cfgdata==>',cfgData)
        if (cfgData.success) {
          yield put({
            type: 'updateState',
            payload: {
              remoteCfg: cfgData.data,
            },
          });
        } else {
          throw cfgData;
        }
        const fData = formData.data;
        if (fData.itemList) {
          // fData.itemList.map((i) => {
          //   i.estimatedAmtStr = i.estimatedAmt
          //     ? parseFloat(i.estimatedAmt).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          //     : null;
          // });
        }

        if (fData.suppList) {
          fData.suppList.map(supp => {
            supp.id = dataUtils.getRandomInt(-99999999, -1)
          })
        }

        if (fData.itemList) {
          fData.itemList.map(item => {
            item.id = dataUtils.getRandomInt(-99999999, -1)
          })
        }


        yield put({
          type: 'updateState',
          payload: {
            mode,
            formData: fData ? fData : {},
            list: fData.suppList ? fData.suppList : [],
            mlist: fData.itemList ? fData.itemList : [],
            attachRepo: fData.attachRepo,
          },
        });
      } else {
        message.error(formData.message);
      }
    },

    * readonly({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      if (payload.mode === 'approval' || payload.mode === 'view') {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
            readOnly: true,
            advice: '',
          },
        });
      } else {
        yield put({ type: 'updateState', payload });
      }
    },

    * newCreate({ payload }: ReduxAction, { call, put, select, take }: ReduxSagaEffects) {
      // 角色判断 soum_bm_ts_save/      soum_bm_ts_bid
      let { saveBtnFlag, bidBtnFlag} = yield select(({ tenderDetails }) => tenderDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_ts_save';
          })) {
          saveBtnFlag = true;
        }
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_ts_bid';
          })) {
          bidBtnFlag = true;
        }
      }
      const currentUser = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          user: currentUser,
          saveBtnFlag,
          bidBtnFlag
        },
      });
      // 初始配置文件参数
      const params = {
        defId: 'Bidding:',
        nodeId: 'initiator',
        mode: viewMode.CREATE,
      };
      // 远程文件配置
      const cfgData = yield call(bpmService.getFormCfg, params);
      // console.log('cfgdata==>',cfgData)
      if (cfgData.success) {
        yield put({
          type: 'updateState',
          payload: {
            remoteCfg: cfgData.data,
          },
        });
      } else {
        throw cfgData;
      }
      yield put({
        type: 'updateState',
        payload: {
          formData: {
            docStatus: '0',
          },
          list: [],
          mlist: [],
          suppFlag: (entType.SUPP === currentUser.user.entType) ? true : false,
          attachRepo: 'tender'+dataUtils.getRandomInt(1, 9999999),
        },
      });
    },

    * save({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const formData = yield select(({ tenderDetails }) => tenderDetails.formData);
      const currentUser = yield select(({ app }) => app.user.user);
      // console.log('currentUser', currentUser)
      const { submitted, approveFlag, } = payload;
      formData.submitted = submitted;
      formData.approveFlag = approveFlag;
      const attachRepo = yield select(({ tenderDetails }) => tenderDetails.attachRepo);
      formData.attachRepo = attachRepo;
      const { mode } = yield select(({ tenderDetails }) => tenderDetails);
      if (mode === 'create') {
        formData.id = null;
      }
      // console.log('formData==>', formData)
      const list = yield select(({ tenderDetails }) => tenderDetails.list);
      // console.log('list==>', list)
      // if (!list[0].suppName) {
      //   message.error('供应商 必填');
      // }
      const mlist = yield select(({ tenderDetails }) => tenderDetails.mlist);
      // console.log('mlist==>', mlist)

      const newData = {
        ...formUtils.standardiseFormData(formData),
        suppList: formData.biType === '1' ? [] : list,
        itemList: mlist,
      };
      // console.log('newData', newData)
      const advice = yield select(({ tenderDetails }) => tenderDetails.advice);
      if(approveFlag && approveFlag !== 'approve' && !advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(tenderService.create, newData);
      if (data.success) {
        if(approveFlag === 'approve'){
          const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
          if (data.success) {
            const data1 = yield call(tenderService.update, { id: formData.id, approveStatus: approveStatus.APPROVED });
            if (data1.success) {
              message.success(resultCode.OK);
              yield put({ type: 'cancel' });
            } else {
              throw data1;
            }
          } else {
            throw data;
          }
        }else if(approveFlag === 'reject'){
          const data = yield call(bpmService.doReject, { taskId: formData.taskId, advice });
          if (data.success) {
            const data1 = yield call(tenderService.update, { id: formData.id, approveStatus: approveStatus.REJECT });
            if (data1.success) {
              message.success(resultCode.OK);
              yield put({ type: 'cancel' });
            } else {
              throw data1;
            }
          } else {
            throw data;
          }
        }else{
          message.success(resultCode.OK);
          yield put({ type: 'redirect' });
        }
      } else {
        message.error(data.message);
      }
    },

    * reSubmit({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const formData = yield select(({ tenderDetails }) => tenderDetails.formData);
      const currentUser = yield select(({ app }) => app.user.user);
      // console.log('currentUser', currentUser)
      if (formData.recCompany) {
        formData.recCompanyId = formData.recCompany.id;
      }
      formData.submitted = false;
      // console.log('formData==>', formData)
      const list = yield select(({ tenderDetails }) => tenderDetails.list);
      // console.log('list==>', list)
      // if (!list[0].suppName) {
      //   message.error('供应商 必填');
      // }
      const mlist = yield select(({ tenderDetails }) => tenderDetails.mlist);
      // console.log('mlist==>', mlist)

      const quoteData = yield select(({ tenderDetails }) => tenderDetails.quoteData);
      // console.log('quoteData==>', quoteData)
      const newData = {
        ...formUtils.standardiseFormData(formData),
        srmPq: formUtils.standardiseFormData(quoteData),
        suppList: list,
        itemList: mlist,
      };
      // console.log('newData', newData)
      const advice = yield select(({ tenderDetails }) => tenderDetails.advice);
      if(!advice.trim()){
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(tenderService.create, newData);
      if (data.success) {
        // message.success('操作成功');
        // yield put({ type: 'redirect' });
        const bmpData = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
        if (bmpData.success) {
          message.success(resultCode.OK);
          yield put({ type: 'cancel' });
        } else {
          throw bmpData;
        }
      } else {
        message.error(data.message);
      }
    },

    * getSingle({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put(routerRedux.push('/source-mgmt/qo/iqo/view/tender'));
    },

    * bidDetail({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const tenderData = yield select(({ tenderDetails }) => tenderDetails.formData);
      const formData = yield call(tenderService.checkBidInfo, tenderData.id);
      if (formData.success) {
        return formData.data;
      } else {
        throw formData;
      }
    },

    * redirect({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      // yield put(routerRedux.push('/source-mgmt/qo/iqo'));
      yield put(routerRedux.goBack());
    },

    * bidRedirect({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      const { uri } = payload
      yield put(routerRedux.push(uri));
    },

    * cancel({ payload }: ReduxAction, { put }: ReduxSagaEffects) {
      yield put({ type: 'clean' });
      yield put(routerRedux.goBack());
    },

    * clean({ payload }: ReduxAction, { put, select }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          list: [],
          mlist: [],
          mode: 'create',
          from: '',
          taskKey: '',
          taskId: '',
          suppFlag: false,
          readOnly: false,
          // suppHiddenFlag:false,
          advice: '',
          remoteCfg: null,
          attachRepo: null,
        },
      });
    },

    * updateMaterial({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const { formData, mlist, list } = yield select(({ tenderDetails }) => tenderDetails);
      if (payload.value) {
        const data = yield call(tenderService.queryMaterial, { queryItemList: payload.value });
        if (data.success && data.data) {
          // 过滤掉空行
          const newList = mlist.slice().filter((item) => item.itemId);
          for (const queryItem of data.data) {
            // 构造物料
            const newItem = {
              itemId: queryItem.itemId,
              itemCode: queryItem.itemCode,
              itemDesc: queryItem.itemDesc,
              itemUom: queryItem.itemUom,
              itemUomName: queryItem.itemUomName,
              itemSpec: queryItem.itemSpec,
              itemQty: null,
              c3code: queryItem.c3code
            };
            // 找到列表中重复的物料
            const duplicationItem = newList.find((x, index) => {
              // 如果有重复的则直接进行替换操作
              if (queryItem.itemId === x.itemId) {
                newList[index] = queryItem;
              }
              return x.itemId === queryItem.itemId;
            });
            // 没有重复则新增
            if (!duplicationItem) {
              newList.push({ ...newItem, ...{ id: dataUtils.getRandomInt(-99999999, -1) } });
            }
          }
          yield put({
            type: 'updateState',
            payload: {
              mlist: newList,
            }
          });
        } else {
          const newItem = {
            itemId: null, itemCode: null,
            itemDesc: null, itemUom: null, itemSpec: null,
            itemQty: null,c3code:null
          };
          mlist[payload.index] = { ...mlist[payload.index], ...newItem };
          yield put({
            type: 'updateState',
            payload: {
              mlist,
            }
          });
        }
      } else {
        const newItem = {
          itemId: null, itemCode: null,
          itemDesc: null, itemUom: null, itemSpec: null,
          itemQty: null,c3code:null
        };
        mlist[payload.index] = { ...mlist[payload.index], ...newItem };
        yield put({
          type: 'updateState',
          payload: {
            mlist,
          }
        });
      }

      // 重置评标小组
      formData.group = null;
      formData.groupId = null;
      yield put({
        type: 'updateState',
        payload: {
          formData,
        }
      });
    },

    * updateSupp({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      // console.log('payload==>',payload)
      const list = yield select(({ tenderDetails }) => tenderDetails.list);
      if (payload.value.id) {
        const supp = yield call(tenderService.querySupp, payload.value.id);
        if (supp.success) {
          list[payload.index] = { ...list[payload.index], ...supp.data };
        } else {
          list[payload.index] = {
            id: dataUtils.getRandomInt(-99999999, -1),
            suppName: null, suppCode: null, suppStatusName: null,
            lastGrade: null, lastGrade2: null, lastGrade3: null
          };
          yield put({
            type: 'updateState',
            payload: {
              list,
            }
          });
        }
      } else {
        list[payload.index] = {
          id: dataUtils.getRandomInt(-99999999, -1),
          suppName: null, suppCode: null, suppStatusName: null,
          lastGrade: null, lastGrade2: null, lastGrade3: null
        };
        yield put({
          type: 'updateState',
          payload: {
            list,
          }
        });
      }
    },


    * updateQuoteType({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      if (payload === '01') {// 公开询价
        yield put({
          type: 'updateState',
          payload: {
            list: [],
          }
        });
      } else {// 非公开询价
        yield put({
          type: 'updateState',
          payload: {
            list: [{
              id: dataUtils.getRandomInt(-99999999, -1),
              suppName: null, suppCode: null, suppStatusName: null,
              lastGrade: null, lastGrade2: null, lastGrade3: null
            }],
          }
        });
      }
    },

    * approve({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ tenderDetails }) => tenderDetails.formData);
      const advice = yield select(({ tenderDetails }) => tenderDetails.advice);
      const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
      if (data.success) {
        const data1 = yield call(tenderService.update, { id: formData.id, approveStatus: approveStatus.APPROVING });
        if (data1.success) {
          message.success(resultCode.OK);
          yield put({ type: 'cancel' });
        } else {
          throw data1;
        }
      } else {
        throw data;
      }
    },

    * reject({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ tenderDetails }) => tenderDetails.formData);
      const advice = yield select(({ tenderDetails }) => tenderDetails.advice);
      if (!advice.trim()) {
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(bpmService.doReject, { taskId: formData.taskId, advice });
      if (data.success) {
        const data1 = yield call(tenderService.update, { id: formData.id, approveStatus: approveStatus.REJECT });
        if (data1.success) {
          message.success(resultCode.OK);
          yield put({ type: 'cancel' });
        } else {
          throw data1;
        }
      } else {
        throw data;
      }
    },

    * removeSupp({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const { list } = yield select(({ tenderDetails }) => tenderDetails);
      const { suppIds } = payload;
      const newList = list.slice().filter((item) => !suppIds.includes(item.suppId));
      yield put({
        type: 'updateState',
        payload: {
          list: newList,
        },
      });
    },

    * removeItem({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const { mlist } = yield select(({ tenderDetails }) => tenderDetails);
      const { index } = payload;
      const newItem = {
        itemId: null, itemCode: null,
        itemDesc: null, itemUom: null, itemSpec: null,
        itemQty: null,c3code:null
      };
      mlist[index] = newItem;
      yield put({
        type: 'updateState',
        payload: {
          mlist,
        }
      });
    },
  },

  reducers: {
    addRow(state: object, { payload }: ReduxAction) {
      const { mlist, total } = state;
      // 选择物料列表
      const newList = mlist.slice();
      newList.push(payload);
      return {
        ...state,
        mlist: newList,
      };
    },

    updateCell(state: object, { payload }: ReduxAction) {
      const { mlist } = state;
      // console.log('mlist1==>',mlist)
      const newList = mlist.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      return {
        ...state,
        mlist: newList,
      };
    },

    deleteRow(state: object, { payload }: ReduxAction) {
      const { mlist total } = state;
      const newmList = mlist.slice().filter((item) => item.id !== payload);
      return {
        ...state,
        mlist: newmList
      };
    },

    querySuccess(state: object, action: ReduxAction) {
      const { list, total } = action.payload;
      return {
        ...state,
        list,
        total,
      };
    },

    updateState(state: object, { payload }: ReduxAction) {
      // console.log('updateState:', payload);
      return {
        ...state,
        ...payload,
      };
    },

    updateForm(state: object, { payload }: ReduxAction) {
      // console.log('fffff==>',state)
      const { key, value } = payload;
      const formData = state.formData;
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      return {
        ...state,
        formData: newFormData,
      };
    },

  },

};
