package org.eco.als.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eco.als.domain.MaintenanceRecord;
import org.eco.als.domain.bo.MaintenanceRecordBo;
import org.eco.als.domain.vo.MaintenanceRecordImportVo;
import org.eco.als.domain.vo.MaintenanceRecordVo;
import org.eco.als.listener.MaintenanceRecordImportListener;
import org.eco.als.mapper.MaintenanceRecordMapper;
import org.eco.als.service.IMaintenanceRecordService;
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.core.utils.StringUtils;
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.AirConfigurationTableDef.AIR_CONFIGURATION;
import static org.eco.als.domain.table.MaintenanceRecordTableDef.MAINTENANCE_RECORD;

/**
 * 维修记录Service业务层处理
 *
 * @author wgk
 * @date 2024-07-19
 */
@Service
@Slf4j
public class MaintenanceRecordServiceImpl extends BaseServiceImpl<MaintenanceRecordMapper, MaintenanceRecord> implements IMaintenanceRecordService {
    @Resource
    private MaintenanceRecordMapper maintenanceRecordMapper;

    @Resource
    private IExcelService excelService;

    @Resource
    private IImportExportService importExportService;

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

    private QueryWrapper buildQueryWrapper(MaintenanceRecordBo maintenanceRecordBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        if (StringUtils.isNotBlank(maintenanceRecordBo.getAircraftType())) {
            queryWrapper.and(MAINTENANCE_RECORD.AIRCRAFT_TYPE.in
                (maintenanceRecordBo.getAircraftType().split(",")));
        }
        if (StringUtils.isNotBlank(maintenanceRecordBo.getAircraftId())) {
            queryWrapper.and(MAINTENANCE_RECORD.AIRCRAFT_ID.in
                (maintenanceRecordBo.getAircraftId().split(",")));
        }
        queryWrapper.and(MAINTENANCE_RECORD.SERIAL_NUMBER.eq
            (maintenanceRecordBo.getSerialNumber()));
        queryWrapper.and(MAINTENANCE_RECORD.SPECIALTY.eq
            (maintenanceRecordBo.getSpecialty()));
        queryWrapper.and(MAINTENANCE_RECORD.SYSTEM_NAME.like
            (maintenanceRecordBo.getSystemName()));
        queryWrapper.and(MAINTENANCE_RECORD.ENGINE_TYPE.eq
            (maintenanceRecordBo.getEngineType()));
        queryWrapper.and(MAINTENANCE_RECORD.ENGINE_SERIAL_NUMBER.eq
            (maintenanceRecordBo.getEngineSerialNumber()));
        queryWrapper.and(MAINTENANCE_RECORD.UNIT_NAME.like
            (maintenanceRecordBo.getUnitName()));
        queryWrapper.and(MAINTENANCE_RECORD.FAULT_PHENOMENON.eq
            (maintenanceRecordBo.getFaultPhenomenon()));
        queryWrapper.and(MAINTENANCE_RECORD.LOCATION_FAULT.eq
            (maintenanceRecordBo.getLocationFault()));
        queryWrapper.and(MAINTENANCE_RECORD.DISCOVERY_TIME.eq
            (maintenanceRecordBo.getDiscoveryTime()));
        queryWrapper.and(MAINTENANCE_RECORD.ITEM_NAME.like
            (maintenanceRecordBo.getItemName()));
        queryWrapper.and(MAINTENANCE_RECORD.ITEM_TYPE.eq
            (maintenanceRecordBo.getItemType()));
        queryWrapper.and(MAINTENANCE_RECORD.PART_NUMBER.eq
            (maintenanceRecordBo.getPartNumber()));
        queryWrapper.and(MAINTENANCE_RECORD.PART_TYPE.eq
            (maintenanceRecordBo.getPartType()));
        queryWrapper.and(MAINTENANCE_RECORD.FAULT_CODE.eq
            (maintenanceRecordBo.getFaultCode()));
        queryWrapper.and(MAINTENANCE_RECORD.INSTALLATION_DATE.eq
            (maintenanceRecordBo.getInstallationDate()));
        queryWrapper.and(MAINTENANCE_RECORD.CAUSE_FAULT.eq
            (maintenanceRecordBo.getCauseFault()));
        queryWrapper.and(MAINTENANCE_RECORD.NATURE_FAULT.eq
            (maintenanceRecordBo.getNatureFault()));
        queryWrapper.and(MAINTENANCE_RECORD.LIABILITY_FAULT.eq
            (maintenanceRecordBo.getLiabilityFault()));
        queryWrapper.and(MAINTENANCE_RECORD.CONSEQUENCES_FAULT.eq
            (maintenanceRecordBo.getConsequencesFault()));
        queryWrapper.and(MAINTENANCE_RECORD.OCCUR_DATE.eq
            (maintenanceRecordBo.getOccurDate()));
        queryWrapper.and(MAINTENANCE_RECORD.METHOD_DETERMINATION.eq
            (maintenanceRecordBo.getMethodDetermination()));
        queryWrapper.and(MAINTENANCE_RECORD.METHOD_RECTIFICATION.eq
            (maintenanceRecordBo.getMethodRectification()));
        queryWrapper.and(MAINTENANCE_RECORD.DISCOVERED_BY.eq
            (maintenanceRecordBo.getDiscoveredBy()));
        queryWrapper.and(MAINTENANCE_RECORD.RECTIFICATION_BY.eq
            (maintenanceRecordBo.getRectificationBy()));
        queryWrapper.and(MAINTENANCE_RECORD.REVIEWER_BY.eq
            (maintenanceRecordBo.getReviewerBy()));
        queryWrapper.and(MAINTENANCE_RECORD.RECTIFICATION_NUMBER.eq
            (maintenanceRecordBo.getRectificationNumber()));
        queryWrapper.and(MAINTENANCE_RECORD.REMARKS.eq
            (maintenanceRecordBo.getRemarks()));

        return queryWrapper;
    }

