import { ReduxAction, ReduxSagaEffects } from '@interfaces';
import { dataUtils, stringUtils } from '@utils';
import { routerRedux } from 'dva/router';
import { message, Modal } from 'antd';
import pathToRegexp from 'path-to-regexp';
import * as quoteService from '../../../services/source/quote';

export default {

  namespace: 'quoteItems',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'update',
    filterParams: {},
    detailBtnFlag: false,
    confirmBtnFlag: false,
    exportBtnFlag: false
  },

  subscriptions: {
    setup({ dispatch, history }: object) {
      history.listen((location) => {
        // console.log("location==>", location)
        const match = pathToRegexp('/source-mgmt/qo/item').exec(location.pathname);
        // console.log('match==>',match)
        /*if (match) {
          const queryparam = dataUtils.queryStringToJSON(location.search);
          // console.log('queryparam',queryparam+'-'+queryparam['docNo']+'-'+queryparam['suppCode'])
          if (queryparam['docNo']) {
            // console.log('queryparam2',queryparam)
            /!*dispatch({
              type: 'updateState',
              payload: {
                filterParams: {
                  // docNo: queryparam['docNo'],
                  peDocNo: queryparam['docNo'],
                  suppCode: queryparam['suppCode'],
                  // suppName: queryparam['suppCode']
                },
              },
            });*!/
            dispatch({type: 'query', payload: {peDocNo: queryparam['docNo']}});
          }
        }*/
        // if (location.pathname === '/source-mgmt/qo/qo') {
        // dispatch({ type: 'clean' });
        // dispatch({ type: 'query' });
        // }
        if (location.pathname === '/source-mgmt/qo/qo/item') {
          dispatch({ type: 'query'});
        }
      });
    },
  },

  effects: {
    * query({ payload }: ReduxAction, { call, put, select }: ReduxSagaEffects) {
      // if(payload.monthDate){
        // 角色判断
        let { detailBtnFlag, confirmBtnFlag, exportBtnFlag } = yield select(({ quoteItems }) => quoteItems);
        const perms = yield select(({ app }) => app.perms);
        // console.log('perms==>', perms)
        if (perms) {
          // if (perms.find((x) => {
          //     return x.menuId === 'soum_qo_item_detail';
          //   })) {
          //   detailBtnFlag = true;
          // }
          if (perms.find((x) => {
              return x.menuId === 'soum_qo_item_confirm';
            })) {
            confirmBtnFlag = true;
          }
          // if (perms.find((x) => {
          //     return x.menuId === 'soum_qo_item_export';
          //   })) {
          //   exportBtnFlag = true;
          // }
        }
        const data = yield call(quoteService.items, payload);
        if (data.success) {
          yield put({
            type: 'querySuccess',
            payload: {
              list: data.data.rows,
              total: data.data.total,
              detailBtnFlag, confirmBtnFlag, exportBtnFlag
            },
          });
          yield put(routerRedux.replace({
            pathname: location.pathname,
            search: '?' + stringUtils.JSON2QueryString(payload),
            // state: { ...payload },
          }));
        } else {
          throw data;
        }
      // }else{
      //   message.warn('请填写询价月份');
      // }
    },
    * querySingle({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(quoteService.getSingle, payload);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
      } else {
        throw data;
      }
    },
    * getSingle({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      if('view'===payload.mode){
        yield put(
          routerRedux.push(`/source-mgmt/qo/qo?itemName=${payload.itemName}&monthDate=${payload.monthDate}`)
        )
      }else if('create'===payload.mode){
        yield put(
          routerRedux.push(`/source-mgmt/qo/compare/detail?mode=${payload.mode}&docId=${payload.docId}`)
        );
      }
    },

    * delete({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      const data = yield call(quoteService.remove, [...payload.ids]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * create({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      const data = yield call(quoteService.create, payload);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * update({ payload }: ReduxAction, { put, call, select }: ReduxSagaEffects) {
      const id = yield select(({ quoteItems }) => quoteItems.currentItem.id);
      const newData = { ...payload, id };
      const data = yield call(quoteService.update, newData);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * showPop({ payload }: ReduxAction, { put, call }: ReduxSagaEffects) {
      yield put({
        type: 'showModal',
        payload: {
          mode: payload.mode,
        }
      });
    },
    * hideModal({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {},
        },
      });
    },
    * clean({ payload }: ReduxAction, { call, put }: ReduxSagaEffects) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          filterParams: {},
        },
      });
    },
  },

  reducers: {

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

    updateCell(state: object, { payload }: ReduxAction) {
      const { list } = state;
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      return {
        ...state,
        list: newList,
      };
    },

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

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

  },
};
