package com.ruoyi.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.database.domain.ApprovalProcess;
import com.ruoyi.database.domain.NonWorkingDayDrinkingReport;
import com.ruoyi.database.domain.dto.ApprovaltDto;
import com.ruoyi.database.domain.gwglLog;
import com.ruoyi.database.service.ApprovalProcessService;
import com.ruoyi.database.service.NonWorkingDayDrinkingReportService;
import com.ruoyi.database.service.gwglLogService;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Description NonWorkingDayDrinkingReportController
 * @Author lijingtong
 * @Date 2025-05-29
 */

@Api(tags = "饮酒报备单")
@RestController
@RequestMapping("nonWorkingDayDrinkingReport")
@RequiredArgsConstructor
public class NonWorkingDayDrinkingReportController extends BaseController {
    private final NonWorkingDayDrinkingReportService nonWorkingDayDrinkingReportService;
    private final ISysDeptService deptService;
    private final gwglLogService gwglLogService;
    private final ApprovalProcessService approvalsProcessService;

    @ApiOperation("查询非工作日饮酒报备单")
    @PostMapping("/list")
    public TableDataInfo query(@RequestBody NonWorkingDayDrinkingReport nonWorkingDayDrinkingReport) {
        List<SysDept> sysDepts = deptService.selectAllDeptList();
//        部门领导
        List<String> leader = sysDepts.stream().map(SysDept::getLeader).collect(Collectors.toList());
//        局党委和分管局成员
        List<String> leaderLeader = sysDepts.stream().map(SysDept::getLeaderLeader).distinct().collect(Collectors.toList());
        startPage();
        SysUser user = getLoginUser().getUser();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<NonWorkingDayDrinkingReport> queryWrapper = new QueryWrapper<>(nonWorkingDayDrinkingReport);
        queryWrapper.orderByDesc("create_time");
        String fTime = nonWorkingDayDrinkingReport.getFTime();
        String eTime = nonWorkingDayDrinkingReport.getETime();
        if (fTime != null && fTime != null) {
            LocalDateTime time = LocalDateTime.parse(fTime);
            LocalDateTime time1 = LocalDateTime.parse(eTime);
            queryWrapper.between("create_time", time, time1);
        }
//        管理员
        if (user.getUserName().equals("admin")) {
            List<NonWorkingDayDrinkingReport> list = nonWorkingDayDrinkingReportService.list(queryWrapper);
            long count = nonWorkingDayDrinkingReportService.count(queryWrapper);
            return getDataTableEnhance(list, count);
        } else if (leader.contains(user.getNickName())) {
//            单位领导
            queryWrapper.eq("dept_id", user.getDeptId());
            queryWrapper.eq("user_type", 0);
            List<NonWorkingDayDrinkingReport> list = nonWorkingDayDrinkingReportService.list(queryWrapper);
            long count = nonWorkingDayDrinkingReportService.count(queryWrapper);
            return getDataTableEnhance(list, count);
        } else if ("刘成志".equals(user.getNickName())) {
//            前、现局党委成员
            queryWrapper.eq("user_type", 2);
            List<NonWorkingDayDrinkingReport> list = nonWorkingDayDrinkingReportService.list(queryWrapper);
            long count = nonWorkingDayDrinkingReportService.count(queryWrapper);
            return getDataTableEnhance(list, count);
        } else if (leaderLeader.contains(user.getNickName())) {
//            分管局领导
            queryWrapper.eq("user_type", 1);
            List<NonWorkingDayDrinkingReport> list = nonWorkingDayDrinkingReportService.list(queryWrapper);
            long count = nonWorkingDayDrinkingReportService.count(queryWrapper);
            return getDataTableEnhance(list, count);
        } else {
//            自己
            queryWrapper.eq("user_id", user.getUserId());
            queryWrapper.eq("user_type", 1);
            List<NonWorkingDayDrinkingReport> list = nonWorkingDayDrinkingReportService.list(queryWrapper);
            long count = nonWorkingDayDrinkingReportService.count(queryWrapper);
            return getDataTableEnhance(list, count);
        }
    }

    @ApiOperation("查询非工作日饮酒报备单详情")
    @GetMapping("/detail/{id}")
    public AjaxResult detail(@PathVariable Long id) {
        NonWorkingDayDrinkingReport nonWorkingDayDrinkingReport = nonWorkingDayDrinkingReportService.getById(id);
        return AjaxResult.success(nonWorkingDayDrinkingReport);
    }

