package com.gxwebsoft.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.oa.entity.Task;
import com.gxwebsoft.oa.entity.TaskCount;
import com.gxwebsoft.oa.entity.TaskRecord;
import com.gxwebsoft.oa.mapper.TaskMapper;
import com.gxwebsoft.oa.param.TaskParam;
import com.gxwebsoft.oa.service.TaskCountService;
import com.gxwebsoft.oa.service.TaskRecordService;
import com.gxwebsoft.oa.service.TaskService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.gxwebsoft.common.core.constants.TaskConstants.*;

/**
 * 任务记录表Service实现
 *
 * @author 科技小王子
 * @since 2023-10-23 18:53:01
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {
  @Resource
  private TaskRecordService taskRecordService;
  @Resource
  private TaskCountService taskCountService;

  @Override
  public PageResult<Task> pageRel(TaskParam param) {
    PageParam<Task, TaskParam> page = new PageParam<>(param);
    page.setDefaultOrder("create_time desc");
    List<Task> list = baseMapper.selectPageRel(page, param);
    return new PageResult<>(list, page.getTotal());
  }

  @Override
  public List<Task> listRel(TaskParam param) {
    List<Task> list = baseMapper.selectListRel(param);
    // 排序
    PageParam<Task, TaskParam> page = new PageParam<>();
    //page.setDefaultOrder("create_time desc");
    return page.sortRecords(list);
  }

  @Override
  public Task getByIdRel(Integer taskId) {
    TaskParam param = new TaskParam();
    param.setTaskId(taskId);
    return param.getOne(baseMapper.selectListRel(param));
  }

  @Override
  public ArrayList<Object> getCountNum(User loginUser, TaskParam param) {
    Integer type = loginUser.getType();
    final Integer userId = param.getUserId();
//    if (param.getUserId() != null) {
//      this.userId = param.getUserId();
//    }else {
//      this.userId = loginUser.getUserId();
//    }

    AtomicInteger count1 = new AtomicInteger(count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, 0)));
    AtomicInteger count2 = new AtomicInteger(count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, 1)));
    // 非管理员仅可浏览和自己相关的工单
    loginUser.getRoles().forEach(d -> {

      if (type.equals(6)) {
        count1.set(count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, 0).eq(Task::getCommander, userId)));
        count2.set(count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, 1).eq(Task::getCommander, userId)));
      }
      if (type.equals(10)) {
        count1.set(count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, 0).eq(Task::getPromoter, userId)));
        count2.set(count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, 1).eq(Task::getPromoter, userId)));
      }
    });
    JSONObject json1 = new JSONObject();
    json1.put("tab", "待处理");
    json1.put("key", "0");
    json1.put("count", count1);
    JSONObject json2 = new JSONObject();
    json2.put("tab", "已完成");
    json2.put("key", "1");
    json2.put("count", count2);
    ArrayList<Object> objects = new ArrayList<>();
    objects.add(json1);
    objects.add(json2);
    return objects;
  }

  /**
   * 提交工单记录
   */
  @Override
  public boolean saveByRel(Task task) {
    // 保存工单
    save(task);
    // 添加第一条记录
    TaskRecord taskRecord = BeanUtil.copyProperties(task, TaskRecord.class);
    taskRecord.setCreateTime(new Date());
    taskRecord.setUpdateTime(new Date());
    taskRecordService.save(taskRecord);
    // 添加统计记录表
    if (taskCountService.count(new LambdaQueryWrapper<TaskCount>().eq(TaskCount::getUserId, task.getUserId())) == 0) {
      final TaskCount taskCount = new TaskCount();
      taskCount.setUserId(task.getUserId());
      taskCount.setRoleId(task.getRoleId());
      taskCount.setRoleCode(task.getRoleCode());
      taskCount.setOrganizationId(task.getOrganizationId());
      taskCountService.save(taskCount);
    }
    // 更新统计表
    TaskCount taskCount = taskCountService.getByUserId(task.getUserId());
    taskCount.setPending(taskCount.getPending() + 1);
    taskCountService.updateById(taskCount);
    return true;
  }

  @Override
  public void updateCount(Task param) {
    final Task task = getById(param.getTaskId());
    // 当前时间 2023-11-04 21:47:16
    final String now = DateUtil.now();
    // 今天日期 2023-11-04
    final String today = DateUtil.today();
    // 今天开始的时间 2023-11-04 00:00:00
    final DateTime dayStart = DateUtil.beginOfDay(DateUtil.date());
    // 今天结束的时间 2023-11-04 00:00:00
    final DateTime dayEnd = DateUtil.offsetDay(dayStart, 1);
    // 当前月份的开始时间 2023-11-01 00:00:00
    final DateTime monthStart = DateUtil.beginOfMonth(DateUtil.date());
    // 当期月份的结束时间 2023-12-01 00:00:00
    final DateTime monthEnd = DateUtil.offsetMonth(monthStart, 1);
    // 今年的开始时间
    final DateTime yearStart = DateUtil.beginOfYear(DateUtil.date());
    // 获取年的值
    final int year = DateUtil.year(yearStart);
    // 是否闰年
    final boolean leapYear = DateUtil.isLeapYear(year);
    // 获取今年的总天数
    int daysByYear = leapYear ? 366 : 365;
    // 今年的结束时间
    final DateTime yearEnd = DateUtil.offsetDay(yearStart, daysByYear);
    // 创建日期范围生成器
    DateRange range = DateUtil.range(monthStart, monthEnd, DateField.MONTH);

    // 查询待处理的工单总数量
    final int pendingTasks = count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, TASK_STATUS_0));
    // 查询今日已处理的工单数量
    final int todayTasks = count(new LambdaQueryWrapper<Task>().between(Task::getUpdateTime, dayStart, dayEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus,TASK_STATUS_1));
    // 查询本月已处理的工单数量
    final int monthTasks = count(new LambdaQueryWrapper<Task>().between(Task::getUpdateTime, monthStart, monthEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus,TASK_STATUS_1));
    // 查询本年已处理的工单总数量
    final int yearTasks = count(new LambdaQueryWrapper<Task>().between(Task::getCreateTime, yearStart, yearEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1));
    // 查询公司总处理工单数量
    final int totalTasks = count(new LambdaQueryWrapper<Task>().eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1));

    // 查询当前登录用户待处理的工单数量
    final int userPendingTasks = count(new LambdaQueryWrapper<Task>().eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getUserId,task.getUserId()));
    // 查询当前登录用户今日已处理的工单数量
    final int userTodayTasks = count(new LambdaQueryWrapper<Task>().between(Task::getUpdateTime,dayStart,dayEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getUserId,task.getUserId()));
    // 查询当前登录用户本月已处理的工单数量
    final int userMonthTasks = count(new LambdaQueryWrapper<Task>().between(Task::getUpdateTime,monthStart,monthEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getUserId,task.getUserId()));
    // 查询当前登录用户本年已处理的工单数量
    final int userYearTasks = count(new LambdaQueryWrapper<Task>().between(Task::getCreateTime,yearStart,yearEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getUserId,task.getUserId()));
    // 查询当前登录用户已处理的总工单数量
    final int userTotalTasks = count(new LambdaQueryWrapper<Task>().eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getUserId,task.getUserId()));

    // 查询受理人待处理的工单数量
    final int commanderPendingTasks = count(new LambdaQueryWrapper<Task>().eq(Task::getStatus, TASK_STATUS_0).eq(Task::getCommander,task.getCommander()));
    // 查询受理人今日已处理的工单数量
    final int commanderTodayTasks = count(new LambdaQueryWrapper<Task>().between(Task::getUpdateTime,dayStart,dayEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getCommander,task.getCommander()));
    // 查询受理人本月已处理的工单数量
    final int commanderMonthTasks = count(new LambdaQueryWrapper<Task>().between(Task::getUpdateTime,monthStart,monthEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getCommander,task.getCommander()));
    // 查询受理人本年已处理的工单数量
    final int commanderYearTasks = count(new LambdaQueryWrapper<Task>().between(Task::getCreateTime,yearStart,yearEnd).eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getCommander,task.getCommander()));
    // 查询受理人已处理的总工单数量
    final int commanderTotalTasks = count(new LambdaQueryWrapper<Task>().eq(Task::getProgress,COMPLETED).eq(Task::getStatus, TASK_STATUS_1).eq(Task::getCommander,task.getCommander()));

    // 统计工单发起人
    if (taskCountService.count(new LambdaQueryWrapper<TaskCount>().eq(TaskCount::getUserId,task.getUserId())) == 0) {
      final TaskCount taskCount = new TaskCount();
      taskCount.setUserId(task.getUserId());
      taskCountService.save(taskCount);
    }
    TaskCount user = taskCountService.getByUserId(task.getUserId());
    System.out.println("user = " + user);
    user.setPending(userPendingTasks);
    user.setToday(userTodayTasks);
    user.setMonth(userMonthTasks);
    user.setYear(userYearTasks);
    user.setTotal(userTotalTasks);
    taskCountService.updateById(user);
    if(!user.getUserId().equals(task.getCommander())){
      // 统计工单受理人
      TaskCount commander = taskCountService.getByUserId(task.getCommander());
      if(commander != null){
        commander.setPending(commanderPendingTasks);
        commander.setToday(commanderTodayTasks);
        commander.setMonth(commanderMonthTasks);
        commander.setYear(commanderYearTasks);
        commander.setTotal(commanderTotalTasks);
        taskCountService.updateById(commander);
      }
    }
    // 统计公司数据
    if (taskCountService.count(new LambdaQueryWrapper<TaskCount>().eq(TaskCount::getUserId,0).eq(TaskCount::getRoleCode, "superAdmin")) == 0) {
      final TaskCount taskCount = new TaskCount();
      taskCount.setRoleCode("superAdmin");
      taskCountService.save(taskCount);
    }
    final TaskCount superAdmin = taskCountService.getByUserId(param.getLoginUserId());
    if (superAdmin.getRoleCode().equals("superAdmin") || superAdmin.getRoleCode().equals("admin")) {
      superAdmin.setPending(pendingTasks);
      superAdmin.setToday(todayTasks);
      superAdmin.setMonth(monthTasks);
      superAdmin.setYear(yearTasks);
      superAdmin.setTotal(totalTasks);
      taskCountService.updateById(superAdmin);
    }
  }

  @Override
  public PageResult<Task> pageRelAll(TaskParam param) {
    PageParam<Task, TaskParam> page = new PageParam<>(param);
    page.setDefaultOrder("create_time desc");
    List<Task> list = baseMapper.selectPageRelAll(page, param);
    return new PageResult<>(list, page.getTotal());
  }

  @Override
  public void updateByIdAll(Task task) {
    baseMapper.updateByTaskId(task);
  }

}
