package com.qingyun.service.service.impl;

import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.helper.LoginHelper;
import org.apache.commons.lang3.StringUtils;

import com.qingyun.common.utils.MapstructUtils;
import com.qingyun.mybatisplus.page.TableDataInfo;
import com.qingyun.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.qingyun.service.domain.bo.ContractModelConfigBo;
import com.qingyun.service.domain.vo.ContractModelConfigVo;
import com.qingyun.service.domain.ContractModelConfig;
import com.qingyun.service.mapper.ContractModelConfigMapper;
import com.qingyun.service.service.IContractModelConfigService;

import com.qingyun.mybatisplus.core.ServicePlusImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 模型配置Service业务层处理
 *
 * @author jianlu
 * @date 2025-07-11
 */
@RequiredArgsConstructor
@Service
public class ContractModelConfigServiceImpl extends ServicePlusImpl<ContractModelConfigMapper, ContractModelConfig, ContractModelConfigVo> implements IContractModelConfigService {


    /**
     * 查询模型配置
     */
    @Override
    public ContractModelConfigVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询模型配置列表
     */
    @Override
    public TableDataInfo<ContractModelConfigVo> queryPageList(ContractModelConfigBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ContractModelConfig> lqw = buildQueryWrapper(bo);
        Page<ContractModelConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            // 密钥脱敏 只显示前3位,后面用 * 号替换
            if (item != null && item.getModelKey() != null) {
                String originalKey = item.getModelKey();
                StringBuilder sb = new StringBuilder();
                if (originalKey.length() > 3) {
                    sb.append(originalKey, 0, 3);
                    for (int i = 3; i < originalKey.length(); i++) {
                        sb.append("*");
                    }
                } else {
                    for (int i = 0; i < originalKey.length(); i++) {
                        sb.append("*");
                    }
                }
                item.setModelKey(sb.toString());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询模型配置列表
     */
    @Override
    public List<ContractModelConfigVo> queryList(ContractModelConfigBo bo) {
        LambdaQueryWrapper<ContractModelConfig> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ContractModelConfig> buildQueryWrapper(ContractModelConfigBo bo) {
        LambdaQueryWrapper<ContractModelConfig> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getModelName()), ContractModelConfig::getModelName, bo.getModelName());
        lqw.eq(StringUtils.isNotBlank(bo.getModelUrl()), ContractModelConfig::getModelUrl, bo.getModelUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getModelKey()), ContractModelConfig::getModelKey, bo.getModelKey());
        lqw.eq(StringUtils.isNotBlank(bo.getModelType()), ContractModelConfig::getModelType, bo.getModelType());
        return lqw;
    }

    /**
     * 新增模型配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ContractModelConfigBo bo) {
        ContractModelConfig add = MapstructUtils.convert(bo, ContractModelConfig.class);
        validEntityBeforeSave(add);
        add.setCreateBy(LoginHelper.getUsername());
        add.setCreateTime(new Date());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改模型配置
     */
    @Override
    public Boolean updateByBo(ContractModelConfigBo bo) {
        ContractModelConfig update = MapstructUtils.convert(bo, ContractModelConfig.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ContractModelConfig entity){
        //TODO 做一些数据校验,如唯一约束
        // 校验模型名称是否唯一
        Long count;
        if (entity.getId() == null) {
            count = this.baseMapper.selectCount(Wrappers.<ContractModelConfig>lambdaQuery()
                .eq(ContractModelConfig::getModelName, entity.getModelName())
            );
        } else {
            count = this.baseMapper.selectCount(Wrappers.<ContractModelConfig>lambdaQuery()
                .eq(ContractModelConfig::getModelName, entity.getModelName())
                .ne(ContractModelConfig::getId, entity.getId())
            );
        }
        if (count > 0) {
            throw new ServiceException("模型名称已存在");
        }
    }

    /**
     * 批量删除模型配置
     */
    @Override
    public Boolean deleteWithValidByIds(Long[] ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(Arrays.asList(ids)) > 0;
    }
}
