package com.gxwebsoft.oa.controller;

import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.oa.entity.Task;
import com.gxwebsoft.oa.entity.TaskRecord;
import com.gxwebsoft.oa.entity.TaskUser;
import com.gxwebsoft.oa.param.TaskParam;
import com.gxwebsoft.oa.service.NoticeService;
import com.gxwebsoft.oa.service.TaskRecordService;
import com.gxwebsoft.oa.service.TaskService;
import com.gxwebsoft.oa.service.TaskUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 工单记录表控制器
 *
 * @author WebSoft
 * @since 2022-11-16 11:21:43
 */
@Api(tags = "工单记录表管理")
@RestController
@RequestMapping("/api/oa/task")
public class TaskController extends BaseController {
    @Resource
    private TaskService taskService;
    @Resource
    private TaskRecordService taskRecordService;
    @Resource
    private TaskUserService taskUserService;
    @Resource
    private UserService userService;
    @Resource
    private NoticeService noticeService;

    @PreAuthorize("hasAuthority('oa:task:list')")
    @OperationLog
    @ApiOperation("分页查询工单记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Task>> page(TaskParam param) {
        // 使用关联查询
        final User loginUser = getLoginUser();
        final Integer type = loginUser.getType();
        loginUser.getRoles().forEach(d -> {
          if(!StrUtil.equals(d.getRoleCode(),"superAdmin") && !StrUtil.equals(d.getRoleCode(),"admin")){
            // 如果是开发者账号则按受理人查询
            if (type.equals(6)) {
              param.setCommander(loginUser.getUserId());
            }else{
              param.setPromoter(getLoginUserId());
            }
          }
        });
        return success(taskService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('oa:task:list')")
    @OperationLog
    @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));
    }

    @PreAuthorize("hasAuthority('oa:task:list')")
    @OperationLog
    @ApiOperation("根据id查询工单记录表")
    @GetMapping("/{id}")
    public ApiResult<Task> get(@PathVariable("id") Integer id) {
        // 使用关联查询
      return success(taskService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('oa:task:save')")
    @OperationLog
    @ApiOperation("添加工单记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Task task) {
        // 记录用户id
        final Integer loginUserId = getLoginUserId();
        Integer promoter = task.getPromoter();
        task.setUserId(loginUserId);
        task.setComments(StrUtil.sub(task.getContent(),0,200));
        task.setPromoter(promoter != null ? promoter : loginUserId);
        task.setLastReadUser(loginUserId);
        if (taskService.save(task)) {
            // 添加聊天内容明细
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUserId(loginUserId);
            taskRecord.setContent(task.getContent());
            taskRecord.setTaskId(task.getTaskId());
            taskRecord.setFiles(task.getFiles());
            taskRecordService.save(taskRecord);
            // 添加工单成员
            TaskUser taskUser = new TaskUser();
            taskUser.setUserId(loginUserId);
            taskUser.setTaskId(task.getTaskId());
            taskUserService.save(taskUser);
            // 发待办提醒
            if(task.getCommander() != null){
              noticeService.addTodo(task);
            }
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('oa:task:update')")
    @OperationLog
    @ApiOperation("修改工单记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Task task) {
        if(task.getCommander() != null && userService.getById(task.getCommander()) == null){
            return fail("受理人不存在");
          }
        if (taskService.updateById(task)) {
              // 发待办提醒
              noticeService.addTodo(task);
              return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('oa:task:remove')")
    @OperationLog
    @ApiOperation("删除工单记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (taskService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('oa:task:save')")
    @OperationLog
    @ApiOperation("批量添加工单记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Task> list) {
        if (taskService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('oa:task:update')")
    @OperationLog
    @ApiOperation("批量修改工单记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Task> batchParam) {
        if (batchParam.update(taskService, "task_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('oa:task:remove')")
    @OperationLog
    @ApiOperation("批量删除工单记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (taskService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('oa:task:list')")
    @ApiOperation("统计信息")
    @GetMapping("/count")
    public ApiResult<?> count(TaskParam param){
      // 验证签名
      isCheckSign();
      User loginUser = getLoginUser();
      ArrayList<Object> countNum = taskService.getCountNum(loginUser,param);
      return success("操作成功",countNum);
    }

}
