package com.njcn.harmonic.common.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.harmonic.common.mapper.SysExcelMapper;
import com.njcn.harmonic.common.mapper.SysExcelRelationMapper;
import com.njcn.harmonic.common.service.ISysExcelService;
import com.njcn.harmonic.pojo.param.excel.ExcelParam;
import com.njcn.harmonic.pojo.po.excel.SysExcel;
import com.njcn.harmonic.pojo.po.excel.SysExcelRelation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xy
 * @since 2026-01-27
 */
@Service
@Slf4j
@RequiredArgsConstructor
@DS("sjzx")
public class SysExcelServiceImpl extends ServiceImpl<SysExcelMapper, SysExcel> implements ISysExcelService {

    private final SysExcelRelationMapper sysExcelRelationMapper;

    @Override
    public boolean addSysExcel(ExcelParam param) {
        LambdaQueryWrapper<SysExcel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysExcel::getExcelName, param.getModelTypeName());
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException("名称重复");
        }

        SysExcel sysExcel = new SysExcel();
        sysExcel.setExcelName(param.getModelTypeName());
        sysExcel.setExcelType(param.getModelType());
        sysExcel.setSort(param.getSort());
        return this.save(sysExcel);
    }

    @Override
    public boolean deleteSysExcel(String id) {
        LambdaQueryWrapper<SysExcelRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysExcelRelation::getSysExcelId, id);
        if (sysExcelRelationMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("请先删除关联关系");
        }
        return this.removeById(id);
    }

    @Override
    public boolean updateSysExcel(ExcelParam.UpdateExcelParam param) {
        LambdaQueryWrapper<SysExcel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysExcel::getExcelName, param.getModelTypeName()).ne(SysExcel::getId, param.getId());
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException("名称重复");
        }
        SysExcel sysExcel = new SysExcel();
        sysExcel.setId(param.getId());
        sysExcel.setExcelName(param.getModelTypeName());
        sysExcel.setExcelType(param.getModelType());
        sysExcel.setSort(param.getSort());
        return this.updateById(sysExcel);
    }

    @Override
    public List<SysExcel> querySysExcel() {
        return this.list().stream().sorted(Comparator.comparing(SysExcel::getSort)).collect(Collectors.toList());
    }


}
