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.PoliceLeaveApproval;
import com.ruoyi.database.domain.dto.ApprovaltDto;
import com.ruoyi.database.domain.gwglLog;
import com.ruoyi.database.service.ApprovalProcessService;
import com.ruoyi.database.service.PoliceLeaveApprovalService;
import com.ruoyi.database.service.gwglLogService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
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 PoliceLeaveApprovalController
 * @Author lijingtong
 * @Date 2025-05-29
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "民警请假审批")
@RequestMapping("/PoliceLeaveApproval")
public class PoliceLeaveApprovalController extends BaseController {

    private final PoliceLeaveApprovalService policeLeaveApprovalService;
    private final ISysDeptService deptService;
    private final ISysUserService userService;
    private final gwglLogService gwglLogService;
    private final ApprovalProcessService approvalsProcessService;


    @RequestMapping("/leavedDaysList")
    @ApiOperation("查询")
    public Integer leavedDaysList() {
        SysUser user = getLoginUser().getUser();
        QueryWrapper<PoliceLeaveApproval> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("submitter_id", user.getUserId());
        List<PoliceLeaveApproval> list = policeLeaveApprovalService.list(queryWrapper);
        Integer leavedDays = 0;
        for (PoliceLeaveApproval approval : list) {
            String days = approval.getDays();
            leavedDays += Integer.parseInt(days);
        }
        return leavedDays;

    }

    @RequestMapping("/list")
    @ApiOperation("查询")
    public TableDataInfo list(PoliceLeaveApproval policeLeaveApproval) {
        SysUser user = getLoginUser().getUser();
        List<SysDept> sysDepts = deptService.selectAllDeptList();
//        局领导
        List<SysUser> users = userService.getList("131000");
        List<String> leaders = users.stream().map(SysUser::getUserName).collect(Collectors.toList());
//        部门领导
        List<String> leader = sysDepts.stream().map(SysDept::getLeader).collect(Collectors.toList());
//        局党委和分管局成员
        List<String> leaderLeader = sysDepts.stream().map(SysDept::getLeaderLeader).distinct().collect(Collectors.toList());

        startPage();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String fTime = policeLeaveApproval.getFTime();
        String eTime = policeLeaveApproval.getETime();
        LocalDateTime time = LocalDateTime.parse(fTime, dtf);
        LocalDateTime time1 = LocalDateTime.parse(eTime, dtf);
        QueryWrapper<PoliceLeaveApproval> queryWrapper = new QueryWrapper<>(policeLeaveApproval);
        queryWrapper.orderByDesc("create_time");
        if (fTime != null && fTime != null) {
            queryWrapper.between("create_time", time, time1);
        }
        if (leader.contains(user.getNickName())) {
//            部门领导和政治处侍昌鑫看普通民警
            queryWrapper.eq("user_type", 0);
            queryWrapper.eq("dept_id", user.getDept());
        } else if ("096484".equals(user.getUserName())) {   //政治处侍昌鑫
            queryWrapper.in("user_type", 0, 1);
        } else if ("admin".equals(user.getUserName())) {
//            管理员看所有
        } else if ("096001".equals(user.getUserName()) || "096002".equals(user.getUserName())) {
//            主要刘成志和陈列
            queryWrapper.eq("zzc_state", 1).or().eq("user_type", 2)
                    .or().eq("dept_state", 1);
        } else if (leaderLeader.contains(user.getNickName())) {
//            分管局
            queryWrapper.eq("user_type", 1);

        } else {
//            自己看自己
            queryWrapper.eq("user_id", user.getUserId());
        }
        List<PoliceLeaveApproval> list = policeLeaveApprovalService.list(new QueryWrapper<>(policeLeaveApproval));
        long size = list.size();
        return getDataTableEnhance(list, size);
    }

