package org.eco.als.service.impl;

import cn.hutool.core.io.FileUtil;
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.DataImport;
import org.eco.als.domain.bo.DataImportBo;
import org.eco.als.domain.vo.DataImportImportVo;
import org.eco.als.domain.vo.DataImportVo;
import org.eco.als.listener.DataImportImportListener;
import org.eco.als.mapper.DataImportMapper;
import org.eco.als.service.IDataImportService;
import org.eco.als.utils.CsvUtils;
import org.eco.common.core.config.EcoConfig;
import org.eco.common.core.constant.Constants;
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.core.utils.file.FileUtils;
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.domain.vo.SysOssVo;
import org.eco.system.service.IImportExportService;
import org.eco.system.service.ISysOssService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

import static org.eco.als.domain.table.DataImportTableDef.DATA_IMPORT;

/**
 * 数据导入信息Service业务层处理
 *
 * @author wgk
 * @date 2024-07-22
 */
@Service
@Slf4j
public class DataImportServiceImpl extends BaseServiceImpl<DataImportMapper, DataImport> implements IDataImportService {
    @Resource
    private DataImportMapper dataImportMapper;

    @Resource
    private IExcelService excelService;

    @Resource
    private IImportExportService importExportService;
    @Resource
    private ISysOssService ossService;

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

    private QueryWrapper buildQueryWrapper(DataImportBo dataImportBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(DATA_IMPORT.OSS_ID.eq
            (dataImportBo.getOssId()));
        queryWrapper.and(DATA_IMPORT.SOURCE.eq
            (dataImportBo.getSource()));
        queryWrapper.and(DATA_IMPORT.SORTIE_NO.eq
            (dataImportBo.getSortieNo()));
        if (StringUtils.isNotBlank(dataImportBo.getAircraftId())) {
            queryWrapper.and(DATA_IMPORT.AIRCRAFT_ID.in
                (dataImportBo.getAircraftId().split(",")));
        }
        queryWrapper.and(DATA_IMPORT.FLIGHT_DATE.eq
            (dataImportBo.getFlightDate()));
        queryWrapper.and(DATA_IMPORT.STATUS.eq
            (dataImportBo.getStatus()));
        queryWrapper.orderBy(DATA_IMPORT.CREATE_TIME.desc());

        return queryWrapper;
    }

    /**
     * 查询数据导入信息
     *
     * @param id 数据导入信息主键
     * @return 数据导入信息
     */
    @Override
    public DataImportVo selectById(Long id) {
        return this.getOneAs(query().where(DATA_IMPORT.ID.eq(id)), DataImportVo.class);

    }


    /**
     * 查询数据导入信息列表
     *
     * @param dataImportBo 数据导入信息Bo
     * @return 数据导入信息集合
     */
    @Override
    public List<DataImportVo> selectList(DataImportBo dataImportBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(dataImportBo);
        return this.listAs(queryWrapper, DataImportVo.class);
    }

    /**
     * 分页查询数据导入信息列表
     *
     * @param dataImportBo 数据导入信息Bo
     * @return 分页数据导入信息集合
     */
    @Override
    public PageResult<DataImportVo> selectPage(DataImportBo dataImportBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(dataImportBo);
        Page<DataImportVo> page = this.pageAs(PageQuery.build(), queryWrapper, DataImportVo.class);
        return PageResult.build(page);
    }

    /**
     * 新增数据导入信息
     *
     * @param dataImportBo 数据导入信息Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(DataImportBo dataImportBo) {
        SysOssVo ossVo = ossService.getById(dataImportBo.getOssId());
        String path = StringUtils.substringAfter(ossVo.getFileName(), Constants.RESOURCE_PREFIX);
        String pathCsv = EcoConfig.getTempPath() + "/" + CsvUtils.getName(FileUtils.getNameNotSuffix(ossVo.getOriginalName()));
        File file = CsvUtils.excelToFileCsv(EcoConfig.getProfile() + path, pathCsv);
        ossVo = ossService.upload(file);
        FileUtil.del(pathCsv);
        dataImportBo.setOssId(ossVo.getOssId());
        DataImport dataImport = MapstructUtils.convert(dataImportBo, DataImport.class);
        return this.save(dataImport);//使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 新增数据导入信息，前台提供主键值，一般用于导入的场合
     *
     * @param dataImportBo 数据导入信息Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(DataImportBo dataImportBo) {
        DataImport dataImport = MapstructUtils.convert(dataImportBo, DataImport.class);
        return dataImportMapper.insertWithPk(dataImport) > 0;//前台传来主键值
    }

    /**
     * 修改数据导入信息
     *
     * @param dataImportBo 数据导入信息Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(DataImportBo dataImportBo) {
        SysOssVo ossVo = ossService.getById(dataImportBo.getOssId());
        String path = StringUtils.substringAfter(ossVo.getFileName(), Constants.RESOURCE_PREFIX);
        String pathCsv = EcoConfig.getTempPath() + "/" + CsvUtils.getName(FileUtils.getNameNotSuffix(ossVo.getOriginalName()));
        File file = CsvUtils.excelToFileCsv(EcoConfig.getProfile() + path, pathCsv);
        ossVo = ossService.upload(file);
        FileUtil.del(pathCsv);
        dataImportBo.setOssId(ossVo.getOssId());
        DataImport dataImport = MapstructUtils.convert(dataImportBo, DataImport.class);
        if (ObjectUtil.isNotNull(dataImport) && ObjectUtil.isNotNull(dataImport.getId())) {
            return this.updateById(dataImport);
        }
        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, DataImportImportVo.class, new DataImportImportListener(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<DataImportVo> listVo, String sheetName, LoginUser loginUser) {
        ExcelResultRes result = excelService.exportExcel(listVo, sheetName, DataImportVo.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));
    }

}
