package org.eco.als.service.impl;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.eco.als.domain.vo.FaultStatisticsWbVo;
import org.eco.common.core.core.domain.model.LoginUser;
import org.eco.common.excel.entity.ExcelResultRes;
import org.eco.common.excel.service.IExcelService;
import org.eco.common.core.utils.bean.BeanUtils;
import org.eco.common.core.utils.MapstructUtils;
import org.eco.system.service.IImportExportService;
import org.eco.common.core.utils.StringUtils;
import org.eco.system.domain.bo.ImportExportBo;
import org.eco.common.orm.core.page.PageQuery;
import org.eco.common.core.core.page.PageResult;
import org.eco.common.orm.core.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import org.eco.als.mapper.FaultStatisticsMapper;
import org.eco.als.domain.FaultStatistics;
import org.eco.als.domain.bo.FaultStatisticsBo;
import org.eco.als.domain.vo.FaultStatisticsVo;
import org.eco.als.domain.vo.FaultStatisticsImportVo;
import org.eco.als.listener.FaultStatisticsImportListener;
import org.eco.als.service.IFaultStatisticsService;
import static org.eco.als.domain.table.FaultStatisticsTableDef.FAULT_STATISTICS;

/**
 * 故障统计Service业务层处理
 *
 * @author wgk
 * @date 2024-12-13
 */
@Service
@Slf4j
public class FaultStatisticsServiceImpl extends BaseServiceImpl<FaultStatisticsMapper, FaultStatistics> implements IFaultStatisticsService {
    @Resource
    private FaultStatisticsMapper faultStatisticsMapper;

    @Resource
    private IExcelService excelService;

    @Resource
    private IImportExportService importExportService;

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

    private QueryWrapper buildQueryWrapper(FaultStatisticsBo faultStatisticsBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(FAULT_STATISTICS.STATISTICS_DATE.eq
        (faultStatisticsBo.getStatisticsDate()));
        queryWrapper.and(FAULT_STATISTICS.WAR_ZONE.eq
        (faultStatisticsBo.getWarZone()));

        queryWrapper.and(FAULT_STATISTICS.GROUPS.eq
            (faultStatisticsBo.getGroups()));
        queryWrapper.and(FAULT_STATISTICS.MAJOR.eq
        (faultStatisticsBo.getMajor()));
        queryWrapper.and(FAULT_STATISTICS.AIRCRAFT_MODEL.eq
            (faultStatisticsBo.getAircraftModel()));
        queryWrapper.and(FAULT_STATISTICS.AIRCRAFT_NUM.eq
            (faultStatisticsBo.getAircraftNum()));
        queryWrapper.and(FAULT_STATISTICS.FAULTY_PARTS_NAME.eq
            (faultStatisticsBo.getFaultyPartsName()));

        if(faultStatisticsBo.getStartStatisticsDate() != null && faultStatisticsBo.getEndStatisticsDate() != null){
            queryWrapper.between("statistics_date", faultStatisticsBo.getStartStatisticsDate(), faultStatisticsBo.getEndStatisticsDate());
        }
        if(faultStatisticsBo.getDistinctField() != null){
            if(faultStatisticsBo.getDistinctField().equals("groups")){
                queryWrapper.select("DISTINCT groups"); // 指定去重字段
            }else if(faultStatisticsBo.getDistinctField().equals("major")){
                queryWrapper.select("DISTINCT major");
            }else if(faultStatisticsBo.getDistinctField().equals("aircraft_model")){
                queryWrapper.select("DISTINCT aircraft_model");
            }else if(faultStatisticsBo.getDistinctField().equals("aircraft_num")){
                queryWrapper.select("DISTINCT aircraft_num");
            }else if(faultStatisticsBo.getDistinctField().equals("faulty_parts_name")){
                queryWrapper.select("DISTINCT faulty_parts_name");
            }
        }

        return queryWrapper;
    }

    /**
     * 查询故障统计
     *
     * @param id 故障统计主键
     * @return 故障统计
     */
    @Override
    public FaultStatisticsVo selectById(Long id) {
            return this.getOneAs(query().where(FAULT_STATISTICS.ID.eq(id)), FaultStatisticsVo.class);

    }


    /**
     * 查询故障统计列表
     *
     * @param faultStatisticsBo 故障统计Bo
     * @return 故障统计集合
     */
    @Override
    public List<FaultStatisticsVo> selectList(FaultStatisticsBo faultStatisticsBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(faultStatisticsBo);
            return this.listAs(queryWrapper, FaultStatisticsVo.class);
    }

    /**
     * 外部查询故障统计列表
     *
     * @param faultStatisticsBo 故障统计Bo
     * @return 故障统计集合
     */
    @Override
    public List<FaultStatisticsWbVo> outsideListAll(FaultStatisticsBo faultStatisticsBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(faultStatisticsBo);
        return this.listAs(queryWrapper, FaultStatisticsWbVo.class);
    }

    /**
     * 分页查询故障统计列表
     *
     * @param faultStatisticsBo 故障统计Bo
     * @return 分页故障统计集合
     */
    @Override
    public PageResult<FaultStatisticsVo> selectPage(FaultStatisticsBo faultStatisticsBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(faultStatisticsBo);
            Page<FaultStatisticsVo> page = this.pageAs(PageQuery.build(), queryWrapper, FaultStatisticsVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增故障统计
     *
     * @param faultStatisticsBo 故障统计Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(FaultStatisticsBo faultStatisticsBo) {
    FaultStatistics faultStatistics =MapstructUtils.convert(faultStatisticsBo, FaultStatistics. class);

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

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


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

    /**
     * 修改故障统计
     *
     * @param faultStatisticsBo 故障统计Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(FaultStatisticsBo faultStatisticsBo) {
        FaultStatistics faultStatistics =MapstructUtils.convert(faultStatisticsBo, FaultStatistics. class);
        if (ObjectUtil.isNotNull(faultStatistics) && ObjectUtil.isNotNull(faultStatistics.getId())){
            boolean updated = this.updateById(faultStatistics);
                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, FaultStatisticsImportVo.class, new FaultStatisticsImportListener(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<FaultStatisticsVo> listVo, String sheetName, LoginUser loginUser) {
        ExcelResultRes result = excelService.exportExcel(listVo, sheetName, FaultStatisticsVo.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));
    }

}
