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 inquiryService from '../../../services/source/inquiry';
import moment from 'moment';
import { numberUtils } from '@utils';
const { entType, resultCode, customMsg, viewMode } = enums;

export default {

  namespace: 'inquiryDetails',

  state: {
    formData: {},
    list: [],
    mlist: [],
    quoteData: {},
    mode: 'create',
    from: '',
    taskKey: '',
    taskId: '',
    suppId: null,
    suppFlag: false,
    readOnly: false,
    // suppHiddenFlag:false,
    advice: '',
    remoteCfg: null,
    user: null,
    saveBtnFlag: false,
    priceBtnFlag: false,
    yjconfirmBtnFlag: false,
    editMaterialFlag: false,
    switchBargainBtnFlag: false,
    abandonBargainBtnFlag: false,
    reBargainBtnFlag: false,
    attachRepo: null,
    taxList: [],
    quoteModalVisible: false,
    showUploadModal: false,
    collectData: [],
  },

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

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // console.log("payload==>", payload)
      // 角色判断 soum_qo_iqo_save  /soum_qo_iqo_price
      let { saveBtnFlag, priceBtnFlag, yjconfirmBtnFlag, editMaterialFlag, switchBargainBtnFlag, abandonBargainBtnFlag, reBargainBtnFlag } = yield select(({ inquiryDetails }) => inquiryDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_save';
        })) {
          saveBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_price';
        })) {
          priceBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_yjcfm';
        })) {
          yjconfirmBtnFlag = true;
        }
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_switchYj';
        })) {
          switchBargainBtnFlag = true;
        }
      }
      const formData = payload.operate === 'copy'
        ? yield call(inquiryService.copy, payload.id)
        : yield call(inquiryService.getSingle, payload.id);
      if (payload.operate === 'copy') {
        yield put({
          type: 'updateState',
          payload: {
            mode: 'create',
          },
        });
      }
      let { mode } = yield select(({ inquiryDetails }) => inquiryDetails);
      if (formData.success) {

        // 如果为复制的询价单，需要更新供应商ID
        if (payload.operate === 'copy') {
          yield put({
            type: 'updateState',
            payload: {
              suppId: formData.data.suppList[0].suppId,
            },
          });
        }

        // 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 = false;
        if (entType.SUPP === currentUser.user.entType) {
          suppFlag = true;
        } else {
          suppFlag = false;
        }

        // 判断物料列表是否能进行编辑操作
        if (!suppFlag && (mode === 'create' || mode === 'edit' || mode === 'update' || (mode === 'approval' && formData.data.taskKey === 'initiator'))) {
          // 该按钮同时控制税率下拉框是否可用
          editMaterialFlag = true;
        } else {
          editMaterialFlag = false;
        }
        yield put({
          type: 'updateState',
          payload: {
            editMaterialFlag,
          },
        });

        // 如果为议价中，则需要更新议价状态切换的两个按钮
        if (mode === 'quote') {
          if (switchBargainBtnFlag) {
            // 如果是议价中的状态，则显示"放弃议价"，不显示"重新议价"
            if (formData.data.docStatus === '04') {
              abandonBargainBtnFlag = true;
              reBargainBtnFlag = false;
            } else {
              abandonBargainBtnFlag = false;
              reBargainBtnFlag = true;
            }
          }
          yield put({
            type: 'updateState',
            payload: {
              abandonBargainBtnFlag,
              reBargainBtnFlag,
            },
          });
        }

        if(mode === viewMode.VIEW && !suppFlag && formData.data.docStatus === '03' /* 报价中 */) {
          /* 报价中时，企业人员不应该可以看见供应商的报价 */
          formData.data.itemList.forEach(i => {
            i.taxPrice = null;  /* 含税单价(元) */
            i.netPrice = null; /* 未税单价(元) */
            i.amt = null; /* 含税金额(元) */
            i.netAmt = null; /* 未税金额(元) */
            i.taxAmt = null; /*税额(元)*/
          });
        }
        // 当采购进行议价的时候，将含税议价初始化为含税报价，该步骤必须在 设置未税降本差异金额 步骤之前
        // 由于初始化的议价=报价，所以就不用计算未税单价了
        if(formData.data.docStatus === '04' && mode === 'quote' && !suppFlag) {
          formData.data.itemList.forEach(i => {
            if (!i.yjPrice) {
              i.yjPrice = i.taxPrice;
            }
          });
        }
        yield put({
          type: 'updateState',
          payload: {
            suppFlag,
            user: currentUser,
            saveBtnFlag,
            priceBtnFlag
          },
        });
        // 初始配置文件参数
        const params = {
          defId: 'Inquiry:',
          nodeId: suppFlag ? 'supp' : (formData.data.prcId ? (mode === viewMode.VIEW ? 'initiator' : (formData.data.docStatus === '04' ? 'quote' : formData.data.taskKey)) : 'initiator'),
          mode: suppFlag ? ( yjconfirmBtnFlag? mode : 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;

        // 有物料 && 物料议价状态为“待确认：01” => 显示比价确认按钮
        //该步骤需要在获取配置文件之后进行
        yjconfirmBtnFlag = fData.itemList ? (fData.itemList[0].yjConfirmStatus === '01' ? true : false) : false;
        yield put({
          type: 'updateState',
          payload: {
            yjconfirmBtnFlag
          },
        });

        // 汇总列表统计
        let itemNumber = 0;
        let quoteAmt = 0;
        let bargainAmt = 0;

        if (fData.itemList) {
          fData.itemList.map((i) => {
            // i.estimatedAmtStr = i.estimatedAmt
            //   ? parseFloat(i.estimatedAmt).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
            //   : null;
            const number = i.estimatedNum * i.proportion / 100;
            i.allowedNumber = (i.proportion || i.proportion === 0)
              ? parseFloat(number).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
              : null;
            i.allowedAmt = (i.proportion || i.proportion === 0)
              ? parseFloat(number * i.taxPrice).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
              : null;

            // 汇总列表计算
            itemNumber += i.estimatedNum;
            quoteAmt +=  i.taxPrice * i.estimatedNum;
            bargainAmt += i.yjPrice * i.estimatedNum;

            // 顺便设置 未税降本差异金额
            // 1.该步骤必须在初始化议价步骤之后 由于初始化的议价=报价，所以就不用计算未税单价了
            // 2.如果有分配比例则需要计算分配后的数量
            if (i.guidePrice != null && i.yjPrice != null) {
              const num = (i.estimatedNum ? i.estimatedNum : 0) * (i.proportion == null ? 1 : i.proportion/100);
              i.yjOverTaxprice = (i.netPrice ? (i.netPrice - i.guidePrice) * num : 0).toFixed(2);
            } else {
              i.yjOverTaxprice = 0;
            }

            // 前端计算 议报价差异 = 含税议价 - 含税报价
            if (i.yjPrice != null && i.taxPrice != null) {
              i.gapPrice = (i.yjPrice - i.taxPrice).toFixed(4);
            }
          });
        }

        // 汇总列表统计
        // const { itemList } = formData.data;
        // const itemNumber = itemList.map(m => m.estimatedNum).reduce((prev, next) => (prev + next), 0); // 当期预估用量
        // const itemAmt = itemList.map(m => m.taxPrice).reduce((prev, next) => (prev + next), 0); // 含税报价
        // const itemEst = itemList.map(m => m.yjPrice).reduce((prev, next) => (prev + next), 0); // 含税议价
        const collectData = (payload.operate === 'copy')
          ? []
          : [{
            itemCount: fData.itemList.length, // 物料品项数
            itemNumber: numberUtils.round_half_up_format(itemNumber, 2), // 物料数量
            quoteAmt: numberUtils.round_half_up_format(quoteAmt, 2), // 报价总金额
            bargainAmt: numberUtils.round_half_up_format(bargainAmt, 2), // 议价总金额
          }];

        yield put({
          type: 'updateState',
          payload: {
            mode,
            formData: fData ? fData : {},
            list: fData.suppList ? fData.suppList : [],
            mlist: fData.itemList ? fData.itemList : [],
            quoteData: fData.srmPq ? fData.srmPq : {},
            attachRepo: suppFlag
              ? ((fData.srmPq && fData.srmPq.attachRepo) ? fData.srmPq.attachRepo : 'inquiry' + dataUtils.getRandomInt(1, 9999999))
              : null,
            taxList: fData.suppTaxRates,
            collectData,
          },
        });
      } 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_qo_iqo_save
      let { saveBtnFlag } = yield select(({ inquiryDetails }) => inquiryDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
          return x.menuId === 'soum_qo_iqo_save';
        })) {
          saveBtnFlag = true;
        }
      }
      const currentUser = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          user: currentUser,
          saveBtnFlag,
          editMaterialFlag: true,
        },
      });
      // 初始配置文件参数
      const params = {
        defId: 'Inquiry:',
        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: '01',
            quoteType: '02',
          },
          list: [{
            id: dataUtils.getRandomInt(-99999999, -1),
            suppName: null, suppCode: null, suppStatusName: null,
            scoreGrade: null, suppLinkMan: null, suppLinkTel: null, cashMethod: null,
            taxClass: null, taxRate: null
          }],
          mlist: [],
          suppFlag: (entType.SUPP === currentUser.user.entType) ? true : false,
        },
      });
    },

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

      const quoteData = yield select(({ inquiryDetails }) => inquiryDetails.quoteData);
      const attachRepo = yield select(({ inquiryDetails }) => inquiryDetails.attachRepo);
      quoteData.attachRepo = attachRepo;
      // console.log('quoteData==>', quoteData)
      const newData = {
        ...formUtils.standardiseFormData(formData),
        srmPq: formUtils.standardiseFormData(quoteData),
        suppList: list,
        itemList: mlist,
      };
      // console.log('newData', newData)

      const data = yield call(inquiryService.create, newData);
      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'redirect' });
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },

    * reSubmit({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      const formData = yield select(({ inquiryDetails }) => inquiryDetails.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(({ inquiryDetails }) => inquiryDetails.list);
      // console.log('list==>', list)
      // if (!list[0].suppName) {
      //   message.error('供应商 必填');
      // }
      const mlist = yield select(({ inquiryDetails }) => inquiryDetails.mlist);
      // console.log('mlist==>', mlist)

      const quoteData = yield select(({ inquiryDetails }) => inquiryDetails.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(({ inquiryDetails }) => inquiryDetails.advice);
      if (!advice.trim()) {
        message.error('请填写审批意见');
        return;
      }
      const data = yield call(inquiryService.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 {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },

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

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

    * 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: [],
          quoteData: {},
          mode: 'create',
          from: '',
          taskKey: '',
          taskId: '',
          suppFlag: false,
          readOnly: false,
          // suppHiddenFlag:false,
          advice: '',
          remoteCfg: null,
          attachRepo: null,
          taxList: [],
          saveBtnFlag: false,
          priceBtnFlag: false,
          showUploadModal: false,
          collectData: [],
        },
      });
    },

    * updateOu({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      // console.log("updateOu==>",payload)
      if (payload.id) {
        const initformData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
        // console.log("initformData==>",initformData)
        const ou = yield call(inquiryService.queryOu, payload.id);
        // console.log("ou==>",ou)
        if (ou.success) {
          const formData = { ...initformData, ...{ recCompanyAddress: ou.data.recCompanyAddress } };
          // console.log("formData==>",formData)
          yield put({
            type: 'updateState',
            payload: { formData },
          });
        } else {
          initformData.recCompany = { id: null, code: null, name: null };
          // initformData.recCompanyAddress = '';
          yield put({
            type: 'updateState',
            payload: { formData: initformData },
          });
        }
      }
      // console.log("=============", yield select(({inquiryDetails}) => inquiryDetails.formData))
    },

    * updateSupp({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      // console.log('payload==>',payload)
      const list = yield select(({ inquiryDetails }) => inquiryDetails.list);
      if (payload.value.id) {
        const supp = yield call(inquiryService.querySupp, payload.value.id);
        if (supp.success) {
          // console.log('supp==>',supp)
          list[payload.index] = { ...list[payload.index], ...supp.data };
          const suppTaxRates = yield call(inquiryService.suppTaxRates, payload.value.id);

          // 更新: 1.供应商ID 2.供应商列表 3.供应商支持的税率列表
          yield put({
            type: 'updateState',
            payload: {
              suppId: payload.value.id,
              list,
              taxList: suppTaxRates.data,
            }
          });
          // 选择供应商后，自动将该供应商报过价、投过标、且处在询价期的物料带出
          // const formData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
          // const item = yield call(inquiryService.querySuppItem,
          //   {
          //     suppCenterId: formData.suppCenterId,
          //     suppId: payload.value.id,
          //     quotePeriod: formData.quotePeriod,
          //   });
          // console.log('item==>',item)
          // 选择供应商后，自动获取该供应商的税率
          // if (item.success) {
          //   const itemList = item.data;
          //   itemList.map((it) => {
          //     it.id = dataUtils.getRandomInt(-99999999, -1);
          //   });
          //   // console.log('itemList==>',itemList)
          //   yield put({
          //     type: 'updateState',
          //     payload: {
          //       list,
          //       mlist: itemList,
          //       taxList: suppTaxRates.data,
          //     }
          //   });
          // } else {
          //   yield put({
          //     type: 'updateState',
          //     payload: {
          //       list,
          //       mlist: [],
          //     }
          //   });
          // }
        } else {
          list[payload.index] = {
            id: dataUtils.getRandomInt(-99999999, -1), suppId: null,
            suppName: null, suppCode: null, suppStatusName: null,
            scoreGrade: null, suppLinkMan: null, suppLinkTel: null, cashMethod: null,
            taxClass: null, taxRate: null
          };
          yield put({
            type: 'updateState',
            payload: {
              list,
              taxList: [],
              // mlist: [],
            }
          });
        }
      } else {
        list[payload.index] = {
          id: dataUtils.getRandomInt(-99999999, -1), suppId: null,
          suppName: null, suppCode: null, suppStatusName: null,
          scoreGrade: null, suppLinkMan: null, suppLinkTel: null, cashMethod: null,
          taxClass: null, taxRate: null
        };
        yield put({
          type: 'updateState',
          payload: {
            list,
            taxList: [],
            // mlist: [],
            collectData: [],
          }
        });
      }
    },

    * updateMaterial({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      // console.log('payload==>',payload)
      const mlist = yield select(({ inquiryDetails }) => inquiryDetails.mlist);
      // console.log('mlist==>',mlist)
      // console.log('item==>',item)
      if (payload.value) {
        let data;
        const formData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
        if (formData.quoteType === '01') {
          data = yield call(inquiryService.queryMaterial,
            {
              itemQueryList: payload.value,
              suppCenterId: formData.suppCenterId,
              suppId: null
            });
        } else {
          const list = yield select(({ inquiryDetails }) => inquiryDetails.list);
          if (list && list[0].suppId) {
            data = yield call(inquiryService.queryMaterial,
              {
                itemQueryList: payload.value,
                suppCenterId: formData.suppCenterId,
                //quotePeriod: formData.quotePeriod,
                suppId: list[0].suppId
              });
          } else {
            message.warn('非公开询价要选择供应商');
            data = { success: false }
          }
        }
        if (data.success) {
          if (data.data) {
            // console.log(data.data)
            // console.log('mlist=>',mlist)
            const newList = mlist.slice().filter((item) => item.itemId);

            const paramItemList = payload.value;

            // console.log('newlist=>',newList)
            // let i = payload.index-1;
            for (const vItem of data.data) {
              const pItem = paramItemList.find((x) => {
                return vItem.itemId === x.id;
              });
              if (pItem) {
                vItem.guidePrice = pItem.guidePrice; //这里，覆盖了原来可能获取的guidePrice，所以后端将获取guidePrice的操作注释掉了，若要修改这里的代码，请注意和后端代码联动修改
                vItem.estimatedNum = pItem.estimatedNum;
                vItem.minNum = pItem.minNum;
                vItem.taxRate = pItem.taxRate;
                vItem.maxProvideNum = pItem.maxProvideNum;
                vItem.orderPeriod = pItem.orderPeriod;
                vItem.deliveryPeriod = pItem.deliveryPeriod;
              }
              const item = newList.find((x, index) => {
                if (vItem.itemId === x.itemId) {
                  newList[index] = vItem;
                }
                return vItem.itemId === x.itemId;
              });
              if (!item) {
                newList.push({ ...vItem, ...{ id: dataUtils.getRandomInt(-99999999, -1) } });
                // mlist[payload.index] = { ...mlist[payload.index], ...data.data };
              }
            }
            if (payload.value.length > data.data.length) {
              message.warn('不在当前询价周期内的物料已被过滤');
            }
            yield put({
              type: 'updateState',
              payload: {
                mlist: newList,
              }
            });
          } else {
            const newItem = {
              itemId: null, itemCode: null, guidePrice: null,
              itemDesc: null, itemUomName: null, itemSpec: null, itemBrand: null,
              fromDate: null, toDate: null, days: null, minNum: null, itemUom: null
            };
            mlist[payload.index] = { ...mlist[payload.index], ...newItem };
            yield put({
              type: 'updateState',
              payload: {
                mlist,
              }
            });
          }
        } else {
          const newItem = {
            itemId: null, itemCode: null, guidePrice: null,
            itemDesc: null, itemUomName: null, itemSpec: null, itemBrand: null,
            fromDate: null, toDate: null, days: null, minNum: null, itemUom: null
          };
          mlist[payload.index] = { ...mlist[payload.index], ...newItem };
          yield put({
            type: 'updateState',
            payload: {
              mlist,
            }
          });
        }
      } else {
        const newItem = {
          itemId: null, itemCode: null, guidePrice: null,
          itemDesc: null, itemUomName: null, itemSpec: null, itemBrand: null,
          fromDate: null, toDate: null, days: null, minNum: null, itemUom: null
        };
        mlist[payload.index] = { ...mlist[payload.index], ...newItem };
        yield put({
          type: 'updateState',
          payload: {
            mlist,
          }
        });
      }
      // console.log('mlist=>',yield select(({ inquiryDetails }) => inquiryDetails.mlist))
    },
    * updateQuoteType({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      // console.log("payload==>",payload)
      if (payload === '01') {// 公开询价
        yield put({
          type: 'updateState',
          payload: {
            list: [],
            mlist: []
          }
        });
      } else {// 非公开询价
        yield put({
          type: 'updateState',
          payload: {
            list: [{
              id: dataUtils.getRandomInt(-99999999, -1),
              suppName: null, suppCode: null, suppStatusName: null,
              scoreGrade: null, suppLinkMan: null, suppLinkTel: null, cashMethod: null,
              taxClass: null, taxRate: null
            }],
            mlist: []
          }
        });
      }
    },

    * approve({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
      // console.log(formData)
      const advice = yield select(({ inquiryDetails }) => inquiryDetails.advice);
      // if (!advice.trim()) {
      //   message.error('请填写审批意见');
      //   return;
      // }
      const data1 = yield call(inquiryService.update, { id: formData.id, approveStatus: '01', reviewFlag: formData.reviewFlag ? '1' : '0' });
      if (data1.success) {
        const data = yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
        if (data.success) {
          message.success(resultCode.OK);
          yield put({ type: 'cancel' });
        } else {
          throw data;
        }
      } else {
        throw data1;
      }
    },

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

    * viewQuote({ payload }: ReduxAction, { put, select }: ReduxSagaEffects) {
      const formData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
      yield put(routerRedux.push(`/source-mgmt/qo/qo?docNo=${formData.docNo}`));
    },

    * handleUpload({ payload }: ReduxAction, { put, select }: ReduxSagaEffects) {
      const itemQueryList = payload.data.map(i => {
        return {
          id : i.itemId, //物料ID
          code : i.itemCode, //物料CODE，Excel导入的物料编码实际为物料OuterCode
          name : i.itemName, //物料名称
          guidePrice: i.guidePrice, //询价指导价（页面显示为未税基准价）
          estimatedNum: i.estimatedNum, //当期预告用量
          minNum: i.minNum, //单次起订量
          taxRate: i.taxRate, //税率
          maxProvideNum: i.maxProvideNum, //最高可供应量
          orderPeriod: i.orderPeriod, //订货或生产周期(天)
          deliveryPeriod: i.deliveryPeriod //物流配送时间(天)
        }
      });

      yield put({
        type: 'updateMaterial',
        payload: {
          value: itemQueryList
        }
      });

      yield put({
        type: 'showUploadModal',
        payload: false
      });
    },

    * yjconfirm({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
      const data = yield call(inquiryService.yjconfirm, formData.id);
      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'redirect' });
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },
    * switchBargain({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const formData = yield select(({ inquiryDetails }) => inquiryDetails.formData);
      const data = yield call(inquiryService.switchBargain, { peId: formData.id, action: payload.action });
      if (data.success) {
        message.success('操作成功');
        yield put({ type: 'redirect' });
      } else {
        let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
        message.error(errorMsg);
      }
    },
    * updateForm({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      // console.log('fffff==>',state)
      const { key, value } = payload;
      const { formData } = yield select(({ inquiryDetails }) => inquiryDetails);
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      if (key === 'suppCenterId') {
        let newList = [];
        if (value) {
          newList.push({
            id: dataUtils.getRandomInt(-99999999, -1), suppId: null,
            suppName: null, suppCode: null, suppStatusName: null,
            scoreGrade: null, suppLinkMan: null, suppLinkTel: null, cashMethod: null,
            taxClass: null, taxRate: null
          });
        }
        yield put({
          type: 'updateState',
          payload: {
            list: newList
          }
        });
      }
      yield put({
        type: 'updateState',
        payload: {
          formData: newFormData
        }
      });
    },
  },

  reducers: {
    addRow(state: object, { payload }: ReduxAction) {
      // console.log('payload==>',payload)
      const { mlist, total } = state;
      const newList = mlist.slice();
      // newList.unshift(payload)
      newList.push(payload);
      // console.log('newList==>',newList)
      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;
      if (key === 'taxPrice') {
        if (value != null) {
          const taxRate = newList[index].taxRate;
          if (taxRate != null) {
            /*税率 录入
            含税单价 录入
            未税单价 = 含税单价 / （1+税率）
            含税金额 = 含税单价 * 数量
            未税金额 = 未税单价 * 数量
            税额 = 含税金额 - 未税金额
            未税降本差异金额 = （未税单价 - 未税基准价）* 数量*/
            const netPrice = (value / (1 + (taxRate / 100))).toFixed(4);
            const num = newList[index].estimatedNum ? newList[index].estimatedNum : 0;
            const amt = (value * num).toFixed(4);
            const netAmt = (netPrice * num).toFixed(4);
            const taxAmt = amt - netAmt;
            newList[index].netPrice = netPrice;
            newList[index].amt = amt;
            newList[index].netAmt = netAmt;
            newList[index].taxAmt = taxAmt;
          } else {
            newList[index].netPrice = null;
            newList[index].amt = null;
            newList[index].netAmt = null;
            newList[index].taxAmt = null;
          }
        } else {
          newList[index].netPrice = null;
          newList[index].amt = null;
          newList[index].netAmt = null;
          newList[index].taxAmt = null;
        }
      } else if (key === 'yjPrice') {
        if (value != null) {
          const taxRate = newList[index].taxRate;
          if (taxRate != null) {
            /*税率 录入
            含税单价 录入
            未税单价 = 含税单价 / （1+税率）
            含税金额 = 含税单价 * 数量
            未税金额 = 未税单价 * 数量
            税额 = 含税金额 - 未税金额*/
            const taxPrice = newList[index].taxPrice;
            const netPrice = (value / (1 + (taxRate / 100))).toFixed(4);
            const num = newList[index].estimatedNum ? newList[index].estimatedNum : 0;
            const amt = (value * num).toFixed(4);
            const netAmt = (netPrice * num).toFixed(4);
            const taxAmt = amt - netAmt;
            const yjOverTaxprice = (newList[index].guidePrice ? (netPrice - newList[index].guidePrice) * num : 0).toFixed(2);
            const gapPrice = (value - taxPrice).toFixed(4);
            newList[index].netPrice = netPrice;
            newList[index].amt = amt;
            newList[index].netAmt = netAmt;
            newList[index].taxAmt = taxAmt;
            newList[index].yjOverTaxprice = yjOverTaxprice;
            newList[index].gapPrice = gapPrice;
          } else {
            newList[index].netPrice = null;
            newList[index].amt = null;
            newList[index].netAmt = null;
            newList[index].taxAmt = null;
            newList[index].yjOverTaxprice = null;
            newList[index].gapPrice = null;
          }
        } else {
          newList[index].netPrice = null;
          newList[index].amt = null;
          newList[index].netAmt = null;
          newList[index].taxAmt = null;
          newList[index].yjOverTaxprice = null;
          newList[index].gapPrice = null;
        }
      } else if (key === 'taxRate') {
        if (value != null) {
          const taxPrice = newList[index].taxPrice;
          if (taxPrice != null) {
            /*税率 录入
            含税单价 录入
            未税单价 = 含税单价 / （1+税率）
            含税金额 = 含税单价 * 数量
            未税金额 = 未税单价 * 数量
            税额 = 含税金额 - 未税金额*/
            const netPrice = (taxPrice / (1 + (value / 100))).toFixed(4);
            const num = newList[index].estimatedNum ? newList[index].estimatedNum : 0;
            const amt = (taxPrice * num).toFixed(4);
            const netAmt = (netPrice * num).toFixed(4);
            const taxAmt = amt - netAmt;
            newList[index].netPrice = netPrice;
            newList[index].amt = amt;
            newList[index].netAmt = netAmt;
            newList[index].taxAmt = taxAmt;
          } else {
            newList[index].netPrice = null;
            newList[index].amt = null;
            newList[index].netAmt = null;
            newList[index].taxAmt = null;
          }
        } else {
          newList[index].netPrice = null;
          newList[index].amt = null;
          newList[index].netAmt = null;
          newList[index].taxAmt = null;
        }
      } else if (key === 'fromDate') {
        if (value) {
          const days = newList[index].days;
          if (days) {
            newList[index].toDate = moment(value.format()).add(days, 'days').format('YYYY-MM-DD');
          } else {
            newList[index].toDate = null;
          }
        } else {
          newList[index].toDate = null;
        }
      }
      return {
        ...state,
        mlist: newList,
      };
    },

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

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

    updateState(state: object, { payload }: ReduxAction) {
      return {
        ...state,
        ...payload,
      };
    },

    updateQuoteForm(state: object, { payload }: ReduxAction) {
      const { key, value } = payload;
      const formData = state.quoteData;
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      return {
        ...state,
        quoteData: newFormData,
      };
    },

    showQuoteModal(state, { payload }) {
      return { ...state, ...payload, quoteModalVisible: true };
    },

    hideQuoteModal(state, { payload }) {
      return { ...state, ...payload, quoteModalVisible: false };
    },

    showUploadModal(state, action) {
      return { ...state, showUploadModal: action.payload };
    },
  },

};
