import { message } from 'antd';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import * as pricesService from '../../services/item/prices';
import { formUtils, stringUtils } from '../../utils';

export default {

  namespace: 'prices',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    filterParams: {},
    showUploadModal: false,
    outBtn: true,
    historyBtn: true,
    adjustBtn: true,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/prices-mgmt/prices') {
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      let { outBtn, historyBtn, adjustBtn } = yield select(({ prices }) => prices);
      const perms = yield select(({ app }) => app.perms);
      // 角色控制按钮权限
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'im_ps_out') {
            outBtn = false;
          } else if (p.menuId === 'im_ps_history') {
            historyBtn = false;
          } else if (p.menuId === 'im_ps_adjust') {
            adjustBtn = false;
          }
        }
      }
      if (payload) {
        payload.cccCode = payload.cccCode ? (typeof payload.cccCode === 'string' ? payload.cccCode.split(',') : payload.cccCode) : [];
        payload.yearMonthDate = payload.yearMonthDateFrom ? [moment(payload.yearMonthDateFrom, 'YYYY-MM-DD'), moment(payload.yearMonthDateTo, 'YYYY-MM-DD')] : [];
        payload.suppCenter && payload.suppCenter.map((value, key) => {
          payload.suppCenter[key] = parseInt(value);
        });
      }

      // 物料三级联动
      if (payload && payload.cccCode) {
        if (payload.cccCode.length > 0) {
          payload.cccCode.map((code, index) => {
            const key = 'c' + (index + 1) + 'Code';
            payload[key] = code;
          });
        } else {
          Object.keys(payload).map((key) => {
            if (key.indexOf('Code') === 2) {
              payload[key] = '';
            }
          });
        }
      }
      const newPayload = formUtils.standardiseFormData(payload);
      if (newPayload.yearMonthDateFrom) {
        newPayload.yearMonthDateFrom = newPayload.yearMonthDateFrom.substring(0, 7);
        newPayload.yearMonthDateTo = newPayload.yearMonthDateTo.substring(0, 7);
      }

      const data = yield call(pricesService.query, newPayload);

      if (data.success) {
        for (let i in data.data.rows) {
          data.data.rows[i].typeName = (data.data.rows[i].c1Name || '') + '>' + (data.data.rows[i].c2Name || '') + '>' + (data.data.rows[i].c3Name || '');
          data.data.rows[i].item = (data.data.rows[i].itemName || '') + '-' + (data.data.rows[i].brandName || '') + '-' + (data.data.rows[i].spec || '');
        }
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            outBtn,
            historyBtn,
            adjustBtn
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));

      } else {
        throw data;
      }
    },

    * querySingle({ payload }, { call, put }) {
      const data = yield call(pricesService.getSingle, payload.id);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
      } else {
        throw data;
      }
    },

    * goToReferprices({ payload }, { put, select }) {
      const { selectedRows } = payload;
      const row = selectedRows[0];
      if (selectedRows.length === 0) {
        // 不带参数跳转页面
        yield put(routerRedux.push(`/price-mgmt/referprices`));
      } else if (selectedRows.length === 1) {
        // 带参数跳转页面
        // row['isSearched'] = false
        const newPayload = {
          id: row.itemId,
          cccCode: [row.c1Code, row.c2Code, row.c3Code],
          itemCode: row.itemName,
          yearMonthDateFrom: row.yearMonth,
          yearMonthDateTo: row.yearMonth,
        };
        yield put(routerRedux.push({
          pathname: `/price-mgmt/referprices`,
          search: '?' + stringUtils.JSON2QueryString(newPayload),
        }));
      } else {
        message.error('请选择一条数据!');
        return 0;
      }
      // yield put(routerRedux.push(`/price-mgmt/referprices`));
    },
    * getSingle({ payload }, { put, select }) {
      const { list } = yield select(({ prices }) => prices);
      const row = list.filter((r) => {
        if (r.id === payload.id[0]) {
          return true;
        }
      });
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });
      if (payload.mode === 'create') {
        yield put(routerRedux.push('/price-mgmt/prices/create'));
      } else {
        if (payload.mode === 'update') {
          yield put(routerRedux.push(`/price-mgmt/prices/${row[0].itemId}`));
        }
        if (payload.mode === 'view') {
          yield put(routerRedux.push(`/price-mgmt/prices/${row[0].itemId}`));
        }
      }
    },

    * adjust({ payload }, { call, put, select }) {
      const data=yield call(pricesService.isAdjust,payload.id);
      if(data.success){
        if(data.data){
          message.warning('物料正在价格调整中，请勿重复发起');
        }else{
          yield put(routerRedux.push(`/price-mgmt/adjust/${payload.id}?mode=${payload.mode}`));
        }
      }else{
        throw data;
      }
      
    },

    * create({ payload }, { call, put, select }) {
      const data = yield call(pricesService.create, { ...formUtils.standardiseFormData(payload) });
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * update({ payload }, { select, call, put }) {
      const id = yield select(({ prices }) => prices.currentItem.id);
      const newData = { ...formUtils.standardiseFormData(payload), id };
      const data = yield call(pricesService.update, newData);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * view({ payload }, { put }) {
      yield put({ type: 'hideModal' });
    },

    * hideModal({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          modalVisible: false,
          currentItem: {},
        },
      });
      yield put({
        type: 'query',
        payload: {},
      });
    },

    * clean({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          filterParams: {},
          mode: 'create',
          showUploadModal: false,
          outBtn: true,
          historyBtn: true,
          adjustBtn: true,
        },
      });
    },
  },

  reducers: {

    querySuccess(state, action) {
      const { list, total, outBtn, historyBtn, adjustBtn } = action.payload;

      return {
        ...state,
        list,
        total,
        outBtn,
        historyBtn,
        adjustBtn
      };
    },

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

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

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

  },

};