    /**
     * 查询维修记录
     *
     * @param id 维修记录主键
     * @return 维修记录
     */
    @Override
    public MaintenanceRecordVo selectById(Long id) {
        return this.getOneAs(query().where(MAINTENANCE_RECORD.ID.eq(id)), MaintenanceRecordVo.class);

    }


    /**
     * 查询维修记录列表
     *
     * @param maintenanceRecordBo 维修记录Bo
     * @return 维修记录集合
     */
    @Override
    public List<MaintenanceRecordVo> selectList(MaintenanceRecordBo maintenanceRecordBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(maintenanceRecordBo);
        return this.listAs(queryWrapper, MaintenanceRecordVo.class);
    }

    /**
     * 分页查询维修记录列表
     *
     * @param maintenanceRecordBo 维修记录Bo
     * @return 分页维修记录集合
     */
    @Override
    public PageResult<MaintenanceRecordVo> selectPage(MaintenanceRecordBo maintenanceRecordBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(maintenanceRecordBo);
        Page<MaintenanceRecordVo> page = this.pageAs(PageQuery.build(), queryWrapper, MaintenanceRecordVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增维修记录
     *
     * @param maintenanceRecordBo 维修记录Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(MaintenanceRecordBo maintenanceRecordBo) {
        MaintenanceRecord maintenanceRecord = MapstructUtils.convert(maintenanceRecordBo, MaintenanceRecord.class);

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

    /**
     * 新增维修记录，前台提供主键值，一般用于导入的场合
     *
     * @param maintenanceRecordBo 维修记录Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(MaintenanceRecordBo maintenanceRecordBo) {
        MaintenanceRecord maintenanceRecord = MapstructUtils.convert(maintenanceRecordBo, MaintenanceRecord.class);


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

    /**
     * 修改维修记录
     *
     * @param maintenanceRecordBo 维修记录Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(MaintenanceRecordBo maintenanceRecordBo) {
        MaintenanceRecord maintenanceRecord = MapstructUtils.convert(maintenanceRecordBo, MaintenanceRecord.class);
        if (ObjectUtil.isNotNull(maintenanceRecord) && ObjectUtil.isNotNull(maintenanceRecord.getId())) {
            return this.updateById(maintenanceRecord);
        }
        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, MaintenanceRecordImportVo.class, new MaintenanceRecordImportListener(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<MaintenanceRecordVo> listVo, String sheetName, LoginUser loginUser) {
        ExcelResultRes result = excelService.exportExcel(listVo, sheetName, MaintenanceRecordVo.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));
    }

}
