import { config, networkUtils } from '../../utils';
import { bpmDefinition, enums } from '@utils';

const { entType } = enums;
const { bpmStatus, todoBpm, todoNonBpm } = bpmDefinition;
const { TODO } = bpmStatus;
const { request } = networkUtils;
const { api } = config;
const { bpm } = api;
const { tasks } = bpm;

// 拷贝待办初始值 - 工作流
function bpmCountInit() {
  return JSON.parse(JSON.stringify(todoBpm));
}

// 拷贝待办初始值 - 非工作流
function nonBpmCountInit() {
  return JSON.parse(JSON.stringify(todoNonBpm));
}

// 可用的待办数
export function resolveTodo(params) {
  // 工作流的待办统计
  const bpmCount = bpmTodo(params);
  // 非工作流的待办统计(即定制化的待办)
  const nonBpmCount = nonBpmTodo(params);
  // 合并
  return [...bpmCount, ...nonBpmCount];
}

// 待办链接的跳转
export function goto(params) {
  const { menu, ...record } = params;
  const itemAccessMenu = menu
    .map(m => m.menuUrl)
    .find(n => n === '/item-mgmt/itemAccess');
  return record.code !== 'SuppliperItem'
    ? record.link
    : itemAccessMenu
    ? record.link
    : record.trial;
}

// 工作流的待办统计
function bpmTodo(params) {
  let todoCount = bpmCountInit();
  const { data, menu } = params;

  // 菜单URI集合
  const menus = menu.map(m => m.menuUrl).filter(n => n !== null);

  // 根据菜单权限，过滤可用的待办列表
  todoCount = todoCount.filter(v => filterTodoParams(v, menus));

  // 赋值待办数量
  todoCount.forEach(todo => {
    if (todo.code === 'ATypeContract') {
      // ABC类合同待办合并
      todo.count =
        data['ATypeContract'] +
        (data['BCTypeContract'] ? data['BCTypeContract'] : 0);
    } else if (todo.code === 'SuppliperItem') {
      // 物料、半成品审批待办合并
      todo.count =
        data['SuppliperItem'] +
        (data['SuppliperSemiItem'] ? data['SuppliperSemiItem'] : 0);
    } else {
      todo.count = data[todo.code] ? data[todo.code] : 0;
    }
    todo.link = todo.link + `?bpmStatus=${TODO}`;
    if (todo.trial) {
      todo.trial = todo.trial + `?bpmStatus=${TODO}`;
    }
  });
  return todoCount;
}

// 根据菜单权限，过滤可用的待办列表
function filterTodoParams(todo, menus) {
  const { code, link, trial } = todo;
  if (code === 'SuppliperItem') {
    // 物料审批
    return menus.includes(link) || menus.includes(trial);
  } else {
    // 其他审批
    return menus.includes(link);
  }
}

// 非工作流的待办统计(即定制化的待办)
function nonBpmTodo(params) {
  let todoCount = nonBpmCountInit();
  const { data, user } = params;
  if (user.entType !== entType.SUPP) {
    // 目前非供应商，不具备以下待办
    return [];
  }
  todoCount.forEach(todo => {
    todo.count = data[todo.code] ? data[todo.code] : 0;
  });
  return todoCount;
}

// 待办统计接口
export async function queryCardTodo(params: Object) {
  return request({
    url: tasks,
    method: 'get',
    data: params
  });
}
