import {
  queryWorkType,
  queryWorkHours,
  queryAuthWorkHours,
  addWorkHours,
  addAuthWorkHours,
  authWorkload,
  queryProject,
  deleteWorkHour,
} from '@/services/workHours.js';
import { queryDepV2 } from '@/services/approval';
import { message } from 'antd';
import moment from 'moment';

function getDepUserTree(data, map) {
  data.title = `${data.Name}`;
  data.key = `${data.ID}`;
  data.value = `${data.ID}`;
  map.set(data.ID, data);
  if (!data.children) data.children = new Array();

  if (data.children) {
    data.children.forEach((item) => {
      getDepUserTree(item, map);
    });
  }
  return data;
}

export default {
  namespace: 'workload',
  state: {
    list: [],
    dataList: [],
    typeList: [],
    allType: {},
    subTypeList: [],
    project: [],
    projectList: { project0: [], project1: [] },
    filter: {},
    depUserTree: [],
  },

  effects: {
    *queryWorkType({ callback }, { call, put }) {
      const { data } = yield call(queryWorkType, { parent_id: -1 });
      let typeList = [];
      let allType = {};
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        allType[item.id] = item;
        if (item.parent_id == 0) {
          typeList.push(item);
        }
      }
      yield put({
        type: 'save',
        payload: { typeList, allType },
      });
      callback && callback();
    },
    *querySubType({ payload, callback }, { call, put }) {
      const { data } = yield call(queryWorkType, payload);
      callback && callback(data);
      yield put({
        type: 'save',
        payload: { subTypeList: data },
      });
    },
    /**
     *
     * payload = {s_time,e_time,user_id}
     */
    *queryAuthWorkHours({ payload, callback }, { call, put, select }) {
      const workload = yield select((s) => s.workload);
      const { typeList, filter, allType } = workload;
      // 合并新旧过滤条件
      const newFilter = {
        ...filter,
        ...payload,
      };
      let { data } = yield call(queryAuthWorkHours, newFilter);
      // let tempList = {};
      // // 根据userid与date将所有数据分类
      data.list.forEach((item) => {
        // let date = moment(item.ts).format('YYYY-MM');
        // let userId = item.User.ID;
        // if (!tempList[userId]) tempList[userId] = {};
        // if (!tempList[userId][date]) tempList[userId][date] = [];
        // tempList[userId][date].push(item);
        item.time = moment(item.ts).format('YYYY-MM-DD');
      });
      // let workList = [];
      // // 重组数据结构
      // Object.keys(tempList).forEach(userId => {
      //   Object.keys(tempList[userId]).forEach(date => {
      //     let item = tempList[userId][date][0];
      //     workList.push({
      //       date,
      //       id: item.type_id,
      //       auditState: item.audit_state,
      //       comment: item.comment,
      //       user: item.User,
      //       time: tempList[userId][date],
      //     });
      //   });
      // });

      callback && callback(data.list);

      yield put({
        type: 'save',
        payload: { list: data.list, filter: newFilter },
      });
    },
    *queryWorkHours({ payload, callback }, { call, put, select }) {
      const workload = yield select((s) => s.workload);
      const { typeList, filter, allType } = workload;
      // 合并新旧过滤条件
      const newFilter = {
        ...filter,
        ...payload,
      };
      // 有userId则查询本人工时列表,没有则查询全部待审核工时列表
      let { data } = yield call(queryWorkHours, newFilter);
      // let tempList = {};
      data.list.forEach((item) => {
        // let date = moment(item.ts).format('YYYY-MM');
        // if (!tempList[date]) tempList[date] = [];
        // tempList[date].push(item);
        item.time = moment(item.ts).format('YYYY-MM-DD');
      });
      // let workList = [];
      // Object.keys(tempList).forEach(date => {
      //   let item = tempList[date][0];
      //   workList.push({
      //     date,
      //     id: item.type_id,
      //     auditState: item.audit_state,
      //     comment: item.comment,
      //     time: tempList[date],
      //   });
      // });
      // let list = getData(data.list, allType);
      // workList = workList.concat(list);
      // console.log(workList);

      callback && callback(data.list);

      yield put({
        type: 'save',
        payload: { dataList: data.list, filter: newFilter },
      });
    },
    // 创建工时
    *addWorkHours({ payload, callback }, { call, put }) {
      const res = yield call(addWorkHours, payload);
      if (res) {
        // callback && callback();
        message.success('保存成功');
        // 创建成功
        yield put({
          type: 'queryWorkHours',
          payload: {},
          callback,
        });
      }
    },
    // 提交审核工时
    *addAuthWorkHours({ payload, callback }, { call, put }) {
      const res = yield call(addAuthWorkHours, payload);
      if (res) {
        message.success('上报成功');
        // 上报成功
        yield put({
          type: 'queryWorkHours',
          payload: {},
          callback,
        });
      }
    },
    // 审核上报的工时
    *authWorkload({ payload, callback }, { call, put }) {
      const res = yield call(authWorkload, payload);
      if (res) {
        message.success('操作成功');
        yield put({
          type: 'queryAuthWorkHours',
          payload: {},
          callback,
        });
      }
    },
    *queryProject({ payload = {}, callback }, { call, put }) {
      const res = yield call(queryProject, payload);
      if (res) {
        yield put({
          type: 'save',
          payload: {
            project: res.data.list,
          },
        });
        callback && callback();
      }
    },
    *deleteWorkHour({ payload, callback }, { call, put }) {
      const res = yield call(deleteWorkHour, payload);
      if (!res) return;
      yield put({
        type: 'queryWorkHours',
        payload: {},
        callback,
      });
    },
    *fetchDepV2({ payload, callback }, { call, put }) {
      const response = yield call(queryDepV2, { pageSize: 999999 });
      if (response) {
        const depUserMap = new Map();
        const depUserTree = response.data.list.map((item) => {
          return getDepUserTree(item, depUserMap);
        });
        yield put({
          type: 'save',
          payload: { depUserTree, depUserMap },
        });
      }
    },
  },

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