    @ApiOperation("新增或修改民警请（休）假审批表 传id为修改 不传id为新增")
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody PoliceLeaveApproval policeLeaveApproval) {
        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());
        String s = OrderNumberGenerator();
        SysUser user = getLoginUser().getUser();
        if (policeLeaveApproval.getId() == null) {
            policeLeaveApproval.setName(user.getNickName());
            policeLeaveApproval.setIdCard(user.getIdCard());
            policeLeaveApproval.setPhone(user.getPhonenumber());
            policeLeaveApproval.setState(0);
            policeLeaveApproval.setCreateTime(new Date().getTime());
            policeLeaveApproval.setDeptName(user.getDept().getDeptName());
            policeLeaveApproval.setCreateBy(user.getNickName());
            policeLeaveApproval.setUserId(user.getUserId());
            policeLeaveApproval.setDeptId(user.getDeptId());
            policeLeaveApproval.setApplyNo(s);
            policeLeaveApproval.setDeptState(0);
            policeLeaveApproval.setZzcState(0);
            policeLeaveApproval.setLeaderState(0);
            UUID uuid = UUID.randomUUID();
            String uuids = uuid.toString();
            policeLeaveApproval.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(3);
            approvalProcess.setCreateTime(new Date().getTime());
            approvalProcess.setApprovalStatus(0);
            approvalProcess.setReadStatus(0);
            approvalProcess.setLeaveType(policeLeaveApproval.getLeaveType());
            approvalProcess.setStartTime(policeLeaveApproval.getStartDate());
            approvalProcess.setEndTime(policeLeaveApproval.getEndDate());
            approvalProcess.setCreateTime(new Date().getTime());
            approvalProcess.setUuid(uuids);
            approvalsProcessService.save(approvalProcess);
            gwglLog gwglLog = new gwglLog();
            gwglLog.setApplyNo(s);
            gwglLog.setResult(1);
            gwglLog.setCheckState(0);
            gwglLog.setDeptId(user.getDeptId());
            gwglLog.setDeptName(user.getDept().getDeptName());
            gwglLog.setUserId(user.getUserId());
            gwglLog.setChecker(user.getDept().getLeader());
            gwglLog.setUserName(user.getNickName());
            gwglLog.setCreateTime(System.currentTimeMillis() / 1000L);
            gwglLogService.save(gwglLog);

            if (leader.contains(user.getNickName())) {
//                单位领导
                policeLeaveApproval.setUserType(1);
            } else if (leaderLeader.contains(user.getNickName())) {
//                局党委和分管局成员
                policeLeaveApproval.setUserType(2);
            } else {
//                普通民警
                policeLeaveApproval.setUserType(0);
            }
            boolean result = policeLeaveApprovalService.save(policeLeaveApproval);
            if (!result) {
                return AjaxResult.error("新增民警请（休）假审批表失败");
            }
            return AjaxResult.success(result);
        } else {
            policeLeaveApproval.setUpdateBy(user.getNickName());
            boolean result = policeLeaveApprovalService.updateById(policeLeaveApproval);
            if (!result) {
                return AjaxResult.error("修改民警请（休）假审批表失败");
            }
            return AjaxResult.success(result);
        }
    }

    @ApiOperation("删除民警请（休）假审批表")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        boolean result = policeLeaveApprovalService.removeById(id);
        if (!result) {
            return AjaxResult.error("删除民警请（休）假审批表失败");
        }
        return AjaxResult.success(result);
    }

    @ApiOperation("查询流程详情")
    @GetMapping("/state/{id}")
    public AjaxResult state(@PathVariable Long id) {
        PoliceLeaveApproval policeLeaveApproval = policeLeaveApprovalService.getById(id);
        if (policeLeaveApproval == null) {
            return AjaxResult.error("查询approval流程失败");
        }
        return AjaxResult.success(policeLeaveApproval);
    }

    @ApiOperation("审批")
    @PostMapping("/approval")
    public AjaxResult approval(@RequestBody ApprovaltDto dto) {

        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());

        Long id = dto.getId();
        SysUser user = getLoginUser().getUser();
        SysDept sysDept = deptService.selectDeptById(user.getDeptId());
