package com.gxwebsoft.oa.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.MyQrCodeUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.Role;
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.param.TaskParam;
import com.gxwebsoft.oa.service.TaskCountService;
import com.gxwebsoft.oa.service.TaskRecordService;
import com.gxwebsoft.oa.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

/**
 * 任务记录表控制器
 *
 * @author 科技小王子
 * @since 2023-10-23 18:53:01
 */
@Api(tags = "任务记录表管理")
@RestController
@RequestMapping("/api/oa/task")
public class TaskController extends BaseController {
    @Resource
    private TaskService taskService;
    @Resource
    private TaskRecordService taskRecordService;
    @Resource
    private TaskCountService taskCountService;

    @ApiOperation("分页查询任务记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Task>> page(TaskParam param) {
        // 使用关联查询
      param.setLoginUserId(getLoginUserId());
      return success(taskService.pageRel(param));
    }

    @ApiOperation("查询全部任务记录表")
    @GetMapping()
    public ApiResult<List<Task>> list(TaskParam param) {
        PageParam<Task, TaskParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(taskService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(taskService.listRel(param));
    }

    @ApiOperation("根据id查询任务记录表")
    @GetMapping("/{id}")
    public ApiResult<Task> get(@PathVariable("id") Integer id) {
        // 更新阅读状态
        Task task = taskService.getByIdRel(id);
        if(!task.getLastReadUser().equals(getLoginUserId())){
          task.setIsRead(1);
          taskService.updateById(task);
        }
        return success(task);
    }

    @ApiOperation("添加任务记录表")
    @Transactional(rollbackFor = {Exception.class})
    @PostMapping()
    public ApiResult<?> save(@RequestBody Task task) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            task.setUserId(loginUser.getUserId());
            Role role = loginUser.getRoles().get(0);
            task.setRoleId(role.getRoleId());
            task.setRoleCode(role.getRoleCode());
            task.setOrganizationId(loginUser.getOrganizationId());
            task.setAvatar(loginUser.getAvatar());
            task.setNickname(loginUser.getNickname());
            task.setLastAvatar(loginUser.getAvatar());
            task.setLastReadUser(loginUser.getUserId());
            task.setLastNickname(loginUser.getNickname());
            if(task.getName() == null){
              task.setName(task.getContent());
            }
        }
        if (taskService.saveByRel(task)) {
            return success("添加成功", task);
        }
        return fail("添加失败");
    }

    @ApiOperation("修改任务记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Task task) {
        if (taskService.updateById(task)) {
            // 更新统计表
            task.setLoginUserId(getLoginUserId());
            taskService.updateCount(task);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除任务记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (taskService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加任务记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Task> list) {
        if (taskService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改任务记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Task> batchParam) {
        if (batchParam.update(taskService, "task_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("批量删除任务记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (taskService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("统计信息")
    @GetMapping("/count")
    public ApiResult<?> count(TaskParam param) {
        User loginUser = getLoginUser();
        ArrayList<Object> countNum = taskService.getCountNum(loginUser, param);
        return success("操作成功", countNum);
    }

    @ApiOperation("生成工单二维码")
    @GetMapping("/taskQRCode")
    public ApiResult<?> taskQRCode(TaskParam param, HttpServletRequest request) throws IOException {
        String url = "https://modules.gxwebsoft.com/oa/task/detail?id=".concat(param.getTaskId().toString());
        final String qrCode = MyQrCodeUtil.getTaskCode(param.getTaskId(),url);
        return success("操作成功", qrCode);
    }

    @ApiOperation("生成邀请加入二维码")
    @GetMapping("/taskJoinQRCode")
    public ApiResult<?> taskJoinQRCode(TaskParam param, HttpServletRequest request) throws IOException {
        User loginUser = getLoginUser();
        String access_token = JwtUtil.getAccessToken(request);
        String url = "https://modules.gxwebsoft.com/passport/register?type=join&dealerId=".concat(loginUser.getUserId().toString())+"&token=".concat(access_token);
        final String qrCode = MyQrCodeUtil.getUserCode(loginUser.getUserId(),url);
        return success("操作成功", qrCode);
    }


    /**
     * 每日清零
     */
    @Scheduled(cron="0 0 0 * * ?")
    public void todayTask() {
      System.out.println("每日清零任务 = ");
      final boolean update = taskCountService.update(new LambdaUpdateWrapper<TaskCount>().set(TaskCount::getToday, 0));
      System.out.println("update = " + update);
    }

    /**
     * 本月清零
     */
    @Scheduled(cron="0 0 1 * * ?")
    public void monthTask() {
      taskCountService.update(new LambdaUpdateWrapper<TaskCount>().set(TaskCount::getMonth, 0));
    }

    /**
     * 每年清零
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    public void yearTask(){
      taskCountService.update(new LambdaUpdateWrapper<TaskCount>().set(TaskCount::getYear, 0));
    }

  /**
   * 定时结算已解决待评价的工单的任务
   * 1个小时内没有用户再次提交新的回复则自动结算
   * 时间间隔2分钟执行一次
   */
  @Scheduled(cron="*/30 * * * * *")
    public void updateProgressTask() {
//      System.out.println("定时任务开始：updateProgressTask = " + DateUtil.now());
      TaskParam taskParam = new TaskParam();
      taskParam.setProgress(TOBECONFIRMED);
//      taskParam.setTaskId(689);
      taskParam.setLimit(10L);
      final PageResult<Task> result = taskService.pageRelAll(taskParam);
      if(result.getCount() == 0){
        return;
      }
      final List<Task> list = result.getList();
      if (!CollectionUtils.isEmpty(list)) {
        list.forEach(task -> {
          try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date newDate = DateUtil.offset(task.getUpdateTime(), DateField.MINUTE, 60 * 24);
            Date date1 = df.parse(newDate.toString());
            Date date2 = df.parse(DateUtil.now());
            final boolean after = date2.after(date1);
            if(after){
              // 更新工单状态
              task.setProgress(COMPLETED);
              task.setStatus(TASK_STATUS_1);
              taskService.updateByIdAll(task);
              // 待评价的工单超过24小时没有评价则自动确认
              final TaskRecord taskRecord = new TaskRecord();
              taskRecord.setTaskId(task.getTaskId());
              taskRecord.setContent("超过24小时没有评价的工单系统已自动评价");
              taskRecord.setTenantId(task.getTenantId());
              final boolean save = taskRecordService.save(taskRecord);
              System.out.println("save = " + save);
              System.out.println("超过24小时没有评价的工单已自动确认 = " + task.getTaskId());
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        });
      }
    }
}