function getData(list, allType) {
  var data = {},
    resData = [];
  // 将数据根据项目以及类别进行分类
  list.forEach((item) => {
    let { project_id, type_id } = item;
    // 初始化数据
    if (!data[project_id]) {
      data[project_id] = {};
    }
    if (!data[project_id][type_id]) {
      data[project_id][type_id] = [];
    }

    data[project_id][type_id].push(item);
  });
  Object.keys(data).forEach((projectId) => {
    let projectData = {
      id: projectId,
      type: 1,
      key: `${1}-${projectId}`,
      auditState: null,
      time: [], // 项目不需要工时
      children: [],
    };
    Object.keys(data[projectId]).forEach((typeId) => {
      let time = data[projectId][typeId].sort(
        (a, b) => new Date(a.ts) - new Date(b.ts),
      );
      let typeData = {
        id: typeId,
        type: 2,
        key: time[0].id,
        auditState: time[0].audit_state,
        time,
      };
      projectData.children.push(typeData);
    });
    resData.push(projectData);
  });
  // projectId = '0' 表示无项目,须根据一级分类展示
  let index = resData.findIndex((item) => item.id == '0');
  if (index != -1) {
    let data = {};
    let subTypeArr = resData[index].children;
    // 清空
    resData.splice(index, 1);
    subTypeArr.forEach((item) => {
      let parentId = allType[item.id].parent_id;
      if (!data[parentId]) data[parentId] = [];

      data[parentId].push(item);
    });
    Object.keys(data).forEach((typeId) => {
      resData.push({
        id: typeId, //大分类 ID
        type: 0,
        key: `${0}-${typeId}`,
        auditState: null,
        time: [], // 大分类不需要工时
        children: data[typeId],
      });
    });
  }

  return resData;
}
