import { message } from 'antd';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import pathToRegexp from 'path-to-regexp';
import * as referService from '../../services/item/referprices';
import { dataUtils, formUtils, stringUtils } from '../../utils';

export default {

  namespace: 'referprices',

  state: {
    list: [],
    total: 0,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/price-mgmt/referprices').exec(location.pathname);
        if (match) {
          const payload = dataUtils.queryStringToJSON(location.search);
          dispatch({ type: 'queryFirst', payload });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      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')] : [];
      }

      // 物料三级联动
      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(referService.query, newPayload);
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(newPayload),
        }));

      } else {
        throw data;
      }
    },

    * queryFirst({ payload }, { call, put }) {
      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')] : [];
      }

      // 物料三级联动
      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(referService.query, newPayload);
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
          },
        });
      } else {
        throw data;
      }
    },

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          showUploadModal: false,
        }
      });
      yield put({
        type: 'queryFirst',
        payload: {},
      });
    },

    * cancelRows({ payload }, { call, put, select }) {
      const { index, row } = payload;
      yield put({ type: `toggleEditable`, payload: { index } });
      const { list } = yield select(({ referprices }) => referprices);
      const data = yield call(referService.getSingle, row.id);

      if (data.success) {
        const newList = list.slice(0);
        newList[index] = data.data;

        yield put({
          type: 'updateState',
          payload: {
            list: newList
          }
        });

      }
    },

    * updateRows({ payload }, { call, put, select }) {
      const { list } = yield select(({ referprices }) => referprices);
      const index = payload.index;
      const prices = list[index];
      const text = [];
      Object.keys(prices).map((key) => {
        if (prices[key]) {
          if (key.substr(0, 5) === 'price') {
            const num = key.split(key.substr(0, 5))[1];
            if (!prices['webName' + num] && num) {
              const arg = '网站' + num + '名称';
              return text.push(arg);
            }
          } else if (key.substr(0, 7) === 'webName') {
            const num = key.split(key.substr(0, 7))[1];
            if (!prices['price' + num] && num) {
              return text.push('网站' + num + '价格');
            }
          }
        }
      });
      if (text.length > 0) {
        return message.warn(text.join(',') + '不能为空');
      }
      // 如果找到这一行的数据,把数据传回后台;
      const data = yield call(referService.updateRows, prices);
      if (data.success) {
        yield put({ type: `toggleEditable`, payload: { index } });
        const result = yield call(referService.getSingle, prices.id);
        if (result.success) {
          const newList = list.slice(0);
          newList[index] = result.data;
          yield put({
            type: 'updateState',
            payload: {
              list: newList
            }
          });

        }
      } else {
        throw data;
      }
    },
  },

  reducers: {

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

    toggleEditable(state, action) {
      const { index } = action.payload;
      const newList = state.list.slice(0);

      if (newList[index].editable === true) {  // editable === true
        newList[index].editable = false;
      } else if (newList[index].editable === false) {
        newList[index].editable = true;
      } else {
        newList[index].editable = true;
      }

      return {
        ...state,
        list: newList,
      };
    },

    updateCell(state, action) {
      const { index, dataIndex, newValue } = action.payload;
      const newList = state.list.slice(0);
      newList[index][dataIndex] = newValue;
      return {
        ...state,
        list: newList,
      };

    },

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

  },

};
