package org.eco.als.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.eco.als.domain.FaultCase;
import org.eco.als.domain.bo.FaultCaseBo;
import org.eco.als.domain.vo.FaultCaseImportVo;
import org.eco.als.domain.vo.FaultCaseVo;
import org.eco.als.es.mapper.EsFaultCaseMapper;
import org.eco.als.listener.FaultCaseImportListener;
import org.eco.als.mapper.FaultCaseMapper;
import org.eco.als.service.IFaultCaseService;
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 org.eco.als.domain.table.FaultCaseTableDef.FAULT_CASE;

/**
 * 故障案例Service业务层处理
 *
 * @author wgk
 * @date 2024-12-13
 */
@Service
@Slf4j
public class FaultCaseServiceImpl extends BaseServiceImpl<FaultCaseMapper, FaultCase> implements IFaultCaseService {
    @Resource
    private FaultCaseMapper faultCaseMapper;
    @Resource
    private EsFaultCaseMapper esFaultCaseMapper;

    @Resource
    private IExcelService excelService;

    @Resource
    private IImportExportService importExportService;

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

    private QueryWrapper buildQueryWrapper(FaultCaseBo faultCaseBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(FAULT_CASE.AIRCRAFT_TYPE_ID.eq
            (faultCaseBo.getAircraftTypeId()));
        queryWrapper.and(FAULT_CASE.AIRCRAFT_TYPE_NAME.like
            (faultCaseBo.getAircraftTypeName()));
        queryWrapper.and(FAULT_CASE.AIRCRAFT_SYSTEM_ID.eq
            (faultCaseBo.getAircraftSystemId()));
        queryWrapper.and(FAULT_CASE.AIRCRAFT_SYSTEM_NAME.like
            (faultCaseBo.getAircraftSystemName()));
        queryWrapper.and(FAULT_CASE.AIRCRAFT_SUBSYSTEM_ID.eq
            (faultCaseBo.getAircraftSubsystemId()));
        queryWrapper.and(FAULT_CASE.AIRCRAFT_SUBSYSTEM_NAME.like
            (faultCaseBo.getAircraftSubsystemName()));
        queryWrapper.and(FAULT_CASE.AUTHOR.eq
            (faultCaseBo.getAuthor()));
        queryWrapper.and(FAULT_CASE.FAULT_PHENOMENON.eq
            (faultCaseBo.getFaultPhenomenon()));
        queryWrapper.and(FAULT_CASE.FAULT_CAUSE.eq
            (faultCaseBo.getFaultCause()));
        queryWrapper.and(FAULT_CASE.FAULT_TREE_PATH.eq
            (faultCaseBo.getFaultTreePath()));
        queryWrapper.and(FAULT_CASE.FAULT_PICTURE_PATH.eq
            (faultCaseBo.getFaultPicturePath()));
        queryWrapper.and(FAULT_CASE.TROUBLESHOOTING_METHOD_PATH.eq
            (faultCaseBo.getTroubleshootingMethodPath()));
        queryWrapper.and(FAULT_CASE.VIEW_COUNT.eq
            (faultCaseBo.getViewCount()));
        queryWrapper.and(FAULT_CASE.ORDER_BY.eq
            (faultCaseBo.getOrderBy()));

        return queryWrapper;
    }

    /**
     * 查询故障案例
     *
     * @param id 故障案例主键
     * @return 故障案例
     */
    @Override
    public FaultCaseVo selectById(Long id) {
        return this.getOneAs(query().where(FAULT_CASE.ID.eq(id)), FaultCaseVo.class);

    }


    /**
     * 查询故障案例列表
     *
     * @param faultCaseBo 故障案例Bo
     * @return 故障案例集合
     */
    @Override
    public List<FaultCaseVo> selectList(FaultCaseBo faultCaseBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(faultCaseBo);
        return faultCaseMapper.selectListWithRelationsByQueryAs(queryWrapper, FaultCaseVo.class);
    }

    /**
     * 分页查询故障案例列表
     *
     * @param faultCaseBo 故障案例Bo
     * @return 分页故障案例集合
     */
    @Override
    public PageResult<FaultCaseVo> selectPage(FaultCaseBo faultCaseBo) {

        QueryWrapper queryWrapper = buildQueryWrapper(faultCaseBo);
        Page<FaultCaseVo> page = this.pageAs(PageQuery.build(), queryWrapper, FaultCaseVo.class);
        return PageResult.build(page);
    }

    @Override
    public EsPageInfo<FaultCase> selectEsPage(FaultCaseBo faultCaseBo) {
        FaultCase faultCase = MapstructUtils.convert(faultCaseBo, FaultCase.class);
        LambdaEsQueryWrapper<FaultCase> wrapper = new LambdaEsQueryWrapper<>();
        assert faultCase != null;
        wrapper.match(StrUtil.isNotBlank(faultCase.getFaultPhenomenon()), "pContent", faultCaseBo.getFaultPhenomenon(), 5.0f)
            .or()
            .match(StrUtil.isNotBlank(faultCase.getFaultPhenomenon()), "fContent", faultCaseBo.getFaultPhenomenon(), 5.0f);
        if (StrUtil.equals(faultCase.getOrderBy(), "createTimeAsc")) {
            wrapper.orderByAsc("createTime");
        } else if (StrUtil.equals(faultCase.getOrderBy(), "createTimeDesc")) {
            wrapper.orderByDesc("createTime");
        } else if (StrUtil.equals(faultCase.getOrderBy(), "countAsc")) {
            wrapper.orderByAsc("viewCount");
        } else if (StrUtil.equals(faultCase.getOrderBy(), "countDesc")) {
            wrapper.orderByDesc("viewCount");
        }
        if (!esFaultCaseMapper.existsIndex("fault_case_index")) {
            esFaultCaseMapper.createIndex();
        }
        Page page = PageQuery.build();
        return esFaultCaseMapper.pageQuery(wrapper, (int) page.getPageNumber(), (int) page.getPageSize());
    }

    /**
     * 新增故障案例
     *
     * @param faultCaseBo 故障案例Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(FaultCaseBo faultCaseBo) {
        FaultCase faultCase = MapstructUtils.convert(faultCaseBo, FaultCase.class);
        this.save(faultCase);//使用全局配置的雪花算法主键生成器生成ID值
        return esFaultCaseMapper.insert(faultCase) > 0;
    }

    /**
     * 新增故障案例，前台提供主键值，一般用于导入的场合
     *
     * @param faultCaseBo 故障案例Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(FaultCaseBo faultCaseBo) {
        FaultCase faultCase = MapstructUtils.convert(faultCaseBo, FaultCase.class);


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

    /**
     * 修改故障案例
     *
     * @param faultCaseBo 故障案例Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(FaultCaseBo faultCaseBo) {
        FaultCase faultCase = MapstructUtils.convert(faultCaseBo, FaultCase.class);
        if (ObjectUtil.isNotNull(faultCase) && ObjectUtil.isNotNull(faultCase.getId())) {
            esFaultCaseMapper.updateById(faultCase);
            return this.updateById(faultCase);
        }
        return false;
    }

    /**
     * 批量删除故障案例
     *
     * @param ids 需要删除的故障案例主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        esFaultCaseMapper.deleteBatchIds(Arrays.asList(ids));
        return this.removeByIds(Arrays.asList(ids));
    }

}
