import { message, Modal } from 'antd';
import { routerRedux } from 'dva/router';
import qs from 'qs';

import { dataUtils, enums, mathUtils, stringUtils } from '@utils';
import * as bpmService from '../../../services/common/bpm';
import * as purchasingOrderService from '../../../services/cooperate/order/purchasingOrder';

const { order, resultCode } = enums;
// const initTime = '00:00:00'
// const endTime = '23:59:59'

/**
 * 获取url上面参数 query string
 * @param {string} url - 指定路径
 * @returns {Object} 这个函数参数只有1个，不做柯理化
 */
const fromQs = (url: string): {} => {
  if (!url) {
    throw 'Ineligible url to parse query string.';
  }
  return qs.parse(url.split('?')[1]);
};

export default {

  namespace: 'purchasingOrderForm',

  state: {
    list: [],
    total: 1,
    currentItem: {},
    modalVisible: false,
    confirmHidden: false,
    approvalHidden: false,
  },

  subscriptions: {
    setup({ dispatch, history }) {
    },
  },

  effects: {
    * query({ payload }, { call, put, select }) {
      if (payload.sortBy && payload.sortBy === 'promisePeriod') {
        payload.sortBy = 'promiseDate';
      }

      const data = yield call(purchasingOrderService.query, payload);
      if (data.success) {
        const rows = data.data.rows;
        // 对时间进行数据清洗
        if (rows.length > 0) {
          rows.map((row) => {
            row.demandDate = dataUtils.ymd(row.demandDate);
            // row.reqDate = dataUtils.ymd(row.reqDate)
            row.docTime = dataUtils.ymd(row.docTime);
            row.promisePeriod = {
              promiseDate: dataUtils.ymd(row.promiseDate),
              deliveryTimeFrom: row.deliveryTimeFrom && row.deliveryTimeFrom.slice(row.deliveryTimeFrom.indexOf('T') + 1),
              deliveryTimeTo: row.deliveryTimeTo && row.deliveryTimeTo.slice(row.deliveryTimeTo.indexOf('T') + 1),
            };
            if (row.details.length > 0) {
              row.details.map((d) => {
                d.diffQty = d.qty - d.promiseQty;
                if ((d.diffQty !== 0) || (row.demandDate !== row.promisePeriod.promiseDate)) {
                  row.hasDiff = true;
                }
              });
            }
          });
        }

        yield put({
          type: 'updateState',
          payload: {
            list: data.data.rows,
            total: data.data.total,
          },
        });

        yield put(routerRedux.replace({
          pathname: location.pathname,
          search: '?' + stringUtils.JSON2QueryString({ ...payload, docDate: null }),
        }));
      } else {
        throw data;
      }
    },

    * getSingle({ payload }, { put, call }) {

      const formData = yield call(purchasingOrderService.getSingle, payload.id);
      if (formData.success) {
        const { suppName, docNo, prcId, approveStatus } = formData.data;
        if (payload.mode === 'approval') {
          if (prcId) {
            // if (approveStatus === '00') {
            //   Modal.error({ title: '请在确认信息点击确认按钮后提交流程', okText: '确定' });
            //   return false;
            // }
            // 查看当前操作人是否为当前任务节点
            const status = yield call(bpmService.doCheckActived, prcId);
            if (status.success && !status.data) {
              Modal.error({ title: '您不是当前处理人', okText: '确定' });
              return false;
            }
          } else {
            Modal.error({ title: '该单据尚未起流程', okText: '确定' });
            return false;
          }
        }
        yield put(routerRedux.push(`/cooperate/order/po/${payload.id}?mode=${payload.mode}&breadCode=${docNo}&breadOuName=${suppName}`));
      }
    },

    * getDetails({ payload }, { put, call }) {
      const { record } = payload;
      const data = yield call(purchasingOrderService.queryDtls, { poId: record.id });

      if (data.success) {
        yield put({
          type: 'updateRow',
          payload: {
            details: data.data,
            expanded: true,
            id: record.id,
          },
        });
      }
    },

    * confirm({ payload }, { put, select, call }) {
      const { list } = yield select(({ purchasingOrderForm }) => purchasingOrderForm);
      const newList = list.filter((l) => payload.indexOf(l.id) > -1);
      let hasError = false;

      newList.map((row) => {
        if (row.docStatus !== '290') {
          hasError = true;
        }
        row.submitted = true;
      });

      if (hasError) {
        message.error(order.SELECT_PO_ERR); // 请选择状态为等待确认的采购进行确认操作
      } else {
        newList.map((row) => {
          // 按照后端的字段格式需求清洗数据
          if (row.promisePeriod) {
            let { promiseDate, deliveryTimeFrom, deliveryTimeTo } = row.promisePeriod;
            promiseDate = dataUtils.ymd(promiseDate || row.demandDate);
            row.promiseDate = promiseDate;
            if (deliveryTimeFrom) {
              row.deliveryTimeFrom = promiseDate + 'T' + deliveryTimeFrom;
            }
            if (deliveryTimeTo) {
              row.deliveryTimeTo = promiseDate + 'T' + deliveryTimeTo;
            }
          }
        });

        // console.warn('newList', newList)
        const data = yield call(purchasingOrderService.update, newList);
        if (data.success) {
          yield put({ type: 'doBatchApprove', payload: newList }); // 批量审批
        } else {
          let errorMsg = data.message + " " + ( data.data && 'info' in data.data ? data.data.info : "");
          message.error(errorMsg);
        }
      }
    },

    * doBatchApprove({ payload }, { call, select, put }) {
      const newPayload = {
        advice: '',
        taskIds: new Array(),
        result: 'APPROVED',
      };
      payload.map((l) => newPayload.taskIds.push(l.taskId));

      const data = yield call(purchasingOrderService.doBatchApprove, newPayload);
      if (data.success) {
        yield put({ type: 'clean' });
        yield put({
          type: 'query',
          payload: fromQs(location.pathname + location.search)
        });
        message.success(resultCode.OK);
      } else {
        throw data;
      }
    },

    * approve({ payload }, { put, call, select }) {
      const { formData, advice } = yield select(({ purchasingOrderDetails }) => purchasingOrderDetails);
      yield call(bpmService.doApprove, { taskId: formData.taskId, advice });
      yield put(routerRedux.goBack());
    },

    * reject({ payload }, { put, call, select }) {
      const { formData, advice } = yield select(({ purchasingOrderDetails }) => purchasingOrderDetails);
      if (!advice.trim()) {
        message.error('请填写审批意见');
        return;
      }
      yield call(bpmService.doReject, { taskId: formData.taskId, advice });
      yield put(routerRedux.goBack());
    },

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

    * clean({ payload }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          list: [],
          total: 1,
          currentItem: {},
          modalVisible: false,
        },
      });
    },

    * checkValid({ payload }, { put, select }) {
      const { list } = yield select(({ purchasingOrderForm }) => purchasingOrderForm);
      const { index, key, pIndex, maxVal } = payload;
      let { value } = payload;

      // const reg= /^(-?\d+)(\.\d{1,2})?$/ // 校验小数点后两位+负数
      const reg = /^\d+(\.\d{1,4})?$/; // 校验小数点后两位
      const regNum = /^\d+(\.\d+)?$/; // 校验是非负浮点数

      // 当输入为promiseQty并且值为0/null时
      if (key === 'promiseQty' && !value) {
        list[pIndex].details[index].diffQty = list[pIndex].details[index].qty;
      }

      if (typeof value === 'string' && !value.split('.')[1]) {
        // 校验
        if (value.split('.').length > 2) {
          value = list[pIndex].details[index][key];
          message.warning(order.EDIT_NUM_FAIL); // 修改数量失败
        } else {
          list[pIndex].details[index][key] = value;
        }
      } else {
        if (value && !regNum.test(value)) {
          message.warning(order.NUM_ALLOW); // 请填写非负数
        } else if (value && !reg.test(value)) {
          message.warning(order.FOUR_BITS_AFTER_POINT); // 仅支持小数点后四位
        } else if (value && value.length > 8) {
          message.warning(order.MAX_LENGTH); // 最长仅支持8位数字
        } else if (value > maxVal) {
          message.warning(order.OVER_LIMIT); // 数量超限
        } else if (value > list[pIndex].details[index].qty) {
          message.warn(order.PRO_QTY_ERR); // 承诺数量不可大于采购数量
        } else if (!value && value != 0) { // 若value为空 默认等于qty
          list[pIndex].details[index][key] = null;
        } else {
          list[pIndex].details[index][key] = value;

          if (key === 'promiseQty') {
            list[pIndex].details[index].diffQty = mathUtils.sub(list[pIndex].details[index].qty, value); // 实时更新差异数量
            list[pIndex].details[index].netAmt = mathUtils.mul(value, list[pIndex].details[index].netPrice);  // 修改未税总金额
            list[pIndex].details[index].amt = mathUtils.mul(value, list[pIndex].details[index].price); // 修改含税总金额
            list[pIndex].details[index].taxAmt = mathUtils.sub(list[pIndex].details[index].amt, list[pIndex].details[index].netAmt); // 修改税额

            let totalNetAmt = 0;
            let totalAmt = 0;
            let totalDiffQty = 0;
            list[pIndex].details.map((d) => {
              totalDiffQty = mathUtils.add(totalDiffQty, d.diffQty);
              totalNetAmt = mathUtils.add(totalNetAmt, d.netAmt);
              totalAmt = mathUtils.add(totalAmt, d.amt);
            });
            list[pIndex].totalDiffQty = totalDiffQty;
            list[pIndex].netAmt = totalNetAmt;
            list[pIndex].amt = totalAmt;
            list[pIndex].taxAmt = mathUtils.sub(totalAmt, totalNetAmt);
            list[pIndex].hasDiff = totalDiffQty !== 0 || list[pIndex].demandDate !== dataUtils.ymd(list[pIndex].promiseDate);
          }
        }
      }

      yield put({
        type: 'updateState',
        payload: { list },
      });
    },

    * updatePromiseDate({ payload }, { put, select }) {
      const { list } = yield select(({ purchasingOrderForm }) => purchasingOrderForm);
      const newList = list.slice();
      const { key, index, value } = payload;

      if (key === 'deliveryTimeTo' && newList[index].promisePeriod.deliveryTimeFrom > value) {
        message.warning(order.TO_TIME_ERR); // 送货TO不可小于送货FROM
        return;
      } else if (key === 'deliveryTimeFrom' && value > newList[index].promisePeriod.deliveryTimeTo) {
        message.warning(order.FROM_TIME_ERR); // 送货FROM不可大于送货TO
        return;
      } else {
        newList[index].promisePeriod[key] = value || null;
      }

      if (key === 'promiseDate') {
        let totalDiffQty = 0;
        newList[index].details.map((d) => {
          totalDiffQty = mathUtils.add(totalDiffQty, d.diffQty);
        });
        newList[index].hasDiff = totalDiffQty !== 0 || newList[index].demandDate !== dataUtils.ymd(value);
      }

      yield put({
        type: 'updateState',
        payload: {
          list: newList,
        }
      });
    },
  },

  reducers: {

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

    updateRow(state, { payload }) {
      const { list } = state;
      const newList = list.slice();
      const { details, expanded, id } = payload;
      newList.map((l) => {
        if (l.id === id) {
          l.details = details;
          l.expanded = expanded;
        }
      });
      return {
        ...state,
        list: newList,
        exquery: true,
      };
    },

    updateCell(state, { payload }) {
      const { list } = state;
      const newList = list.slice();
      const { key, index, value } = payload;
      newList[index][key] = value;
      return {
        ...state,
        list: newList,
      };
    },

    updateChildCell(state, { payload }) {
      const { list } = state;
      const newList = list.slice();
      const { index, key, pIndex, maxVal } = payload;
      let { value } = payload;

      const reg = /^(-?\d+)(\.\d{1,4})?$/; // 校验小数点后两位

      // 校验
      if (!reg.test(value) || value.length > 8) {
        value = newList[pIndex].details[index][key];
        message.warning(order.EDIT_NUM_FAIL); // 修改数量失败
      } else if (value > maxVal) {
        value = newList[pIndex].details[index][key];
        message.warning(order.OVER_LIMIT); // 数量超限
      } else if (value > newList[pIndex].details[index].qty) {
        value = newList[pIndex].details[index][key];
        message.warn(order.PRO_QTY_ERR); // 承诺数量不可大于采购数量
      } else {
        newList[pIndex].details[index][key] = value;
      }

      return {
        ...state,
        list: newList,
      };
    },

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

  },
};
