import { message } from 'antd';
import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';

import * as itemDetailService from '../../services/item/itemDetail';
import { dataUtils, enums, formUtils } from '../../utils';

const { item } = enums;

export default {

  namespace: 'itemDetail',

  state: {
    formData: {},
    mode: 'create',
    otherProps: [],
    saveBtnHidden: true,
    controlDisable:false,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/item-mgmt/items/:id').exec(location.pathname);
        if (match) {
          if (match[1] === 'create') {
            dispatch({ type: 'clean' });
            return 0;
          }
          dispatch({ type: 'query', payload: match[1] });
          dispatch({ type: 'updateState', payload: dataUtils.queryStringToJSON(location.search) });
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, select, put }) {
      const otherProps = new Array;
      const data = yield call(itemDetailService.getSingle, payload);
      let { mode, saveBtnHidden,controlDisable } = yield select(({ itemDetail }) => itemDetail);

      const perms = yield select(({ app }) => app.perms);
      // 角色控制 开发采购专员(2)/订单采购专员(4)/开发采购经理(3)/订单采购经理(5) 都可以操作新物料保存按钮
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'im_its_save') {
            saveBtnHidden = false;
          }else if(p.menuId === 'im_its_control'){
            controlDisable = true;
          }
        }
      }

      if (data.success) {
        const formData = data.data;
        formData.cccCode = formData.c1Code?[formData.c1Code, formData.c2Code, formData.c3Code]:[];
        formData.cccCodeName = formData.c1Code?[formData.c1Name, formData.c2Name, formData.c3Name].join(' / '):'';
        formData.repItemName = { id: formData.repItemId, code: formData.repItemCode, name: formData.repItemId ? `${formData.repItemName}(${formData.repItemCode})` : formData.repItemName };
        formData.reqDept = { id: formData.reqDeptId, code: formData.reqDeptCode, name: formData.reqDeptName };
        formData.semiProduct = formData.semiProduct === '1' ? true : false;
        for (let i = 1; i < 11; i++) {
          const otherProp = {};
          otherProp.otherProp = formData['otherProp' + i];
          otherProp.otherPropValue = formData['otherProp' + i + 'Value'];
          otherProp.standardPropValue = formData['standardProp' + i + 'Value'];
          otherProp.key = 'prop' + i;
          otherProp.lineNo = i;
          otherProps.push(otherProp);
        }

        yield put({
          type: 'querySuccess',
          payload: {
            formData,
            mode,
            otherProps,
            saveBtnHidden,
            controlDisable,
          },
        });
      } else {
        throw data;
      }
    },

    * save({ payload }, { call, put, select }) {
      const { formData, otherProps } = yield select(({ itemDetail }) => itemDetail);
      formData.repItemId = formData.repItemName && formData.repItemName.id;
      formData.reqDeptId = formData.reqDept && formData.reqDept.id;
      const currUser = yield select(({ app }) => app.user.user);

      if (formData.cccCode) {
        // 防止JDE同步的数据有误
        if (formData.cccCode.length !== 3) {
          message.error(item.ERR_NO_C3CODE, 2);
          return ;
        } else {
          formData.cccCode.map((code, index) => {
            formData['c' + (index + 1) + 'Code'] = code;
          });
        }
      }

      const errList = new Array;
      otherProps.map((op, i) => {
        if (op.otherProp && op.otherPropValue) {
          formData['otherProp' + (i + 1)] = op.otherProp;
          formData['otherProp' + (i + 1) + 'Value'] = op.otherPropValue;
        } else if ((op.otherProp && !op.otherPropValue) || (!op.otherProp && op.otherPropValue)) {
          errList.push(i + 1);
        }
      });

      if (errList.length > 0) {
        message.warning(item.ERR_PROPS); // 请填写完整其他属性信息
        return;
      } else {
        const data = yield call(itemDetailService.create, { ...formUtils.standardiseFormData(formData), ouId: currUser.entId });
        if (data.success) {
          yield put(routerRedux.push(`/item-mgmt/items`));
        } else {
          throw data;
        }
      }
    },

    * cancel({ payload }, { call, put }) {
      yield put(routerRedux.goBack());
    },

    * clean({ payload }, { call, put, select }) {
      const otherProps = new Array;
      for (let i = 1; i < 11; i++) {
        const otherProp = {};
        otherProp.otherProp = null;
        otherProp.otherPropValue = null;
        otherProp.standardPropValue = null;
        otherProp.key = 'prop' + i;
        otherProp.lineNo = i;
        otherProps.push(otherProp);
      }

      const perms = yield select(({ app }) => app.perms);
      let { saveBtnHidden,controlDisable } = yield select(({ itemDetail }) => itemDetail);
      // 角色控制 开发采购专员(2)/订单采购专员(4) 全部按钮开放 ; 开发采购经理(3)/订单采购经理(5) 提起试制按钮不出现
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'im_its_save') {
            saveBtnHidden = false;
          }else if(p.menuId === 'im_its_control'){
            controlDisable = true;
          }
        }
      }

      yield put({
        type: 'updateState',
        payload: {
          formData: {},
          mode: 'create',
          otherProps,
          saveBtnHidden,
          controlDisable,
        },
      });
    },

    * transCHToEn({ payload }, { call, put }) {
      const data = yield call(itemDetailService.transCHToEn, { source: payload.value });
      if (data.success) {
        yield put({
          type: 'updateForm',
          payload: {
            key: payload.targetKey,
            value: data.data,
          },
        });
      }
    },

    * updateForm({ payload }, { call, put, select }) {
      const { key, value } = payload;
      const { formData, otherProps } = yield select(({ itemDetail }) => itemDetail);
      const newFormData = Object.assign({}, formData);
      newFormData[key] = value;
      const newOtherProps = new Array;
      if (key === 'repItemName' && value.id != null) {
        newFormData[key].name = `${value.name}(${value.code})`;
        const data = yield call(itemDetailService.getSingle, value.id);
        if (data.success) {
          const formData = data.data;
          for (let i = 1; i < 11; i++) {
            const otherProp = {};
            otherProp.otherProp = formData['otherProp' + i];
            otherProp.otherPropValue = null;
            otherProp.standardPropValue = formData['otherProp' + i + 'Value'];
            otherProp.key = 'prop' + i;
            otherProp.lineNo = i;
            newOtherProps.push(otherProp);
          }
        }
      }
      if (key === 'repItemName' && value.id === null) {
        for (let i = 1; i < 11; i++) {
          const otherProp = {};
          otherProp.otherProp = null;
          otherProp.otherPropValue = null;
          otherProp.standardPropValue = null;
          otherProp.key = 'prop' + i;
          otherProp.lineNo = i;
          newOtherProps.push(otherProp);
        }
      }
      if(key === 'semiProduct' && value){
        newFormData['batType'] = '1';
      }
      yield put({
        type: 'updateState',
        payload: {
          formData: newFormData,
          otherProps: key === 'repItemName' ? newOtherProps : otherProps,
        }
      });
    },

  },

  reducers: {

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



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

    updateOtherProps(state, { payload }) {
      const { otherProps } = state;
      const newOtherProps = otherProps.slice();
      const { key, index, value } = payload;
      newOtherProps[index][key] = value;
      return {
        ...state,
        otherProps: newOtherProps,
      };
    },

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