import {ReduxAction, ReduxSagaEffects} from '@interfaces';
import {dataUtils, enums, formUtils} from '@utils';
import pathToRegexp from 'path-to-regexp';
import {routerRedux} from 'dva/router';
import {message} from 'antd';
import * as bidGroupDetailService from '../../../services/source/bidGroupDetail';

export default {

  namespace: 'bidGroupDetail',

  state: {
    formData: {},
    list: [],
    total: 1,
    mode: 'create',
    from: '',
    user: null,
    itemC3Id: null,
    saveBtnFlag: false,
    readOnly: false,
    saveBtnHidden: true,
  },

  subscriptions: {
    setup({dispatch, history}: object) {
      history.listen(() => {
        const match = pathToRegexp('/source-mgmt/bid-mgmt/bidGroup/:id').exec(location.pathname);
        // console.log('match==', match)
        if (match) {
          if (match[1] === 'create') {
            dispatch({type: 'clean'});
            dispatch({ type: 'newCreate' });
            return 0;
          }
          dispatch({type: 'readonly', payload: dataUtils.queryStringToJSON(location.search) || {from: ''}})
          dispatch({type: 'query', payload: match[1]});
        }
      });
    },
  },

  effects: {
    * query({payload}, {call, put, select}) {
      // console.log('payload==>', payload)
      //角色判断 soum_bm_eg_save
      let { saveBtnFlag } = yield select(({ bidGroupDetail }) => bidGroupDetail);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_eg_save';
          })) {
          saveBtnFlag = true;
        }
      }
      const formData = yield call(bidGroupDetailService.getSingle, payload);
      if (formData.success) {
        yield put({
          type: 'updateState',
          payload: {
            formData: formData.data,
            list: formData.data.members,
            saveBtnFlag
          },
        });
      } else {
        throw formData;
      }
    },
    * newCreate({ payload }, { call, put, select }) {
      //角色判断 soum_bm_eg_save
      let { saveBtnFlag } = yield select(({ bidGroupDetail }) => bidGroupDetail);
      const perms = yield select(({ app }) => app.perms);
      // console.log('perms==>', perms)
      if (perms) {
        if (perms.find((x) => {
            return x.menuId === 'soum_bm_eg_save';
          })) {
          saveBtnFlag = true;
        }
      }
      yield put({
        type: 'updateState',
        payload: {
          mode: 'create',
          saveBtnFlag,
        },
      });
    },
    * querySingle({payload}, {call, put}) {
      const data = yield call(bidGroupDetailService.getSingle, payload.id);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
      } else {
        throw data;
      }
    },

    * getSingle({payload}, {call, put}) {
      const formData = yield call(bidGroupDetailService.getSingle, payload.id);
      if (formData.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
      }
    },

    * save({payload}, {call, put, select}) {
      const {formData, list} = yield select(({bidGroupDetail}) => bidGroupDetail);
      const newData = {
        ...formUtils.standardiseFormData(formData),
        members: list,
      };
      const data = yield call(bidGroupDetailService.create, newData);
      if(data.success){
        message.success('操作成功');
        yield put({ type: 'cancel' });
      } else {
        throw data;
      }
    },

    * readonly({payload}: ReduxAction, {put}: ReduxSagaEffects) {
      if (payload.mode === 'view') {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
            readOnly: true,
            saveBtnHidden: false,
          },
        });
      } else {
        yield put({type: 'updateState', payload:{
          mode: payload.mode,
          readOnly: false,
          saveBtnHidden: true,
        }});
      }
    },

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

    * showPop({payload}, {put, call}) {
      yield put({
        type: 'showModal',
        payload: {
          mode: payload.mode,
        }
      });
    },

    * updateEmp({ payload }: ReduxAction, { select, call, put }: ReduxSagaEffects) {
      // console.log('payload=>',payload)
      const {list} = yield select(({bidGroupDetail}) => bidGroupDetail);
      if (payload.empId) {
        const emp = yield call(bidGroupDetailService.getEmp, payload.empId);
        // console.log('emp=>',emp)
        if (emp.success) {
          const item = list.find((x) => {
            return x.empId === emp.data.empId;
          });
          if (item) {
            const newItem = {
              empId: null, empCode: null,empName:null,
              ouName: null, orgName: null, mobile: null, roleNames: null
            };
            list[payload.index] = { ...list[payload.index], ...newItem };
            message.warn('重复选择成员');
          } else {
            list[payload.index] = { ...list[payload.index], ...emp.data };
          }
        } else {
          const newItem = {
            empId: null, empCode: null,empName:null,
            ouName: null, orgName: null, mobile: null, roleNames: null
          };
          list[payload.index] = { ...list[payload.index], ...newItem };
        }
      } else {
        const newItem = {
          empId: null, empCode: null,empName:null,
          ouName: null, orgName: null, mobile: null, roleNames: null
        };
        list[payload.index] = { ...list[payload.index], ...newItem };
      }
      yield put({
        type: 'updateState',
        payload: {
          list,
        }
      });
    },

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

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

    * clean({payload}, {call, put}) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          formData: {},
          mode: 'create',
        },
      });
    },
  },

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

      //如果物料品类发生改变，重置小组成员
      if (key === 'itemC3Id') {
        return {
          ...state,
          formData: newFormData,
          list: [],
          itemC3Id: value,
        };
      } else {
        return {
          ...state,
          formData: newFormData,
        };
      }
    },

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

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

    addRow(state: object, {payload}: ReduxAction) {
      const {list, total} = state;
      const newList = list.slice();
      newList.push(payload);
      // console.log('newlist=>',newList)
      return {
        ...state,
        list: newList,
      };
    },

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