package com.gxwebsoft.open.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
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.AppService;
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;
import java.util.stream.Collectors;

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

    @ApiOperation("分页查询工单记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Task>> page(TaskParam param) {
        // 验证签名
        isCheckSign();
        // 使用关联查询
        final User loginUser = getLoginUser();
        final Integer type = loginUser.getType();
        // 如果是开发者账号则按受理人查询
        if (type.equals(6)) {
          param.setCommander(loginUser.getUserId());
        }else{
          param.setPromoter(getLoginUserId());
        }

        return success(taskService.pageRel(param));
    }

    @ApiOperation("查询全部工单记录表")
    @GetMapping()
    public ApiResult<List<Task>> list(TaskParam param) {
        // 验证签名
        isCheckSign();
        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) {
        // 验证签名
        isCheckSign();
        // 使用关联查询
        Task task = taskService.getByIdRel(id);
        task.setAppInfo(appService.getById(task.getAppId()));
      return success(task);
    }

    @ApiOperation("添加工单记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Task task) {
        // 验证签名
        isCheckSign();
        // 当前登录用户id
        Integer loginUserId = getLoginUserId();
        task.setUserId(loginUserId);
        task.setPromoter(loginUserId);
        task.setComments(StrUtil.sub(task.getContent(),0,200));
        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);
              return success("创建成功");
              }
        return fail("创建失败");
    }

    @ApiOperation("修改工单记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Task task) {
        // 验证签名
        isCheckSign();
        if (taskService.updateById(task)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除工单记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        // 验证签名
        isCheckSign();
        if (taskService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

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

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

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

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

    // 查询用户的工单ID
    private List<Integer> getTaskIds(){
      final Integer loginUserId = getLoginUserId();
      return taskUserService.list(new LambdaQueryWrapper<TaskUser>().eq(TaskUser::getUserId, loginUserId))
        .stream().map(TaskUser::getTaskId).collect(Collectors.toList());
    }

}
