package com.ruoyi.zhushi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zhushi.entity.NjBalanceManage;
import com.ruoyi.zhushi.entity.NjBalanceManageDetail;
import com.ruoyi.zhushi.entity.NjBalanceManageDetailDTO;
import com.ruoyi.zhushi.entity.NjRuleConfigDTO;
import com.ruoyi.zhushi.mapper.NjBalanceManageDetailMapper;
import com.ruoyi.zhushi.mapper.NjBalanceManageMapper;
import com.ruoyi.zhushi.mapper.NjRuleConfigAndUserMapper;
import com.ruoyi.zhushi.service.NjBalanceManageDetailService;
import com.ruoyi.zhushi.service.NjBalanceManageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.*;
@Service
@Transactional(rollbackFor = Exception.class)
public class NjBalanceManageDetailServiceImpl implements NjBalanceManageDetailService {

    @Autowired
    private NjBalanceManageMapper njBalanceManageMapper;
    @Autowired
    private NjBalanceManageDetailMapper njBalanceManageDetailMapper;
    @Autowired
    private ISysUserService iSysUserService;


    //查询年假申请信息
    @Override
    public TableDataInfo<NjBalanceManageDetailDTO> queryPageList(NjBalanceManageDetailDTO njBalanceManageDetailDTO, PageQuery pageQuery) {
        LambdaQueryWrapper<NjBalanceManageDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(njBalanceManageDetailDTO.getUserName()!= null, NjBalanceManageDetail::getUserName, njBalanceManageDetailDTO.getUserName());
        queryWrapper.like(njBalanceManageDetailDTO.getNickName()!= null, NjBalanceManageDetail::getNickName, njBalanceManageDetailDTO.getNickName());
        IPage<NjBalanceManageDetailDTO> njBalanceManageDTOS = njBalanceManageDetailMapper.selectVoPage(pageQuery.build(), queryWrapper, NjBalanceManageDetailDTO.class);
        return TableDataInfo.build(njBalanceManageDTOS);
    }

    //单条插入
    @Override
    public boolean insert(NjBalanceManageDetailDTO njBalanceManageDetailDTO) {
        //校验是否 休假的那天被申请过了
        QueryWrapper<NjBalanceManageDetail> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",njBalanceManageDetailDTO.getUserId());
        queryWrapper.in("status",new String[]{"0","1","2"});//待提交 待审批 审批通过
        List<NjBalanceManageDetail> list = njBalanceManageDetailMapper.selectList(queryWrapper);
        if (list!=null&&list.size()>0) {
            for (NjBalanceManageDetail njBalanceManageDetail:list) {
                //本次申请的日期分割 然后循环判断
                String[] applyDates=  njBalanceManageDetailDTO.getApplyDates().split(",");
                for (String applyDate:applyDates) {
                    if (njBalanceManageDetail.getApplyDates().contains(applyDate)) {
                        throw new GlobalException("本次申请的年假日期"+applyDate+" 已经被申请过了！");
                    }
                }

            }
        }
        NjBalanceManageDetail njBalanceManageDetail = new NjBalanceManageDetail();
        BeanUtils.copyProperties(njBalanceManageDetailDTO,njBalanceManageDetail);
        SysUser sysUser = iSysUserService.selectUserById(njBalanceManageDetailDTO.getUserId());
        njBalanceManageDetail.setUserName(sysUser.getUserName());
        njBalanceManageDetail.setNickName(sysUser.getNickName());
        njBalanceManageDetail.setDeptName(sysUser.getDept().getDeptName());
        njBalanceManageDetail.setStatus("2");//审核通过
        //年假申请明细 插入
        int i = njBalanceManageDetailMapper.insert(njBalanceManageDetail);
        int j = 0;
        //年假余额表 修改已使用和未使用年假
        if (i==1) {
            //查询这个用户
            BigDecimal used_days = new BigDecimal(0);
            QueryWrapper detailQuery =new QueryWrapper();
            detailQuery.select("sum(used_day) used_days");
            detailQuery.eq("user_id",njBalanceManageDetailDTO.getUserId());
            detailQuery.eq("status","2");//审核通过的
            List<Map> detailList= njBalanceManageDetailMapper.selectMaps(detailQuery);
            if (detailList!=null&&detailList.size()>0) {
                Map map =detailList.get(0);
                used_days =  (BigDecimal )map.get("used_days");
            }
            UpdateWrapper<NjBalanceManage> updateWrapper = new UpdateWrapper();
            updateWrapper.set("used_day",used_days);
            updateWrapper.setSql("unused_day = annual_leave - " + used_days);
            updateWrapper.eq("user_id",njBalanceManageDetailDTO.getUserId());
            j = njBalanceManageMapper.update(null,updateWrapper);
        }
        if (i==1&&j==1) {
            return true;
        } else {
            throw new RuntimeException("年假申请失败！请联系软件部门");
        }

    }
    //日历查询
    @Override
    public List<Map<String, String>> calendarQuery() {
        // 用一个 Map 记录每个日期对应的人员
        Map<String, Set<String>> dateToNamesMap = new HashMap<>();

        int currentYear = LocalDate.now().getYear();
        QueryWrapper<NjBalanceManageDetail> queryWrapper = new QueryWrapper();
        queryWrapper.eq(" YEAR(create_time)",currentYear);
        queryWrapper.eq("status","2");//审核通过的
        List<NjBalanceManageDetail> list =  njBalanceManageDetailMapper.selectList(queryWrapper);


        if (list!=null && list.size()>0) {
            for (NjBalanceManageDetail njBalanceManageDetail : list) {
                String applyDates = njBalanceManageDetail.getApplyDates();
                String nickName = njBalanceManageDetail.getNickName();
                if (applyDates != null && !applyDates.isEmpty()) {
                    String[] dates = applyDates.split(",");
                    for (String date : dates) {
                        dateToNamesMap
                            .computeIfAbsent(date, k -> new LinkedHashSet<>())
                            .add(nickName); // 用 Set 去重
                    }
                }
            }
        }
        // 最后构建List<Map<String, String>> 格式
        List<Map<String, String>> resultList = new ArrayList<>();
        for (Map.Entry<String, Set<String>> entry : dateToNamesMap.entrySet()) {
            Map<String, String> map = new HashMap<>();
            map.put(entry.getKey(), String.join(",", entry.getValue()));
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public boolean cancelByIds(Collection<Long> ids) {
        QueryWrapper <NjBalanceManageDetail> queryWrapper =new QueryWrapper();
        queryWrapper.in("id",ids);
        List<NjBalanceManageDetail> list = njBalanceManageDetailMapper.selectList(queryWrapper);
        if (list!=null&&list.size()>0) {
            //还原 年假
            for (NjBalanceManageDetail njBalanceManageDetail:list) {
                Long userId = njBalanceManageDetail.getUserId();
                UpdateWrapper<NjBalanceManage> updateWrapper = new UpdateWrapper();
                updateWrapper.setSql("used_day=used_day-"+njBalanceManageDetail.getUsedDay());
                updateWrapper.setSql("unused_day = unused_day+"+njBalanceManageDetail.getUsedDay());
                updateWrapper.eq("user_id",userId);
                njBalanceManageMapper.update(null,updateWrapper);
            }
        }
        UpdateWrapper <NjBalanceManageDetail> queryDetailWrapper =new UpdateWrapper();
        queryDetailWrapper.set("status","4");//作废（撤销）
        queryDetailWrapper.in("id",ids);
        return njBalanceManageDetailMapper.update(null,queryDetailWrapper)>0;
    }

}