    @ApiOperation("新增或修改非工作日饮酒报备单 传id为修改 不传id为新增")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody NonWorkingDayDrinkingReport nonWorkingDayDrinkingReport) {
        List<SysDept> sysDepts = deptService.selectAllDeptList();
//        部门领导
        List<String> leader = sysDepts.stream().map(SysDept::getLeader).collect(Collectors.toList());
//        局党委和分管局成员
        List<String> leaderLeader = sysDepts.stream().map(SysDept::getLeaderLeader).distinct().collect(Collectors.toList());
        SysUser user = getLoginUser().getUser();
        if (nonWorkingDayDrinkingReport.getId() == null) {
            String s = OrderNumberGenerator();
            nonWorkingDayDrinkingReport.setCreateBy(user.getNickName());
            nonWorkingDayDrinkingReport.setState(0);
            nonWorkingDayDrinkingReport.setApplyNo(s);
            nonWorkingDayDrinkingReport.setName(user.getNickName());
            nonWorkingDayDrinkingReport.setUserId(user.getUserId());
            nonWorkingDayDrinkingReport.setDeptName(user.getDept().getDeptName());
            nonWorkingDayDrinkingReport.setDeptId(user.getDeptId());
            if (leader.contains(user.getNickName())) {
//                单位领导
                nonWorkingDayDrinkingReport.setUserType(1);
            } else if (leaderLeader.contains(user.getNickName())) {
//                局党委和分管局成员
                nonWorkingDayDrinkingReport.setUserType(2);
            } else {
//                普通民警
                nonWorkingDayDrinkingReport.setUserType(0);
            }
            UUID uuid = UUID.randomUUID();
            String uuids = uuid.toString();
            nonWorkingDayDrinkingReport.setUuid(uuids);
            ApprovalProcess approvalProcess = new ApprovalProcess();
            approvalProcess.setApprovalNo(s);
            approvalProcess.setProcessTitle("饮酒报备");
            approvalProcess.setSubmitterName(user.getNickName());
            approvalProcess.setSubmitterId(user.getUserId());
            approvalProcess.setSubmitTime(new Date().getTime());
            approvalProcess.setMatterType(4);
            approvalProcess.setApprovalStatus(0);
            approvalProcess.setReadStatus(0);
            approvalProcess.setDrinkingPlace(nonWorkingDayDrinkingReport.getDrinkPlace());
            approvalProcess.setStartTime(nonWorkingDayDrinkingReport.getDrinkTime());
            approvalProcess.setCreateTime(new Date().getTime());
            approvalProcess.setUuid(uuids);
            approvalsProcessService.save(approvalProcess);
            boolean result = nonWorkingDayDrinkingReportService.save(nonWorkingDayDrinkingReport);
            if (!result) {
                return AjaxResult.error("新增非工作日失败");
            }
            return AjaxResult.success(result);
        } else {
            nonWorkingDayDrinkingReport.setUpdateBy(user.getNickName());
            boolean result = nonWorkingDayDrinkingReportService.updateById(nonWorkingDayDrinkingReport);
            if (!result) {
                return AjaxResult.error("修改非工作日失败");
            }
            return AjaxResult.success(result);
        }

    }

    @ApiOperation("删除非工作日饮酒报备单")
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        boolean result = nonWorkingDayDrinkingReportService.removeById(id);
        if (!result) {
            return AjaxResult.error("删除非工作日inksReport失败");
        }
        return AjaxResult.success(result);
    }


    @ApiOperation("审批非工作日饮酒报备单")
    @PostMapping("/approval")
    @Transactional
    public AjaxResult approval(@RequestBody ApprovaltDto dto) {
        SysUser user = getLoginUser().getUser();
        Long id = dto.getId();
        Integer state = dto.getState();
        NonWorkingDayDrinkingReport nonWorkingDayDrinkingReport = nonWorkingDayDrinkingReportService.getById(id);
        nonWorkingDayDrinkingReport.setState(state);
        boolean result = nonWorkingDayDrinkingReportService.updateById(nonWorkingDayDrinkingReport);
        ApprovalProcess one = approvalsProcessService.lambdaQuery()
                .eq(ApprovalProcess::getApprovalNo, nonWorkingDayDrinkingReport.getApplyNo())
                .one();
        one.setApprovalStatus(state);
        boolean result2 = approvalsProcessService.updateById(one);
        gwglLog gwglLog = new gwglLog();
        gwglLog.setApplyNo(nonWorkingDayDrinkingReport.getApplyNo());
        gwglLog.setDeptId(nonWorkingDayDrinkingReport.getDeptId());
        gwglLog.setDeptName(nonWorkingDayDrinkingReport.getDeptName());
        gwglLog.setUserId(nonWorkingDayDrinkingReport.getUserId());
        gwglLog.setUserName(nonWorkingDayDrinkingReport.getName());
        gwglLog.setCreateTime(nonWorkingDayDrinkingReport.getCreateTime());
        gwglLog.setReason(nonWorkingDayDrinkingReport.getReason());
        gwglLog.setType(1);
        gwglLog.setReason(dto.getReason());
        gwglLog.setApplyNo(nonWorkingDayDrinkingReport.getApplyNo());
        gwglLog.setChecker(user.getNickName());
        gwglLog.setCheckTime(System.currentTimeMillis());
        gwglLog.setCheckState(state);
        boolean result1 = gwglLogService.save(gwglLog);
        if (!result || !result1) {
            return AjaxResult.error("审批非工作日饮酒报备单失败");
        }
        return AjaxResult.success("审批非工作日饮酒报备单成功");
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    private static final String DATA_KEY = "DDATAKEY:";

    public static String OrderNumberGenerator() {
        String format = sdf.format(new Date());
        RedisCache bean = SpringUtils.getBean(RedisCache.class);
        bean.setCacheObject(DATA_KEY + format, bean.getCacheObject(DATA_KEY + format) == null ? 1 : (Integer) (bean.getCacheObject(DATA_KEY + format)) + 1);
        return format + String.format("%04d", (Integer) (bean.getCacheObject(DATA_KEY + format)));
    }
}
