import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import * as bpmService from '../../../services/common/bpm';
import * as statementOfAccountService from '../../../services/cooperate/finance/statementOfAccount';
import { formUtils, stringUtils } from '../../../utils';

export default {

  namespace: 'accounts',

  state: {
    list: [],
    total: 0,
    currentItem: {},
    modalVisible: false,
    suppId: '',
    ouId: '',
    accountType: '',
    mode: 'create',
    createBtn: true, // 是否隐藏按钮 false 不隐藏 true 隐藏
    editBtn: true,
    invoiceBtn: true,
    approvalBtn: true,
    remindBtn: true,
    reAccBtn: true,
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/cooperate/finance/soa') {
          // dispatch({type: 'clean'});
          // dispatch({type: 'query'});
        }
      });
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      // 角色判断 createBtn, editBtn, invoiceBtn, approvalBtn, remindBtn
      let { createBtn, editBtn, invoiceBtn, approvalBtn, remindBtn, reAccBtn } = yield select(({ accounts }) => accounts);
      const perms = yield select(({ app }) => app.perms);
      // 角色控制 开发采购专员(2)/订单采购专员(4) 全部按钮开放 ; 开发采购经理(3)/订单采购经理(5) 提起试制按钮不出现
      if (perms) {
        for (const p of perms) {
          if (p.menuId === 'cp_fn_soa_add') {
            createBtn = false;
          } else if (p.menuId === 'cp_fn_soa_edit') {
            editBtn = false;
          } else if (p.menuId === 'cp_fn_soa_invoice') {
            invoiceBtn = false;
          } else if (p.menuId === 'cp_fn_soa_approval') {
            approvalBtn = false;
          } else if (p.menuId === 'cp_fn_soa_reAcc') {
            reAccBtn = false;
          }
        }
      }
      if (payload && !payload.bpmStatus) {
        payload.bpmStatus = 'NONE';
      }
      if (payload && payload.payPeriodFromDate) {
        payload['payPeriodFromDate'] = payload.payPeriodFromDate.substring(0, 7);
      }
      if (payload && payload.payPeriodToDate) {
        payload['payPeriodToDate'] = payload.payPeriodToDate.substring(0, 7);
      }
      const data = yield call(statementOfAccountService.query, payload);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            list: data.data.rows,
            total: data.data.total,
            createBtn,
            editBtn,
            invoiceBtn,
            approvalBtn,
            remindBtn,
            reAccBtn,
          },
        });
        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString(payload),
        }));
      } else {
        throw data;
      }
    },
    * querySingle({ payload }, { call, put }) {
      const data = yield call(statementOfAccountService.getSingle, payload.id);
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            mode: payload.mode,
          },
        });
      } else {
        throw data;
      }
    },
    * goToRemind({ payload }, { call, put, select }) {
      // TODO: 提醒供应商对账
    },
    * goToApproval({ payload }, { call, put, select }) {
      const data = yield call(statementOfAccountService.getSingle, payload.id);
      if (data.success) {
        const status = yield call(bpmService.doCheckActived, data.data.prcId);
        if (status.success) {
          if (status.data) {
            yield put(routerRedux.push(`/cooperate/finance/soa/approval?id=${payload.id}`));
          } else {
            Modal.error({
              title: '您不是当前处理人',
              okText: '确认'
            });
          }
        }
      }
    },
    * goToFormaInvoice({ payload }, { call, put, select }) {
      // TODO: 跳转到形式发票页, 需要判断是否在流程中   以及对账单状态
      const { selectedRowKeys, selectedRows } = payload;
      if (!selectedRows[0].invNo && selectedRows[0].status === '03') {
        // 如果没有汇总形式发票编号,则进入新增页面
        yield put(routerRedux.push(`/cooperate/finance/s-invoice/create?checkId=${selectedRowKeys[0]}`));
      } else if (!selectedRows[0].invNo && selectedRows[0].status !== '03') {
        Modal.error({
          title: '对账未完成，暂不支持开票',
          okText: '确认'
        });
      } else {
        Modal.error({
          title: '已开票，不能重复开票',
          okText: '确认'
        });
      }
    },
    * getSingle({ payload }, { call, put, select }) {
      yield put({
        type: 'updateState',
        payload: {
          mode: payload.mode,
        },
      });
      if (payload.mode === 'create') {
        const currentUser = yield select(({ app }) => app.user);
        const { ouId, accountType } = yield select(({ accounts }) => accounts);
        const data = yield call(statementOfAccountService.isExistAccount, { suppId: currentUser.user.entId, ouId, accountType });
        if (data.data > 0) {
          Modal.error({
            title: '账期内已存在该类型对账单，不可再做新建',
            okText: '确认'
          });
        } else {
          yield put(routerRedux.push(`/cooperate/finance/soa/create?ouId=${ouId}&accountType=${accountType}`));
        }
      } else if (payload.mode === 'update') {
        if (payload.account.status === '01') {
          yield put(routerRedux.push(`/cooperate/finance/soa/update?id=${payload.account.id}`));
        } else {
          Modal.error({
            title: '只有新建的对账单才能编辑',
            okText: '确认'
          });
        }
      } else {
        yield put(routerRedux.push(`/cooperate/finance/soa/view?id=${payload.id}`));
      }
    },
    * reAcc({ payload }, { call, put }) {
      const data = yield call(statementOfAccountService.reAcc, payload.id);
      if (data.success) {
        message.success("操作成功");
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * delete({ payload }, { call, put }) {
      const data = yield call(statementOfAccountService.remove, [...payload.ids]);
      if (data.success) {
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },
    * create({ payload }, { put, call }) {
      const data = yield call(statementOfAccountService.create, payload);
      if (data.success) {
        yield put({ type: 'hideModal' });
        yield put({ type: 'query' });
      } else {
        throw data;
      }
    },

    * showPop({ }, { put, select }) {
      const currentUser = yield select(({ app }) => app.user);
      yield put({
        type: 'showModal',
        payload: {
          suppId: currentUser.user.empId,
        }
      });
    },

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

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 0,
          currentItem: {},
          modalVisible: false,
          mode: 'create',
          createBtn: true, // 是否隐藏按钮 false 不隐藏 true 隐藏
          editBtn: true,
          invoiceBtn: true,
          approvalBtn: true,
          remindBtn: true,
        },
      });
    },
  },

  reducers: {

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

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

  },
};