//        分管局领导
        String leaderLeader1 = sysDept.getLeaderLeader();
        Integer state = dto.getState();
        PoliceLeaveApproval policeLeaveApproval = policeLeaveApprovalService.getById(id);
        if (leader.contains(user.getNickName())) {
//            部门领导和政治处侍昌鑫看普通民警
            policeLeaveApproval.setDeptState(state);
            if (state == 2) {
                policeLeaveApproval.setState(2);
            }
            gwglLog one = gwglLogService.lambdaQuery()
                    .eq(gwglLog::getApplyNo, policeLeaveApproval.getApplyNo())
                    .orderByDesc(gwglLog::getCreateTime)
                    .last("LIMIT 1")
                    .one();
            one.setApplyNo(policeLeaveApproval.getApplyNo());
            one.setDeptId(policeLeaveApproval.getDeptId());
            one.setDeptName(policeLeaveApproval.getDeptName());
            one.setUserId(policeLeaveApproval.getUserId());
            one.setUserName(policeLeaveApproval.getName());
            one.setCreateTime(policeLeaveApproval.getCreateTime());
            one.setReason(dto.getReason());
            one.setResult(state);
            one.setType(1);
            one.setChecker(user.getNickName());
            one.setCheckTime(System.currentTimeMillis() / 1000L);
            one.setCheckState(state);
            boolean result = gwglLogService.updateById(one);


            gwglLog gwglLog = new gwglLog();
            gwglLog.setApplyNo(policeLeaveApproval.getApplyNo());
            gwglLog.setDeptId(policeLeaveApproval.getDeptId());
            gwglLog.setDeptName(policeLeaveApproval.getDeptName());
            gwglLog.setUserId(policeLeaveApproval.getUserId());
            gwglLog.setUserName(policeLeaveApproval.getName());
            gwglLog.setCreateTime(System.currentTimeMillis() / 1000L);
            gwglLog.setResult(0);
            gwglLog.setType(policeLeaveApproval.getLeaveType());
            gwglLog.setChecker("侍昌鑫");

            gwglLog.setCheckState(0);
            boolean result1 = gwglLogService.save(gwglLog);
        } else if ("096484".equals(user.getUserName())) {
            //政治处侍昌鑫
            policeLeaveApproval.setZzcState(state);
            if (state == 2) {
                policeLeaveApproval.setState(2);
            }
            if (policeLeaveApproval.getUserType() == 0) {
//                政治处审核普通民警
                gwglLog one = gwglLogService.lambdaQuery()
                        .eq(gwglLog::getApplyNo, policeLeaveApproval.getApplyNo())
                        .orderByDesc(gwglLog::getCreateTime)
                        .last("LIMIT 1")
                        .one();
                one.setApplyNo(policeLeaveApproval.getApplyNo());
                one.setDeptId(policeLeaveApproval.getDeptId());
                one.setDeptName(policeLeaveApproval.getDeptName());
                one.setUserId(policeLeaveApproval.getUserId());
                one.setUserName(policeLeaveApproval.getName());
                one.setCreateTime(System.currentTimeMillis() / 1000L);
                one.setResult(state);
                one.setType(1);
                one.setReason(dto.getReason());
                one.setChecker(user.getNickName());
                one.setCheckTime(System.currentTimeMillis() / 1000L);
                one.setCheckState(state);
                boolean result1 = gwglLogService.updateById(one);
                policeLeaveApproval.setState(state);
            } else {

                gwglLog gwglLog = new gwglLog();
                gwglLog.setApplyNo(policeLeaveApproval.getApplyNo());
                gwglLog.setDeptId(policeLeaveApproval.getDeptId());
                gwglLog.setDeptName(policeLeaveApproval.getDeptName());
                gwglLog.setUserId(policeLeaveApproval.getUserId());
                gwglLog.setUserName(policeLeaveApproval.getName());
                gwglLog.setCreateTime(System.currentTimeMillis() / 1000L);
                gwglLog.setResult(state);
                gwglLog.setType(policeLeaveApproval.getLeaveType());
                gwglLog.setChecker("刘成志");
                gwglLog.setCheckTime(System.currentTimeMillis() / 1000L);
                gwglLog.setCheckState(0);
                boolean result1 = gwglLogService.save(gwglLog);

                gwglLog gwglLog1 = new gwglLog();
                gwglLog1.setApplyNo(policeLeaveApproval.getApplyNo());
                gwglLog1.setDeptId(policeLeaveApproval.getDeptId());
                gwglLog1.setDeptName(policeLeaveApproval.getDeptName());
                gwglLog1.setUserId(policeLeaveApproval.getUserId());
                gwglLog1.setUserName(policeLeaveApproval.getName());
                gwglLog1.setCreateTime(System.currentTimeMillis() / 1000L);
                gwglLog1.setResult(state);
                gwglLog1.setType(policeLeaveApproval.getLeaveType());
                gwglLog1.setChecker("陈列");
                gwglLog1.setCheckTime(System.currentTimeMillis() / 1000L);
                gwglLog1.setCheckState(0);
                boolean result2 = gwglLogService.save(gwglLog);
                boolean result = approvalsProcessService.lambdaUpdate()
                        .eq(ApprovalProcess::getUuid, policeLeaveApproval.getUuid())
                        .set(ApprovalProcess::getApprovalStatus, state)
                        .set(ApprovalProcess::getCcName, leaderLeader1)
                        .set(ApprovalProcess::getReadStatus, 0)
                        .update();
            }
        } else if ("admin".equals(user.getUserName())) {
//            管理员看所有
            policeLeaveApproval.setDeptState(state);
            if (state == 2) {
                policeLeaveApproval.setState(2);
            }
            gwglLog gwglLog = new gwglLog();
            gwglLog.setApplyNo(policeLeaveApproval.getApplyNo());
            gwglLog.setDeptId(policeLeaveApproval.getDeptId());
            gwglLog.setDeptName(policeLeaveApproval.getDeptName());
            gwglLog.setUserId(policeLeaveApproval.getUserId());
            gwglLog.setUserName(policeLeaveApproval.getName());
            gwglLog.setCreateTime(policeLeaveApproval.getCreateTime());
            gwglLog.setReason(policeLeaveApproval.getReason());
            gwglLog.setResult(state);
            gwglLog.setType(policeLeaveApproval.getLeaveType());
            gwglLog.setReason(policeLeaveApproval.getReason());
            gwglLog.setChecker(user.getNickName());
            gwglLog.setCheckTime(System.currentTimeMillis() / 1000L);
            gwglLog.setCheckState(state);
            boolean result1 = gwglLogService.save(gwglLog);

        } else if ("096001".equals(user.getUserName()) || "096002".equals(user.getUserName())) {
//            刘成志和陈列
            if (state == 2) {
                policeLeaveApproval.setState(2);
            }
            policeLeaveApproval.setLeaderState(state);
            /*gwglLog one = gwglLogService.lambdaQuery()
                    .eq(gwglLog::getApplyNo, policeLeaveApproval.getApplyNo())
                    .orderByDesc(gwglLog::getCreateTime)
                    .last("LIMIT 1")
                    .one();
            one.setApplyNo(policeLeaveApproval.getApplyNo());
            one.setDeptId(policeLeaveApproval.getDeptId());
            one.setDeptName(policeLeaveApproval.getDeptName());
            one.setUserId(policeLeaveApproval.getUserId());
            one.setUserName(policeLeaveApproval.getName());
            one.setCreateTime(System.currentTimeMillis() / 1000L);
            one.setResult(state);
            one.setType(1);
            one.setReason(dto.getReason());
            one.setChecker(user.getNickName());
            one.setCheckTime(System.currentTimeMillis() / 1000L);
            one.setCheckState(state);
            boolean result1 = gwglLogService.updateById(one);*/
            boolean result1 = gwglLogService.lambdaUpdate()
                    .eq(gwglLog::getApplyNo, policeLeaveApproval.getApplyNo())
                    .eq(gwglLog::getChecker, user.getNickName())
                    .set(gwglLog::getCheckState, state)
                    .set(gwglLog::getCheckTime, System.currentTimeMillis() / 1000L)
                    .set(gwglLog::getType, 1)
                    .update();
            boolean result = approvalsProcessService.lambdaUpdate()
                    .eq(ApprovalProcess::getUuid, policeLeaveApproval.getUuid())
                    .set(ApprovalProcess::getApprovalStatus, state)
                    .set(ApprovalProcess::getCcName, leaderLeader1)
                    .set(ApprovalProcess::getReadStatus, 0)
                    .update();
            policeLeaveApproval.setState(state);
            if (!result && !result1) {
                return AjaxResult.success("审批请（休）假失败");
            }
        }
        boolean result = policeLeaveApprovalService.updateById(policeLeaveApproval);

        if (!result) {
            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)));
    }
}
