import { message } from 'antd';
import { routerRedux } from 'dva/router';
import * as itemsService from '../../services/item/items';
import { formUtils, stringUtils, enums } from '../../utils';

const { itemStatus, entType } = enums;

export default {

  namespace: 'items',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    mode: 'create',
    createBtn: true, // 是否隐藏按钮 true隐藏 false不隐藏
    editBtn: true,
    invalidBtn: true,
    trialBtn: true,
    historyBtn: true,
    showUploadModal: false,
    supplier: false,
  },

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

  effects: {
    * query({ payload }, { call, select, put }) {
      // 角色判断 createBtn, editBtn, invalidBtn, trialBtn
      let { createBtn, editBtn, invalidBtn, trialBtn, historyBtn } = yield select(({ items }) => items);
      const perms = yield select(({ app }) => app.perms);
      // 角色控制按钮权限
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'im_its_add') {
            createBtn = false;
          } else if (p.menuId === 'im_its_update') {
            editBtn = false;
          } else if (p.menuId === 'im_its_disable') {
            invalidBtn = false;
          } else if (p.menuId === 'im_its_trial') {
            trialBtn = false;
          } else if (p.menuId === 'im_its_history') {
            historyBtn = false;
          }
        }
      }

      if (payload && payload.cccCode && typeof payload.cccCode !== 'string') {
        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 data = yield call(itemsService.query, payload);
      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 || '');
        }
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            createBtn,
            editBtn,
            invalidBtn,
            trialBtn,
            historyBtn,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));

      } else {
        throw data;
      }
    },

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

    * goToEdit({ payload }, { put, select,call }) {
      const list = yield select(({ items }) => items.list);
      // filter 返回一个新的数组
      const reuslt = list.filter((row) => {
        if (row.id === payload.id) {
          return true;
        }
      });
      if (reuslt[0].itemStatus === itemStatus.CANCELED) {
        message.warning('该物料已作废不可修改!');
        return;
      }else{
        const data=yield call(itemsService.isInitialTrial,reuslt[0].id);
        if(data.success){
          if(data.data){
            message.warning('该物料试制中不可修改!');
            return;
          }
        }else{
          throw data;
        }
      }
      yield put({
        type: 'getSingle',
        payload: {
          mode: payload.mode,
          id: payload.id,
        },
      });

    },

    * getSingle({ payload }, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });
      yield put({
        type: 'itemDetail/updateState',
        payload: {
          mode: payload.mode,
        },
      });
      if (payload.mode === 'create') {
        yield put(routerRedux.push('/item-mgmt/items/create'));
      } else {
        yield put(routerRedux.push(`/item-mgmt/items/${payload.id}?mode=${payload.mode}`));
      }
    },

    * delete({ payload }, { call, put, select }) {
      const list = yield select(({ items }) => items.list);
      // filter 返回一个新的数组
      const reuslt = list.filter((row) => {
        if (row.id === payload.ids[0]) {
          return true;
        }
      });
      if (reuslt[0].itemStatus === itemStatus.DEACTIVATED) {
        message.warning('该物料处于停用状态不可作废!');
        return;
      } else if (reuslt[0].itemStatus === itemStatus.CANCELED) {
        message.warning('该物料已作废不可重复操作!');
        return;
      }else{
        const data=yield call(itemsService.isTrial,reuslt[0].id);
        if(data.success){
          if(data.data){
            message.warning('该物料试制中不可作废!');
            return;
          }
        }else{
          throw data;
        }
      }
      const data = yield call(itemsService.remove, payload.ids[0]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    // 正式物料 ---> 停用
    * deactivate({ payload }, { call, put, select }) {
      const { selectedRow } = payload
      if (selectedRow.itemStatus !== itemStatus.FORMAL) {
        message.warning('仅限正式物料可做停用操作!');
        return;
      } else {
        selectedRow.itemStatus = itemStatus.DEACTIVATED
      }
      const data = yield call(itemsService.updateStatus, selectedRow);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    // 停用恢复 ---> 正式物料
    * recover({ payload }, { call, put, select }) {
      const { selectedRow } = payload
      if (selectedRow.itemStatus !== itemStatus.DEACTIVATED) {
        message.warning('该物料并不是停用物料!');
        return;
      } else {
        selectedRow.itemStatus = itemStatus.FORMAL
      }
      const data = yield call(itemsService.updateStatus, selectedRow);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * create({ payload }, { call, put }) {
      const data = yield call(itemsService.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(({ items }) => items.currentItem.id);
      const newData = { ...formUtils.standardiseFormData(payload), id };
      const data = yield call(itemsService.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: {},
        },
      });
    },

    * trial({ payload }, { call, put, select }) {
      const list = yield select(({ items }) => items.list);
      // filter 返回一个新的数组
      const reuslt = list.filter((row) => {
        if (row.id === payload.ids[0]) {
          return true;
        }
      });

      if (reuslt[0].itemStatus === itemStatus.DOING) {
        message.warning('该物料在审批中,不可提起试制!');
        return;
      } else if (reuslt[0].itemStatus === itemStatus.DEACTIVATED) {
        message.warning('该物料处于停用状态不可提起试制!');
        return;
      } else if (reuslt[0].itemStatus === itemStatus.CANCELED) {
        message.warning('该物料已作废不可提起试制!');
        return;
      } else {
        const data = yield call(itemsService.isEnabled,reuslt[0].semiProduct==='1'?'1':'0');
        const enabled=data.data;
        if(data.success){
          if(enabled){
            yield put(routerRedux.push(`/item-mgmt/itemTrial/newTrial?itemId=${reuslt[0].id}`));
          }else{
            message.warning(`您无权发起${reuslt[0].semiProduct==='1'?'半成品':'该物料'}的试制`);
          }  
        }else{
          throw data;
        }
      }
    },

    * clean({ payload }, { put, select }) {
      const { user } = yield select(({ app }) => app.user);
      yield put({
        type: 'updateState',
        payload: {
          supplier: user.entType === entType.SUPP,
        },
      });
    },
  },

  reducers: {

    querySuccess(state, action) {
      const { list, total, createBtn, editBtn, invalidBtn, trialBtn, historyBtn } = action.payload;
      return {
        ...state,
        list,
        total,
        createBtn,
        editBtn,
        invalidBtn,
        trialBtn,
        historyBtn
      };
    },

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

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

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

  },

};
