package com.hotwj.platform.regulationManagement.policyRevision.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 com.hotwj.platform.regulationManagement.policyRevision.domain.HotPolicyRevision;
import com.hotwj.platform.regulationManagement.policyRevision.domain.bo.HotPolicyRevisionBo;
import com.hotwj.platform.regulationManagement.policyRevision.domain.vo.HotPolicyRevisionVo;
import com.hotwj.platform.regulationManagement.policyRevision.mapper.HotPolicyRevisionMapper;
import com.hotwj.platform.regulationManagement.policyRevision.service.IHotPolicyRevisionService;
import com.hotwj.platform.resourceManagement.companyPolicy.domain.HotCompanyPolicy;
import com.hotwj.platform.resourceManagement.companyPolicy.mapper.HotCompanyPolicyMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 制度修正记录Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-11
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotPolicyRevisionServiceImpl implements IHotPolicyRevisionService {

    private final HotPolicyRevisionMapper baseMapper;
    private final HotCompanyPolicyMapper hotCompanyPolicyMapper;
    private final ISysUserService userService;

    /**
     * 查询制度修正记录
     *
     * @param id 主键
     * @return 制度修正记录
     */
    @Override
    public HotPolicyRevisionVo queryById(Long id) {
        HotPolicyRevisionVo vo = baseMapper.selectVoById(id);
        if (vo == null) {
            return null;
        }
        if (vo.getPolicyId() != null) {
            HotCompanyPolicy policy = hotCompanyPolicyMapper.selectById(vo.getPolicyId());
            if (policy != null) {
                vo.setPolicyTitle(policy.getPolicyTitle());
                vo.setPolicyType(policy.getPolicyType());
            }
        }

        return vo;
    }

    /**
     * 分页查询制度修正记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 制度修正记录分页列表
     */
    @Override
    public TableDataInfo<HotPolicyRevisionVo> queryPageList(HotPolicyRevisionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotPolicyRevision> lqw = buildQueryWrapper(bo);
        Page<HotPolicyRevisionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<HotPolicyRevisionVo> records = result.getRecords();
        if (records != null && !records.isEmpty()) {
            List<Long> policyIds = records.stream().map(HotPolicyRevisionVo::getPolicyId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            Map<Long, HotCompanyPolicy> policyMap = hotCompanyPolicyMapper.selectList(
                    Wrappers.<HotCompanyPolicy>lambdaQuery()
                            .in(HotCompanyPolicy::getId, policyIds)
                            .select(HotCompanyPolicy::getId, HotCompanyPolicy::getPolicyTitle, HotCompanyPolicy::getPolicyType)
            ).stream().collect(Collectors.toMap(HotCompanyPolicy::getId, Function.identity()));
            for (HotPolicyRevisionVo vo : records) {
                HotCompanyPolicy p = vo.getPolicyId() != null ? policyMap.get(vo.getPolicyId()) : null;
                if (p != null) {
                    vo.setPolicyTitle(p.getPolicyTitle());
                    vo.setPolicyType(p.getPolicyType());
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的制度修正记录列表
     *
     * @param bo 查询条件
     * @return 制度修正记录列表
     */
    @Override
    public List<HotPolicyRevisionVo> queryList(HotPolicyRevisionBo bo) {
        LambdaQueryWrapper<HotPolicyRevision> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotPolicyRevision> buildQueryWrapper(HotPolicyRevisionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotPolicyRevision> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotPolicyRevision::getCreatedTime);
        lqw.eq(bo.getCompanyId() != null, HotPolicyRevision::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getPolicyId() != null, HotPolicyRevision::getPolicyId, bo.getPolicyId());
        lqw.eq(bo.getVersionNo() != null, HotPolicyRevision::getVersionNo, bo.getVersionNo());
        lqw.eq(StringUtils.isNotBlank(bo.getChangeNote()), HotPolicyRevision::getChangeNote, bo.getChangeNote());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), HotPolicyRevision::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachmentUrl()), HotPolicyRevision::getAttachmentUrl, bo.getAttachmentUrl());
        lqw.eq(bo.getTemplateId() != null, HotPolicyRevision::getTemplateId, bo.getTemplateId());
        lqw.eq(bo.getCreatedBy() != null, HotPolicyRevision::getCreatedBy, bo.getCreatedBy());
        lqw.apply(StringUtils.isNotBlank(bo.getPolicyName()), "policy_id in (select id from hot_company_policy where policy_title like {0})", "%" + bo.getPolicyName() + "%");
        lqw.apply(StringUtils.isNotBlank(bo.getPolicyType()), "policy_id in (select id from hot_company_policy where policy_type = {0})", bo.getPolicyType());
        if (params != null && params.get("beginTime") != null && params.get("endTime") != null) {
            lqw.between(HotPolicyRevision::getCreatedTime, params.get("beginTime"), params.get("endTime"));
        } else {
            lqw.eq(bo.getCreatedTime() != null, HotPolicyRevision::getCreatedTime, bo.getCreatedTime());
        }
        lqw.eq(bo.getIsDeleted() != null, HotPolicyRevision::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增制度修正记录
     *
     * @param bo 制度修正记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotPolicyRevisionBo bo) {
        HotPolicyRevision add = MapstructUtils.convert(bo, HotPolicyRevision.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改制度修正记录
     *
     * @param bo 制度修正记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotPolicyRevisionBo bo) {
        HotPolicyRevision update = MapstructUtils.convert(bo, HotPolicyRevision.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotPolicyRevision 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 Long nextVersionNo(Long policyId) {
        LambdaQueryWrapper<HotPolicyRevision> lqw = Wrappers.lambdaQuery();
        lqw.eq(HotPolicyRevision::getPolicyId, policyId);
        lqw.orderByDesc(HotPolicyRevision::getVersionNo);
        lqw.last("limit 1");
        HotPolicyRevision last = baseMapper.selectOne(lqw);
        Long lastNo = last != null ? last.getVersionNo() : 0L;
        return lastNo + 1;
    }

    @Override
    public Boolean createRevision(HotPolicyRevisionBo bo) {
        return insertByBo(bo);
    }
}
