import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { message } from 'antd';
import { dataUtils, enums, formUtils } from '@utils';
import * as bidService from '@services/source/bids';
import * as taxCodes from '@services/mdata/tax';
const { bidInfoStatus,bidResult,entType} = enums;
export default {

  namespace: 'bidDetails',

  state: {
    formData: {},
    mode: 'create',
    from: '',
    taskKey: '',
    taskId: '',
    list: [],
    modalVisible:false,
    suppFlag:false,
    saveBtnFlag: false,
    attachRepo:null,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(() => {
        const match = pathToRegexp('/source-mgmt/bid-mgmt/bids/bids/:id').exec(location.pathname);
        console.log(match);
        if (match) {
          const queryparam = dataUtils.queryStringToJSON(location.search);
          console.log('queryparam-->',queryparam);
          dispatch({ type: 'clean' });
          if(queryparam.mode === 'create'){
            dispatch({ type: 'newCreate' ,payload:{id: match[1], bidNo:queryparam.bidNo}});
          }else{
            dispatch({ type: 'query', payload: {id: match[1], mode: queryparam.mode} });
          }
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      console.log("payload==>", payload)
      //角色判断 soum_bm_bs_save
      let { saveBtnFlag } = yield select(({ bidDetails }) => bidDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_bs_save';
          })) {
          saveBtnFlag = true;
        }
      }
      const formData =  yield call(bidService.getSingle, payload.id);
      if (formData.success) {
        // console.log('formData==>',formData)
        const currentUser = yield select(({ app }) => app.user);
        let suppFlag = false;
        if (entType.SUPP === currentUser.user.entType) {
          suppFlag = true;
        } else {
          suppFlag = false;
        }
        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;
        //   });
        // }
        const mode = formData.data.docStatus === '0' ? payload.mode : 'view';
        yield put({
          type: 'updateState',
          payload: {
            formData: fData ? fData : {},
            list: fData.itemList ? fData.itemList : [],
            mode,
            suppFlag,
            saveBtnFlag,
            attachRepo: fData.attachRepo,
          },
        });
      } else {
        message.error(formData.message);
      }
    },

    * newCreate({ payload }, { call, put, select }) {
      //角色判断 soum_bm_bs_save
      let { saveBtnFlag } = yield select(({ bidDetails }) => bidDetails);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_bs_save';
          })) {
          saveBtnFlag = true;
        }
      }
      // console.log('newCreate==>',payload)
      const initData = yield call(bidService.getInit, payload.id);
      // console.log('initData==>',initData)
      const currentUser = yield select(({ app }) => app.user);
      let suppFlag = false;
      if (entType.SUPP === currentUser.user.entType) {
        suppFlag = true;
      } else {
        suppFlag = false;
      }
      if(initData.success){
        yield put({
          type: 'updateState',
          payload: {
            formData: {
              id:null,
              biId:initData.data.biId,
              biNo:initData.data.biNo,
              biName:initData.data.biName,
              docStatus:bidInfoStatus.WAITING,
              bidResult:bidResult.FAIL,
              bidUser:null,tel:null,docTime:null,
              bidNo:payload.bidNo,bidResult:null,memo:null,
            },
            list:initData.data.itemList,
            mode: 'create',
            suppFlag,
            saveBtnFlag,
            attachRepo: 'bid'+dataUtils.getRandomInt(1, 9999999),
          },
        });
      }else{
        message.error(initData.message);
      }

    },


    * save({ payload }, { select, call, put }) {
      const formData = yield select(({ bidDetails }) => bidDetails.formData);
      const { submitted } = payload;
      formData.submitted = submitted;
      const attachRepo = yield select(({ bidDetails }) => bidDetails.attachRepo);
      formData.attachRepo = attachRepo;
      const list = yield select(({ bidDetails }) => bidDetails.list);
      const newData = {
        ...formUtils.standardiseFormData(formData),
        itemList: list,
      };
      const data = yield call(bidService.create, newData);
      if (data.success) {
        message.success('操作成功');
        // yield put(routerRedux.push('/source-mgmt/bid-mgmt/tenders/tenders'));
        yield put(routerRedux.push('/source-mgmt/bid-mgmt/bids/bids'));
        /*if (submitted) {
          yield put(routerRedux.replace(`/contract-mgmt/contracts/${data.data}?mode=view`));
        } else {
          yield put(routerRedux.replace(`/contract-mgmt/contracts/${data.data}?mode=update`));
        }*/
      } else {
        throw data;
      }
    },

    * redirect({ payload }, { put }) {
      yield put(routerRedux.push('/source-mgmt/bid-mgmt/bids/bids'));
    },

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

    * clean({ payload }, { put, select }) {
      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          mode: 'create',
          from: '',
          taskKey: '',
          taskId: '',
          list: [],
          modalVisible:false,
          suppFlag:false,
          attachRepo: null,
        },
      });
    },

    * updateCell({ payload }, { put, select, call }) {
      const { list } = yield select(({ bidDetails }) => bidDetails);
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      if (key === 'price' || key === 'taxRate') {
        if (value!==null) {
          if (key === 'taxRate') {
            const taxCode = yield call(taxCodes.getSingle, value);
            if (taxCode.success) {
              newList[index]['taxRateCompute'] = taxCode.data.taxRate;
            } else {
              throw taxCode;
            }
          }
          const taxPrice = newList[index].price;
          const taxRateCompute = newList[index].taxRateCompute;
          if (taxPrice !== null && taxRateCompute !== null) {
            /*税率 物料带出
            含税单价 录入
            未税单价 = 含税单价 / （1+税率）
            含税金额 = 含税单价 * 数量
            未税金额 = 未税单价 * 数量
            税额 = 含税金额 - 未税金额*/
            const netPrice = (taxPrice / (1 + (taxRateCompute / 100))).toFixed(4);
            const num = newList[index].itemQty;
            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;
        }
      }
      yield put({
        type: 'updateState',
        payload: {
          list: newList
        },
      });
    },

  },

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

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


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

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

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


  },

};
