package com.hotwj.platform.config.dispatchTemplate.service.impl;

import cn.hutool.core.collection.CollUtil;
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.config.dispatchTemplate.domain.HotDispatchTemplate;
import com.hotwj.platform.config.dispatchTemplate.domain.bo.HotDispatchTemplateBo;
import com.hotwj.platform.config.dispatchTemplate.domain.vo.HotDispatchTemplateVo;
import com.hotwj.platform.config.dispatchTemplate.mapper.HotDispatchTemplateMapper;
import com.hotwj.platform.config.dispatchTemplate.service.IHotDispatchTemplateService;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
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.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 下发模板Service业务层处理
 *
 * @author shihongwei
 * @date 2026-02-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotDispatchTemplateServiceImpl implements IHotDispatchTemplateService {

    private final HotDispatchTemplateMapper baseMapper;
    private final ISysCompanyService sysCompanyService;

    /**
     * 查询下发模板
     *
     * @param id 主键
     * @return 下发模板
     */
    @Override
    public HotDispatchTemplateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询下发模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 下发模板分页列表
     */
    @Override
    public TableDataInfo<HotDispatchTemplateVo> queryPageList(HotDispatchTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotDispatchTemplate> lqw = buildQueryWrapper(bo);
        Page<HotDispatchTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的下发模板列表
     *
     * @param bo 查询条件
     * @return 下发模板列表
     */
    @Override
    public List<HotDispatchTemplateVo> queryList(HotDispatchTemplateBo bo) {
        LambdaQueryWrapper<HotDispatchTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean useDefault() {
        Long companyId = LoginHelper.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }
        SysCompanyVo company = sysCompanyService.queryById(companyId);
        if (company == null) {
            throw new ServiceException("公司不存在");
        }
        Long count = baseMapper.selectCount(
                Wrappers.lambdaQuery(HotDispatchTemplate.class)
                        .eq(HotDispatchTemplate::getCompanyId, companyId)
        );
        if (count != null && count > 0) {
            throw new ServiceException("当前公司已存在下发模板配置，请先清除已存在数据");
        }
        List<HotDispatchTemplate> defaultConfigs = baseMapper.selectList(
                Wrappers.lambdaQuery(HotDispatchTemplate.class)
                        .eq(HotDispatchTemplate::getCompanyId, 1L)
        );
        if (CollUtil.isEmpty(defaultConfigs)) {
            throw new ServiceException("默认配置不存在，请联系管理员");
        }
        List<HotDispatchTemplate> newConfigs = new ArrayList<>();
        for (HotDispatchTemplate cfg : defaultConfigs) {
            HotDispatchTemplate newCfg = new HotDispatchTemplate();
            newCfg.setCompanyId(companyId);
            newCfg.setTemplateName(cfg.getTemplateName());
            newCfg.setTemplateType(cfg.getTemplateType());
            newCfg.setStyleOssId(cfg.getStyleOssId());
            newCfg.setContent(cfg.getContent());
            newCfg.setIsDeleted(0L);
            newConfigs.add(newCfg);
        }
        return baseMapper.insertBatch(newConfigs);
    }

    private LambdaQueryWrapper<HotDispatchTemplate> buildQueryWrapper(HotDispatchTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotDispatchTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotDispatchTemplate::getId);
        lqw.eq(bo.getCompanyId() != null, HotDispatchTemplate::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), HotDispatchTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(StringUtils.isNotBlank(bo.getTemplateType()), HotDispatchTemplate::getTemplateType, bo.getTemplateType());
        lqw.eq(bo.getStyleOssId() != null, HotDispatchTemplate::getStyleOssId, bo.getStyleOssId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), HotDispatchTemplate::getContent, bo.getContent());
        lqw.like(StringUtils.isNotBlank(bo.getCreateByName()), HotDispatchTemplate::getCreateByName, bo.getCreateByName());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateByName()), HotDispatchTemplate::getUpdateByName, bo.getUpdateByName());
        lqw.eq(bo.getIsDeleted() != null, HotDispatchTemplate::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增下发模板
     *
     * @param bo 下发模板
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotDispatchTemplateBo bo) {
        HotDispatchTemplate add = MapstructUtils.convert(bo, HotDispatchTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改下发模板
     *
     * @param bo 下发模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotDispatchTemplateBo bo) {
        HotDispatchTemplate update = MapstructUtils.convert(bo, HotDispatchTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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