package org.eco.als.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eco.als.domain.QaHistory;
import org.eco.als.domain.bo.QaHistoryBo;
import org.eco.als.domain.vo.QaHistoryImportVo;
import org.eco.als.domain.vo.QaHistoryVo;
import org.eco.als.listener.QaHistoryImportListener;
import org.eco.als.mapper.QaHistoryMapper;
import org.eco.als.service.IQaHistoryService;
import org.eco.common.core.core.domain.model.LoginUser;
import org.eco.common.core.core.page.PageResult;
import org.eco.common.core.utils.MapstructUtils;
import org.eco.common.excel.entity.ExcelResultRes;
import org.eco.common.excel.service.IExcelService;
import org.eco.common.orm.core.page.PageQuery;
import org.eco.common.orm.core.service.impl.BaseServiceImpl;
import org.eco.system.service.IImportExportService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.avg;
import static org.eco.als.domain.table.QaHistoryTableDef.QA_HISTORY;

/**
 * 问答历史记录Service业务层处理
 *
 * @author wgk
 * @date 2024-12-13
 */
@Service
@Slf4j
public class QaHistoryServiceImpl extends BaseServiceImpl<QaHistoryMapper, QaHistory> implements IQaHistoryService {
    @Resource
    private QaHistoryMapper qaHistoryMapper;

    @Resource
    private IExcelService excelService;

    @Resource
    private IImportExportService importExportService;

    @Override
    public QueryWrapper query() {
        return super.query().from(QA_HISTORY);
    }

    private QueryWrapper buildQueryWrapper(QaHistoryBo qaHistoryBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(QA_HISTORY.USER_ID.eq
            (qaHistoryBo.getUserId()));
        queryWrapper.and(QA_HISTORY.QUESTION.eq
            (qaHistoryBo.getQuestion()));
        queryWrapper.and(QA_HISTORY.ANSWER.eq
            (qaHistoryBo.getAnswer()));
        queryWrapper.and(QA_HISTORY.GRAPH.eq
            (qaHistoryBo.getAnswer()));
        queryWrapper.and(QA_HISTORY.OSS_ID.eq
            (qaHistoryBo.getOssId()));
        queryWrapper.and(QA_HISTORY.FILE_NAME.like
            (qaHistoryBo.getFileName()));
        queryWrapper.and(QA_HISTORY.REMARKS.eq
            (qaHistoryBo.getRemarks()));
        queryWrapper.orderBy(QA_HISTORY.CREATE_TIME.desc());

        return queryWrapper;
    }

    /**
     * 查询问答历史记录
     *
     * @param id 问答历史记录主键
     * @return 问答历史记录
     */
    @Override
    public QaHistoryVo selectById(Long id) {
        return this.getOneAs(query().where(QA_HISTORY.ID.eq(id)), QaHistoryVo.class);

    }


    /**
     * 查询问答历史记录列表
     *
     * @param qaHistoryBo 问答历史记录Bo
     * @return 问答历史记录集合
     */
    @Override
    public List<QaHistoryVo> selectList(QaHistoryBo qaHistoryBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(qaHistoryBo);
        return this.listAs(queryWrapper, QaHistoryVo.class);
    }

    @Override
    public List<QaHistoryVo> groupQuestion() {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.select(QA_HISTORY.QUESTION, QueryMethods.count(QA_HISTORY.QUESTION).as("couns")).groupBy(QA_HISTORY.QUESTION).orderBy("couns", false);
        return this.listAs(queryWrapper, QaHistoryVo.class);
    }

    /**
     * 分页查询问答历史记录列表
     *
     * @param qaHistoryBo 问答历史记录Bo
     * @return 分页问答历史记录集合
     */
    @Override
    public PageResult<QaHistoryVo> selectPage(QaHistoryBo qaHistoryBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(qaHistoryBo);
        Page<QaHistoryVo> page = this.pageAs(PageQuery.build(), queryWrapper, QaHistoryVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增问答历史记录
     *
     * @param qaHistoryBo 问答历史记录Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(QaHistoryBo qaHistoryBo) {
        QaHistory qaHistory = MapstructUtils.convert(qaHistoryBo, QaHistory.class);

        return this.save(qaHistory);//使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 新增问答历史记录，前台提供主键值，一般用于导入的场合
     *
     * @param qaHistoryBo 问答历史记录Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(QaHistoryBo qaHistoryBo) {
        QaHistory qaHistory = MapstructUtils.convert(qaHistoryBo, QaHistory.class);


        return qaHistoryMapper.insertWithPk(qaHistory) > 0;//前台传来主键值
    }

    /**
     * 修改问答历史记录
     *
     * @param qaHistoryBo 问答历史记录Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(QaHistoryBo qaHistoryBo) {
        QaHistory qaHistory = MapstructUtils.convert(qaHistoryBo, QaHistory.class);
        if (ObjectUtil.isNotNull(qaHistory) && ObjectUtil.isNotNull(qaHistory.getId())) {
            boolean updated = this.updateById(qaHistory);
            return updated;
        }
        return false;
    }

    @Override
    public void asyncImportData(MultipartFile file, boolean updateSupport, LoginUser loginUser) {
        ExcelResultRes result;
        try {
            String name = file.getOriginalFilename();
            result = excelService.importExcel(file.getInputStream(), name, QaHistoryImportVo.class, new QaHistoryImportListener(updateSupport, loginUser));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        boolean flag = importExportService.saveInfo(result, loginUser, "0");
        if (flag) {
            log.info("异步导入日志写入成功");
        }
    }

    @Override
    public void asyncExport(List<QaHistoryVo> listVo, String sheetName, LoginUser loginUser) {
        ExcelResultRes result = excelService.exportExcel(listVo, sheetName, QaHistoryVo.class);
        boolean flag = importExportService.saveInfo(result, loginUser, "1");
        if (flag) {
            log.info("异步导出日志写入成功");
        }
    }

    /**
     * 批量删除问答历史记录
     *
     * @param ids 需要删除的问答历史记录主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

}
