import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { message } from 'antd';
import { dataUtils, formUtils } from '../../../utils';
import * as returnOrderService from '../../../services/cooperate/order/returnOrder';

export default {

  namespace: 'returnOrderDetails',

  state: {
    formData: null,
    mode: 'create',
    from: '',
    taskKey: '',
    taskId: '',
    list: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(() => {
        const match = pathToRegexp('/cooperate/order/ro/:id').exec(location.pathname);
        console.log(match);
        if (match) {
          // if (match[1] === 'create') {
          //   dispatch({ type: 'clean' });
          //   // dispatch({ type: 'initForm' })
          //   dispatch({ type: 'newCreate' });
          //   return 0;
          // }

          // if (match[1] === 'createWithData') {
          //   dispatch({ type: 'clean' });
          //   const faultCode = dataUtils.queryStringToJSON(location.search).code;

          //   dispatch({ type: 'initWithForm', payload: faultCode });

          //   return 0;
          // }
          // dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) || { from: '' } });
          // dispatch({ type: 'query', payload: match[1] });
          dispatch({
            type: 'updateState', payload: {
              formData: {
                faultCode: 'RT1505426OH00489',
                faultName: '待确认',
                faultType: '---',
                agentCode: '王宁',
                returnUnit: '上海埃林哲餐饮管理股份有限公司',
                supplierName: '上海武林食品股份有限公司',
                supplierAddress: '上海市延陵西路123号',
                amount: '1318.20',
                bidMoney:'2018-03-26',
                storageDate:'2018-03-27',
                currency: '人民币',
                remark: '请按时入库'
              },
              list: [{
                materialCode: '201111301315',
                materialname: '慧爱牌麦芽糖',
                materialmode: '优质',
                materialunit: '袋',
                materialnumber: '-20',
                materialprice: 19.96,
                materialamount: -998.00,
                remark: '请及时收货'
              }, {
                materialCode: '201111401308',
                materialname: '香草棒',
                materialmode: '优质',
                materialunit: '斤',
                materialnumber: '-20',
                materialprice: 16.01,
                materialamount: -320.20,
                remark: '请及时确认'
              }]
            }
          });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      // const formData = yield call(inquiryService.getSingle, payload);
      // debugger;
      // const currentUser = yield select(({ app }) => app.user);
      // if (formData.success) {
      //   const partList = yield call(inquiryService.getSingle, { faultCode: formData.data.faultCode });
      //   yield put({
      //     type: 'updateState',
      //     payload: {
      //       formData: formData.data,
      //       list: partList.data.rows,
      //     },
      //   });
      // } else {
      //   throw formData;
      // }
    },

    * save({ payload }, { select, call, put }) {
      const formData = yield select(({ bidForm }) => bidForm.formData);
      const list = yield select(({ bidForm }) => bidForm.list);

      const newData = {
        ...formUtils.standardiseFormData(formData),
        ...formUtils.standardiseFormData(payload),
        faultPds: list,
      };

      const data = yield call(returnOrderService.update, newData);
      if (data.success) {
        message.success('操作成功');
        const { from } = yield select(({ bidForm }) => bidForm);
        yield put(routerRedux.replace(`/fault/forms/${data.data}?mode=update&from=${from}`));
      } else {
        throw data;;
      }
    },

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

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

    updateCell(state, { payload }) {
      const { list } = state;
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      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,
      };
    },

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