package org.dromara.main.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.main.domain.MainAbilityConfig;
import org.dromara.main.domain.MainExamEvaluation;
import org.dromara.main.domain.bo.MainExamEvaluationBo;
import org.dromara.main.domain.vo.MainExamEvaluationVo;
import org.dromara.main.mapper.MainAbilityConfigMapper;
import org.dromara.main.mapper.MainExamEvaluationMapper;
import org.dromara.main.service.IMainExamEvaluationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collection;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class MainExamEvaluationServiceImpl implements IMainExamEvaluationService {

    private final MainExamEvaluationMapper baseMapper;
    private final MainAbilityConfigMapper mainAbilityConfigMapper;

    @Override
    public MainExamEvaluationVo queryById(Long id) {
        MainExamEvaluationVo vo = baseMapper.selectVoByIdWithImages(id);
        if (vo != null) {
            encodeDetailFieldInVo(vo);
        }
        return vo;
    }

    @Override
    public TableDataInfo<MainExamEvaluationVo> queryPageList(MainExamEvaluationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MainExamEvaluation> lqw = buildQueryWrapper(bo);
        Page<MainExamEvaluationVo> result = baseMapper.selectVoPageWithImages(pageQuery.build(), lqw);
        result.getRecords().forEach(this::encodeDetailFieldInVo);
        return TableDataInfo.build(result);
    }

    @Override
    public List<MainExamEvaluationVo> queryList(MainExamEvaluationBo bo) {
        LambdaQueryWrapper<MainExamEvaluation> lqw = buildQueryWrapper(bo);
        List<MainExamEvaluationVo> list = baseMapper.selectVoList(lqw);
        list.forEach(this::encodeDetailFieldInVo);
        return list;
    }

    private LambdaQueryWrapper<MainExamEvaluation> buildQueryWrapper(MainExamEvaluationBo bo) {
        LambdaQueryWrapper<MainExamEvaluation> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getEvaluationName()), MainExamEvaluation::getEvaluationName, bo.getEvaluationName());
        lqw.eq(StringUtils.isNotBlank(bo.getGrade()), MainExamEvaluation::getGrade, bo.getGrade());
        lqw.eq(StringUtils.isNotBlank(bo.getPosition()), MainExamEvaluation::getPosition, bo.getPosition());
        lqw.eq(StringUtils.isNotBlank(bo.getPositionType()), MainExamEvaluation::getPositionType, bo.getPositionType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), MainExamEvaluation::getStatus, bo.getStatus());
        lqw.orderByDesc(MainExamEvaluation::getCreateTime);
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MainExamEvaluationBo bo) {
        decodeDetailFieldInBo(bo);
        MainExamEvaluation add = BeanUtil.toBean(bo, MainExamEvaluation.class);
        validEntityBeforeSave(add);

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            saveMainAbilityConfigs(add.getId(), bo.getAbilityConfigs());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MainExamEvaluationBo bo) {
        decodeDetailFieldInBo(bo);
        MainExamEvaluation update = BeanUtil.toBean(bo, MainExamEvaluation.class);
        validEntityBeforeSave(update);

        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            mainAbilityConfigMapper.deleteByEvaluationId(bo.getId());
            saveMainAbilityConfigs(bo.getId(), bo.getAbilityConfigs());
        }
        return flag;
    }

    private void saveMainAbilityConfigs(Long evaluationId, List<MainAbilityConfig> configs) {
        if (!CollectionUtils.isEmpty(configs)) {
            for (int i = 0; i < configs.size(); i++) {
                MainAbilityConfig config = configs.get(i);
                config.setEvaluationId(evaluationId);
                config.setSortOrder(i);
            }
            mainAbilityConfigMapper.insertBatch(configs);
        }
    }

    private void validEntityBeforeSave(MainExamEvaluation entity) {
        // TODO 做一些数据校验，如唯一约束
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验
        }
        ids.forEach(mainAbilityConfigMapper::deleteByEvaluationId);
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(List<Long> ids, String status) {
        if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(status)) {
            return false;
        }
        for (Long id : ids) {
            MainExamEvaluation entity = new MainExamEvaluation();
            entity.setId(id);
            entity.setStatus(status);
            baseMapper.updateById(entity);
        }
        return true;
    }

    @Override
    public Boolean syncThirdPartyData() {
        log.info("开始同步第三方测评数据");
        return true;
    }

    private void decodeDetailFieldInBo(MainExamEvaluationBo bo) {
        if (StringUtils.isNotBlank(bo.getDetail())) {
            try {
                String decoded = new String(Base64.getDecoder().decode(bo.getDetail()), StandardCharsets.UTF_8);
                bo.setDetail(decoded);
            } catch (Exception e) {
                log.warn("详情字段Base64解码失败，使用原始值", e);
            }
        }
    }

    private void encodeDetailFieldInVo(MainExamEvaluationVo vo) {
        if (StringUtils.isNotBlank(vo.getDetail())) {
            try {
                String encoded = Base64.getEncoder().encodeToString(vo.getDetail().getBytes(StandardCharsets.UTF_8));
                vo.setDetail(encoded);
            } catch (Exception e) {
                log.warn("详情字段Base64编码失败，使用原始值", e);
            }
        }
    }
}
