package org.dromara.zjk.expert.retirementRecords.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zjk.domain.ZjkExpert;
import org.dromara.zjk.enums.ZjkExpertTypeEnum;
import org.dromara.zjk.expert.retirementRecords.domain.ZjkRetirementRecords;
import org.dromara.zjk.expert.retirementRecords.domain.bo.ZjkRetirementRecordsBo;
import org.dromara.zjk.expert.retirementRecords.domain.vo.ZjkRetirementRecordsVo;
import org.dromara.zjk.expert.retirementRecords.mapper.ZjkRetirementRecordsMapper;
import org.dromara.zjk.expert.retirementRecords.service.IZjkRetirementRecordsService;
import org.dromara.zjk.mapper.ZjkExpertMapper;
import org.dromara.zjk.service.IZjkExpertService;
import org.dromara.zjk.service.impl.ZjkExpertServiceImpl;
import org.dromara.zjk.utils.IdCardUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 专家退休记录Service业务层处理
 *
 * @author zhangzhou
 * @date 2024-11-19
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ZjkRetirementRecordsServiceImpl implements IZjkRetirementRecordsService {

    private final ZjkRetirementRecordsMapper baseMapper;

    private final ZjkExpertMapper zjkExpertMapper;

    @Autowired
    private IZjkExpertService zjkExpertService;


    /**
     * 查询专家退休记录
     *
     * @param id 主键
     * @return 专家退休记录
     */
    @Override
    public ZjkRetirementRecordsVo queryById(Long id){
        return baseMapper.queryById(id);
    }

    /**
     * 分页查询专家退休记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 专家退休记录分页列表
     */
    @Override
    public TableDataInfo<ZjkRetirementRecordsVo> queryPageList(ZjkRetirementRecordsBo bo, PageQuery pageQuery) {
        Page<ZjkRetirementRecordsVo> result = baseMapper.queryRetirement(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的专家退休记录列表
     *
     * @param bo 查询条件
     * @return 专家退休记录列表
     */
    @Override
    public List<ZjkRetirementRecordsVo> queryList(ZjkRetirementRecordsBo bo) {
        LambdaQueryWrapper<ZjkRetirementRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjkRetirementRecords> buildQueryWrapper(ZjkRetirementRecordsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjkRetirementRecords> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getExpertStatus() != null, ZjkRetirementRecords::getExpertStatus, bo.getExpertStatus());
        return lqw;
    }

    /**
     * 新增专家退休记录
     *
     * @param bo 专家退休记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ZjkRetirementRecordsBo bo) {
        // 专家发起离职申请  根据用户 id 获取专家信息
        Long userId = LoginHelper.getUserId();
        ZjkExpert zjkExpertVo = zjkExpertMapper.selectOne(new LambdaQueryWrapper<ZjkExpert>()
            .eq(ZjkExpert::getUserId, userId)
            .eq(ZjkExpert::getDeleteFlag, UserConstants.DEL_FLAG_NORMAL));
        if (zjkExpertVo == null) {
            throw new ServiceException("当前用户不存在专家信息");
        }
        zjkExpertVo.setRetirementTime(new Date());
        zjkExpertVo.setStatus(ZjkExpertTypeEnum.ESIGN.getCode());

        zjkExpertMapper.updateById(zjkExpertVo);
        zjkExpertService.refreshHmac(zjkExpertVo.getExpertId());
        ZjkRetirementRecords add = MapstructUtils.convert(bo, ZjkRetirementRecords.class);
        validEntityBeforeSave(add);
        add.setUserId(zjkExpertVo.getUserId());
        add.setExpertId(zjkExpertVo.getExpertId());
        add.setRetirementTime(zjkExpertVo.getRetirementTime());
        add.setExpertStatus(ZjkExpertTypeEnum.ESIGN.getCodeAsString());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改专家退休记录
     *
     * @param bo 专家退休记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZjkRetirementRecordsBo bo) {
        ZjkRetirementRecords update = MapstructUtils.convert(bo, ZjkRetirementRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjkRetirementRecords entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除专家退休记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

/*    @Override
    public void executeRetirement() {
        // 获取开始时间
        long startTime = System.currentTimeMillis();
        // 用户修改集合
        List<ZjkExpert> updateExpert = new ArrayList<>();
        // 退休记录集合
        List<ZjkRetirementRecords> zjkRetirementRecordsList = new ArrayList<>();
        // 获取所有的专家信息
        List<ZjkExpert> zjkExpertList = zjkExpertMapper.selectExpertAllList();
        for (ZjkExpert expert : zjkExpertList) {
            // 条件：年龄大于等于 65岁则进行退休流程
            boolean isEligibleForInspection = !IdCardUtils.isAgeUnder65(expert.getIdCard());
            if (isEligibleForInspection) {
                // 将符合条件的专家添加到更新列表中
                expert.setStatus(ZjkExpertTypeEnum.RETIRE.getCode());
                expert.setRetirementTime(new Date());
                updateExpert.add(expert);
                // 创建退休记录并添加到退休记录集合
                ZjkRetirementRecords record = new ZjkRetirementRecords();
                record.setUserId(expert.getUserId());
                record.setExpertId(expert.getExpertId());
                record.setRetirementTime(expert.getRetirementTime());
                record.setExpertStatus(ZjkExpertTypeEnum.RETIRE.getCodeAsString());
                record.setReason("退休年龄达标");
                zjkRetirementRecordsList.add(record);
            }
        }
        baseMapper.insertBatch(zjkRetirementRecordsList);
        zjkExpertMapper.insertBatch(zjkExpertList);
        // 获取结束时间
        long endTime = System.currentTimeMillis();
        // 计算方法执行时间（毫秒）
        long duration = endTime - startTime;
        log.info("专家退休方法执行时间: " + duration + " 毫秒");
    }*/
@Override
public void executeRetirement() {
    long startTime = System.currentTimeMillis();

    List<ZjkExpert> updateExpert = new ArrayList<>();
    List<ZjkRetirementRecords> zjkRetirementRecordsList = new ArrayList<>();

    List<ZjkExpert> zjkExpertList = zjkExpertMapper.selectExpertAllList();

    for (ZjkExpert expert : zjkExpertList) {
        if (!IdCardUtils.isAgeUnder65(expert.getIdCard())) {
            expert.setStatus(ZjkExpertTypeEnum.RETIRE.getCode());
            expert.setRetirementTime(new Date());
            updateExpert.add(expert);

            ZjkRetirementRecords record = new ZjkRetirementRecords();
            record.setUserId(expert.getUserId());
            record.setExpertId(expert.getExpertId());
            record.setRetirementTime(expert.getRetirementTime());
            record.setExpertStatus(ZjkExpertTypeEnum.RETIRE.getCodeAsString());
            record.setReason("退休年龄达标");
            zjkRetirementRecordsList.add(record);
        }
    }

    if (!zjkRetirementRecordsList.isEmpty()) {
        baseMapper.insertBatch(zjkRetirementRecordsList);
    }

    if (!updateExpert.isEmpty()) {
        zjkExpertMapper.updateBatchById(updateExpert);
    }

    // 如果需要重新计算 HMAC
    for (ZjkExpert expert : updateExpert) {
        zjkExpertService.refreshHmac(expert.getExpertId());
    }

    long endTime = System.currentTimeMillis();
    log.info("专家退休方法执行时间: {} 毫秒，共处理专家数: {}", (endTime - startTime), updateExpert.size());
}

}
