package com.njcn.device.pq.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.mapper.PqsLineWeightMapper;
import com.njcn.device.pq.pojo.param.TerminalMainQueryParam;
import com.njcn.device.pq.pojo.po.PqsLineWeight;
import com.njcn.device.pq.pojo.vo.PqsLineWeightVo;
import com.njcn.device.pq.pojo.vo.TerminalTree;
import com.njcn.device.pq.service.IPqsLineWeightService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.device.utils.ExcelStyleUtil;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.poi.util.PoiUtil;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.InputStreamResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wr
 * @since 2023-08-24
 */
@Service
@RequiredArgsConstructor
public class PqsLineWeightServiceImpl extends ServiceImpl<PqsLineWeightMapper, PqsLineWeight> implements IPqsLineWeightService {

    private final LineMapper lineMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addLineWeight(PqsLineWeight lineWeight) {
        PqsLineWeight weight = this.getById(lineWeight.getLineIndex());
        if (ObjectUtil.isNotNull(weight)) {
            return this.updateById(lineWeight);
        }
        return this.save(lineWeight);
    }

    @Override
    public Page<PqsLineWeightVo> LineWeightList(TerminalMainQueryParam param) {
        return this.baseMapper.selectWeight(new Page(param.getPageNum(), param.getPageSize()),param);
    }

    @Override
    public InputStreamResource exportTemplate() throws IOException {
        ExportParams exportParams = new ExportParams("批量导入模板（所有字段均是必填,请严格按照模板标准填入数据）", "监测点评分权重录入信息");
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, PqsLineWeightVo.WeightExcel.class, new ArrayList<PqsLineWeightVo.WeightExcel>());
        //临时缓冲区
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //创建临时文件
        workbook.write(out);
        byte[] bookByteAry = out.toByteArray();
        InputStream in = new ByteArrayInputStream(bookByteAry);
        InputStreamResource inputStreamResource = new InputStreamResource(in);
        return inputStreamResource;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchWeight(MultipartFile file, HttpServletResponse response) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(1);
        params.setNeedVerify(true);
        //第一个sheet为台账信息
        params.setStartSheetIndex(0);
        params.setSheetNum(1);
        try {
            ExcelImportResult<PqsLineWeightVo.WeightExcel> weightList = ExcelImportUtil.importExcelMore(file.getInputStream(), PqsLineWeightVo.WeightExcel.class, params);
            //如果存在非法数据，将不合格的数据导出
            if (weightList.isVerifyFail()) {
                PoiUtil.exportFileByWorkbook(weightList.getFailWorkbook(), "非法监测点权重录入信息.xlsx", response);
            } else {
                saveWeightBase(weightList.getList());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportWeight(TerminalMainQueryParam terminalMainQueryParam) {
        List<PqsLineWeightVo.WeightExcel> weightExcels = this.baseMapper.selectWeights(terminalMainQueryParam);
        ExcelUtil.exportExcel("监测点权重信息.xlsx",PqsLineWeightVo.WeightExcel.class,weightExcels);
    }

    private void saveWeightBase(List<PqsLineWeightVo.WeightExcel> weightList) {
        List<PqsLineWeightVo.Msg> weightExcelMsg = new ArrayList<>();
        List<PqsLineWeight> info = new ArrayList<>();
        List<TerminalTree> provinceList = lineMapper.getProvinceList(null, 0);
        Map<String, String> areaMap = provinceList.stream().collect(Collectors.toMap(TerminalTree::getName, TerminalTree::getId));
        weightList.stream().forEach(x -> {
                    if (areaMap.containsKey(x.getAreaName())) {
                        x.setAreaName(areaMap.get(x.getAreaName()));
                    }
                }
        );
        for (PqsLineWeightVo.WeightExcel weightExcel : weightList) {
            String lineID = this.baseMapper.getLineID(weightExcel);
            if(StrUtil.isNotBlank(lineID)){
                PqsLineWeight weight = BeanUtil.copyProperties(weightExcel, PqsLineWeight.class);
                weight.setLineIndex(lineID);
                info.add(weight);
            }else{
                PqsLineWeightVo.Msg msg = BeanUtil.copyProperties(weightExcel, PqsLineWeightVo.Msg.class);
                msg.setMsg("未匹配到监测点对象，请仔细请检查/区域/供电公司/变电站名称/装置名称/监测点名称,是否对应正确");
                weightExcelMsg.add(msg);
            }

        }
        if(CollUtil.isNotEmpty(info)){
            this.saveOrUpdateBatch(info);
        }
        //错误信息不为空，则以excel的形式输出到前台
        if (CollectionUtil.isNotEmpty(weightExcelMsg)) {
            ExcelUtil.exportExcel("失败列表.xlsx", PqsLineWeightVo.Msg.class, weightExcelMsg);
        }

    }
}
