package com.hotwj.platform.config.hiddenDangerInspectStore.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.hiddenDangerInspectStore.domain.HotHiddenDangerInspectStore;
import com.hotwj.platform.config.hiddenDangerInspectStore.domain.bo.HotHiddenDangerInspectStoreBo;
import com.hotwj.platform.config.hiddenDangerInspectStore.domain.vo.HotHiddenDangerInspectStoreVo;
import com.hotwj.platform.config.hiddenDangerInspectStore.mapper.HotHiddenDangerInspectStoreMapper;
import com.hotwj.platform.config.hiddenDangerInspectStore.service.IHotHiddenDangerInspectStoreService;
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 2025-12-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotHiddenDangerInspectStoreServiceImpl implements IHotHiddenDangerInspectStoreService {

    private final HotHiddenDangerInspectStoreMapper baseMapper;
    private final ISysCompanyService sysCompanyService;

    /**
     * 查询隐患排查检查库
     *
     * @param id 主键
     * @return 隐患排查检查库
     */
    @Override
    public HotHiddenDangerInspectStoreVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @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(HotHiddenDangerInspectStore.class)
                        .eq(HotHiddenDangerInspectStore::getCompanyId, companyId)
        );
        if (count != null && count > 0) {
            throw new ServiceException("当前公司已存在隐患排查配置，请先清除已存在数据");
        }

        // 获取总部配置 (companyId = 1)
        List<HotHiddenDangerInspectStore> defaultConfigs = baseMapper.selectList(
                Wrappers.lambdaQuery(HotHiddenDangerInspectStore.class)
                        .eq(HotHiddenDangerInspectStore::getCompanyId, 1L)
        );

        if (CollUtil.isEmpty(defaultConfigs)) {
            throw new ServiceException("默认配置不存在，请联系管理员");
        }

        List<HotHiddenDangerInspectStore> newConfigs = new ArrayList<>();
        for (HotHiddenDangerInspectStore cfg : defaultConfigs) {
            HotHiddenDangerInspectStore newCfg = new HotHiddenDangerInspectStore();
            // 复制属性，排除ID等
            newCfg.setCompanyId(companyId);
            newCfg.setInspectType(cfg.getInspectType());
            newCfg.setContent(cfg.getContent());
            newCfg.setNormalText(cfg.getNormalText());
            newCfg.setAbnormalText(cfg.getAbnormalText());
            newCfg.setCode(cfg.getCode());
            newCfg.setIsDeleted(0L);
            newConfigs.add(newCfg);
        }

        return baseMapper.insertBatch(newConfigs);
    }


    /**
     * 分页查询隐患排查检查库列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 隐患排查检查库分页列表
     */
    @Override
    public TableDataInfo<HotHiddenDangerInspectStoreVo> queryPageList(HotHiddenDangerInspectStoreBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotHiddenDangerInspectStore> lqw = buildQueryWrapper(bo);
        Page<HotHiddenDangerInspectStoreVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的隐患排查检查库列表
     *
     * @param bo 查询条件
     * @return 隐患排查检查库列表
     */
    @Override
    public List<HotHiddenDangerInspectStoreVo> queryList(HotHiddenDangerInspectStoreBo bo) {
        LambdaQueryWrapper<HotHiddenDangerInspectStore> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<HotHiddenDangerInspectStoreVo> queryByCompanyIdAndIds(Long companyId, List<Long> ids) {
        if (companyId == null || ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<HotHiddenDangerInspectStore> lqw = Wrappers.<HotHiddenDangerInspectStore>lambdaQuery()
                .eq(HotHiddenDangerInspectStore::getCompanyId, companyId)
                .in(HotHiddenDangerInspectStore::getId, ids);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotHiddenDangerInspectStore> buildQueryWrapper(HotHiddenDangerInspectStoreBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotHiddenDangerInspectStore> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotHiddenDangerInspectStore::getId);
        lqw.eq(bo.getCompanyId() != null, HotHiddenDangerInspectStore::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getInspectType() != null, HotHiddenDangerInspectStore::getInspectType, bo.getInspectType());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), HotHiddenDangerInspectStore::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getNormalText()), HotHiddenDangerInspectStore::getNormalText, bo.getNormalText());
        lqw.eq(StringUtils.isNotBlank(bo.getAbnormalText()), HotHiddenDangerInspectStore::getAbnormalText, bo.getAbnormalText());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), HotHiddenDangerInspectStore::getCode, bo.getCode());
        lqw.eq(bo.getIsDeleted() != null, HotHiddenDangerInspectStore::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增隐患排查检查库
     *
     * @param bo 隐患排查检查库
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotHiddenDangerInspectStoreBo bo) {
        HotHiddenDangerInspectStore add = MapstructUtils.convert(bo, HotHiddenDangerInspectStore.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改隐患排查检查库
     *
     * @param bo 隐患排查检查库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotHiddenDangerInspectStoreBo bo) {
        HotHiddenDangerInspectStore update = MapstructUtils.convert(bo, HotHiddenDangerInspectStore.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotHiddenDangerInspectStore entity) {
        if (entity.getCompanyId() == null || StringUtils.isBlank(entity.getCode())) {
            return;
        }
        LambdaQueryWrapper<HotHiddenDangerInspectStore> lqw = Wrappers.lambdaQuery();
        lqw.eq(HotHiddenDangerInspectStore::getCompanyId, entity.getCompanyId());
        lqw.eq(HotHiddenDangerInspectStore::getCode, entity.getCode());
        lqw.eq(HotHiddenDangerInspectStore::getInspectType, entity.getInspectType());
        lqw.eq(HotHiddenDangerInspectStore::getIsDeleted, 0L);
        if (entity.getId() != null) {
            lqw.ne(HotHiddenDangerInspectStore::getId, entity.getId());
        }
        Long count = baseMapper.selectCount(lqw);
        if (count != null && count > 0) {
            throw new ServiceException("同一公司下隐患排查检查库代码已存在，请修改后重试");
        }
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean clearAll() {
        Long companyId = LoginHelper.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }
        // 逻辑删除当前公司所有配置
        return baseMapper.delete(
                Wrappers.lambdaQuery(HotHiddenDangerInspectStore.class)
                        .eq(HotHiddenDangerInspectStore::getCompanyId, companyId)
        ) > 0;
    }
}
