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

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.biz.enums.DeviceResponseEnum;
import com.njcn.device.line.mapper.LineDetailMapper;
import com.njcn.device.pq.mapper.LineMarkMapper;
import com.njcn.device.pq.pojo.bo.excel.LineMark;
import com.njcn.device.pq.pojo.param.TerminalMainQueryParam;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.device.pq.pojo.vo.LineMarkVO;
import com.njcn.device.pq.service.LineMarkService;
import com.njcn.poi.util.PoiUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.enums.SystemResponseEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * pqs
 * 监测点评分
 *
 * @author cdf
 * @date 2022/5/10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LineMarkServiceImpl implements LineMarkService {

    private final DicDataFeignClient dicDataFeignClient;

    private final LineMarkMapper lineMarkMapper;

    private final LineDetailMapper lineDetailMapper;

    @Override
    public String batchExport(MultipartFile file, HttpServletResponse response) {
        ImportParams params = new ImportParams();
        //头行忽略的行数
        // 标题行设置为0行，默认是0，可以不设置
        // params.setHeadRows(1);
        // 标题行设置为0行，默认是0，可以不设置
        //params.setTitleRows(1);
        params.setNeedVerify(true);
        //第一个sheet为台账信息
        params.setStartSheetIndex(0);
        params.setSheetNum(1);
        ExcelImportResult<LineMark> lineMarkExcelImportResult = null;
        try {
            lineMarkExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), LineMark.class, params);
        } catch (Exception e) {
            throw new BusinessException(DeviceResponseEnum.Excel_ERROR);
        }
        //如果存在非法数据，将不合格的数据导出
        if (lineMarkExcelImportResult.isVerifyFail()) {
            PoiUtil.exportFileByWorkbook(lineMarkExcelImportResult.getFailWorkbook(), "非法台账信息.xlsx", response);
            return CommonResponseEnum.FAIL.getMessage();
        }


        //不存在非法数据进行录入
        List<DictData> lineGradeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_LEVEL.getName()).getData();
        if (CollectionUtil.isEmpty(lineGradeList)) {
            throw new BusinessException(SystemResponseEnum.LINE_MARK_EMPTY);
        }
        //监测是否存在监测点
        Integer flag = 1;
        for (LineMark item : lineMarkExcelImportResult.getList()) {
            String errMsg = "第" + flag + "行";
            LineMarkVO m = lineMarkMapper.getLineMarkData(item.getGdName(), item.getSubName(), item.getDevName(), item.getLineName());
            if (Objects.isNull(m)) {
                return errMsg + "未匹配到监测点对象，请仔细检查!";
            } else {
                if (Objects.isNull(m.getLineIndex()) || Objects.isNull(m.getDevIndex())) {
                    return errMsg + "获取监测点ID异常,请联系管理员!";
                }
                item.setLineIndex(m.getLineIndex());
                item.setDevIndex(m.getDevIndex());
                if (CollectionUtil.isNotEmpty(lineGradeList)) {
                    boolean g = false;
                    for (DictData dicData : lineGradeList) {
                        if (dicData.getName().equals(item.getMark())) {
                            item.setMark(dicData.getId());
                            g = true;
                        }
                    }
                    if (!g) {
                        return errMsg + "未知评级异常,请检查监测点评级是否存在!";
                    }
                } else {
                    throw new BusinessException(SystemResponseEnum.LINE_MARK_EMPTY);
                }
            }
            flag++;
        }
        //进行批量操作E
        lineMarkMapper.batchUpdateForLine(lineMarkExcelImportResult.getList());

        return CommonResponseEnum.SUCCESS.getMessage();

    }

    @Override
    public IPage<LineMarkVO> getLineMark(TerminalMainQueryParam terminalMainQueryParam) {
        Page<LineMarkVO> page = new Page<>(terminalMainQueryParam.getPageNum(), terminalMainQueryParam.getPageSize());
        return lineMarkMapper.getLineMark(page, terminalMainQueryParam.getComFlag(), terminalMainQueryParam.getLineGrade(), terminalMainQueryParam.getSearchValue());
    }

    @Override
    public List<LineMark> exportLineMark(TerminalMainQueryParam terminalMainQueryParam){
        return lineMarkMapper.exportLineMark(terminalMainQueryParam.getComFlag(), terminalMainQueryParam.getLineGrade(), terminalMainQueryParam.getSearchValue());
    }

    @Override
    public boolean singleOperate(String lineIndex, String lineGrade) {
        return lineMarkMapper.singleOperate(lineIndex, lineGrade);
    }

    @Override
    public LineDetail getLineGradeById(String id) {
        return lineDetailMapper.selectById(id);
    }
}
