package com.ruoyi.zhushi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.PageQuery;
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.exception.GlobalException;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.zhushi.entity.*;
import com.ruoyi.zhushi.mapper.NjBalanceManageMapper;
import com.ruoyi.zhushi.mapper.NjRuleConfigAndUserMapper;
import com.ruoyi.zhushi.mapper.NjRuleConfigMapper;
import com.ruoyi.zhushi.service.NjBalanceManageService;
import com.ruoyi.zhushi.service.NjRuleConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class NjRuleConfigServiceImpl implements NjRuleConfigService {

    @Autowired
    private NjRuleConfigMapper njRuleConfigMapper;

    @Autowired
    private NjRuleConfigAndUserMapper njRuleConfigAndUserMapper;

    @Autowired
    private NjBalanceManageMapper njBalanceManageMapper;
    @Autowired
    private NjBalanceManageService njBalanceManageService;
    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService iSysUserService;
    @Override
    public TableDataInfo<NjRuleConfigDTO> queryRuleConfig(NjRuleConfigDTO njRuleConfigDTO, PageQuery pageQuery) {

        // 创建查询条件
        LambdaQueryWrapper<NjRuleConfig> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(null != njRuleConfigDTO.getRuleName(), NjRuleConfig::getRuleName, njRuleConfigDTO.getRuleName());
        // 查询
        IPage<NjRuleConfigDTO> njRuleConfigDTOIPage = njRuleConfigMapper.selectVoPage(pageQuery.build(), queryWrapper, NjRuleConfigDTO.class);
        // 获取记录
        List<NjRuleConfigDTO> njRuleConfigDTOS = njRuleConfigDTOIPage.getRecords();

        njRuleConfigDTOS.forEach(nj -> {
            if(!nj.getApplicableRange()){
                LambdaQueryWrapper<NjRuleConfigAndUser> njRuleConfigAndUserLambdaQueryWrapper = Wrappers.lambdaQuery();
                njRuleConfigAndUserLambdaQueryWrapper.eq(NjRuleConfigAndUser::getNjRuleConfigId, nj.getId());
                List<NjRuleConfigAndUser> njRuleConfigAndUserDTOS = njRuleConfigAndUserMapper.selectVoList(njRuleConfigAndUserLambdaQueryWrapper, NjRuleConfigAndUser.class);
                nj.setMembers(njRuleConfigAndUserDTOS);
            }
        });

        return TableDataInfo.build(njRuleConfigDTOS);
    }

    @Override
    public Boolean  addRule(NjRuleConfigDTO njRuleConfigDTO) {
        //1.插入或者更新 规则信息
        NjRuleConfig njRuleConfig = new NjRuleConfig();
        BeanUtil.copyProperties(njRuleConfigDTO, njRuleConfig);
        njRuleConfigMapper.insertOrUpdate(njRuleConfig);


        //2.删除关联的明细用户信息
        QueryWrapper<NjRuleConfigAndUser> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("nj_rule_config_id", njRuleConfig.getId());
        njRuleConfigAndUserMapper.delete(deleteWrapper);
        //3. 删除 之前关联的用户生成的年假信息
        UpdateWrapper<NjBalanceManage> deleteNjWrapper = new UpdateWrapper<>();
        njBalanceManageMapper.delete(deleteNjWrapper);

        //4.插入本次关联的明细用户信息
        List<NjRuleConfigAndUser> njRuleConfigAndUsers = new ArrayList<>();
        if (null != njRuleConfigDTO.getMembers() && njRuleConfigDTO.getMembers().size() > 0) {
            // 遍历集合
            for (NjRuleConfigAndUser member : njRuleConfigDTO.getMembers()){
                NjRuleConfigAndUser njRuleConfigAndUser = new NjRuleConfigAndUser();

                //判断是否用户是否被其他规则选择
                LambdaQueryWrapper<NjRuleConfigAndUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(NjRuleConfigAndUser::getUserId, member.getUserId());
                List<NjRuleConfigAndUserDTO> njRuleConfigAndUserDTOS = njRuleConfigAndUserMapper.selectVoList(queryWrapper, NjRuleConfigAndUserDTO.class);
                if(null != njRuleConfigAndUserDTOS && njRuleConfigAndUserDTOS.size() > 0){
                    throw new GlobalException(member.getNickName()+"已经被其他年假规则选择！");
                }

                njRuleConfigAndUser.setNjRuleConfigId(njRuleConfig.getId());
                njRuleConfigAndUser.setRuleName(njRuleConfig.getRuleName());
                njRuleConfigAndUser.setUserId(member.getUserId());
                njRuleConfigAndUser.setUserName(member.getUserName());
                njRuleConfigAndUser.setNickName(member.getNickName());
                njRuleConfigAndUser.setJoinedDate(member.getJoinedDate());
                SysUser sysUser = iSysUserService.selectUserById(member.getUserId());
                SysDept sysDept = iSysDeptService.selectDeptById(sysUser.getDeptId());
                njRuleConfigAndUser.setDeptName(sysDept.getDeptName());
                njRuleConfigAndUsers.add(njRuleConfigAndUser);
            }
        }
        boolean i = njRuleConfigAndUserMapper.insertOrUpdateBatch(njRuleConfigAndUsers);

        // 5.重新生成年假信息
        njBalanceManageService.generateYearBalance();
        // 批量插入
        return i;

    }

    @Override
    public int delRule(long id) {
        return njRuleConfigMapper.deleteById(id);
    }

    @Override
    public int delUser(long id) {
        return njRuleConfigAndUserMapper.deleteById(id);
    }

    @Override
    public List<NjRuleConfigDTO> queryAll() {
        LambdaQueryWrapper<NjRuleConfig> queryWrapper = Wrappers.lambdaQuery();
        List<NjRuleConfigDTO> njRuleConfigDTOS = njRuleConfigMapper.selectVoList(queryWrapper, NjRuleConfigDTO.class);
        return njRuleConfigDTOS;
    }

    @Override
    public List<NjRuleConfigAndUserDTO> queryUserByRuleConfigId(Long id) {
        LambdaQueryWrapper<NjRuleConfigAndUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(NjRuleConfigAndUser::getNjRuleConfigId, id);
        List<NjRuleConfigAndUserDTO> njRuleConfigAndUserDTOS = njRuleConfigAndUserMapper.selectVoList(queryWrapper);
        return njRuleConfigAndUserDTOS;
    }
}
