package com.artfess.yhxt.specialcheck.manager.impl;

import cn.hutool.core.bean.BeanUtil;
import com.artfess.base.model.CommonResult;
import com.artfess.poi.Excel;
import com.artfess.poi.editor.IFontEditor;
import com.artfess.poi.style.Align;
import com.artfess.poi.style.BorderStyle;
import com.artfess.poi.style.Color;
import com.artfess.poi.style.font.BoldWeight;
import com.artfess.poi.style.font.Font;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.model.SysDictionaryDetail;
import com.artfess.yhxt.specialcheck.model.BizMqiCheckDetail;
import com.artfess.yhxt.specialcheck.dao.BizMqiCheckDetailDao;
import com.artfess.yhxt.specialcheck.manager.BizMqiCheckDetailManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.specialcheck.vo.MqiCheckDetailVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * MQI检查数据表明细表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author wangping
 * @since 2021-08-13
 */
@Service
public class BizMqiCheckDetailManagerImpl extends BaseManagerImpl<BizMqiCheckDetailDao, BizMqiCheckDetail> implements BizMqiCheckDetailManager {

    @Resource
    private SysDictionaryManager sysDictionaryManager;

    @Override
    public List<BizMqiCheckDetail> selectListByMqiDataId(String id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("MQI_DATA_ID_", id);
       return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public CommonResult<String> importData(String mqiId, MultipartFile file) {
        try {
            List<BizMqiCheckDetail> bizMqiCheckDetailArrayList = new ArrayList<>();
            List<MqiCheckDetailVo> mqiCheckDetailVos = ExcelUtil.readExcel(MqiCheckDetailVo.class, file);
            //方向
            Map<String, List<SysDictionaryDetail>> fx = sysDictionaryManager.queryDictItemsByCode("qlfx");
            //评定等级
            Map<String, List<SysDictionaryDetail>> pddj = sysDictionaryManager.queryDictItemsByCode("MQI-pddj");
            mqiCheckDetailVos.forEach(s->{
                BizMqiCheckDetail bizMqiCheckDetail = s.getBizMqiCheckDetail(s);
                //方向
                List<SysDictionaryDetail> fxDetails = fx.get("qlfx");
                for (int i = 0; i < fxDetails.size(); i++) {
                    Map map = (Map)fxDetails.get(i);
                    SysDictionaryDetail detail = BeanUtil.toBean(map, SysDictionaryDetail.class);
                    if (detail.getName().equals(bizMqiCheckDetail.getDirectionValue())){
                        bizMqiCheckDetail.setDirection(detail.getValue());
                    }
                }
                //评定等级
                List<SysDictionaryDetail> pddjDetails = pddj.get("MQI-pddj");
                for (int i = 0; i < pddjDetails.size(); i++) {
                    Map map = (Map)pddjDetails.get(i);
                    SysDictionaryDetail detail = BeanUtil.toBean(map, SysDictionaryDetail.class);
                    if (detail.getName().equals(bizMqiCheckDetail.getRatingValue())){
                        bizMqiCheckDetail.setRating(Integer.parseInt(detail.getValue()));
                    }
                }
                bizMqiCheckDetailArrayList.add(bizMqiCheckDetail);
            });
            this.saveBatch(bizMqiCheckDetailArrayList);
            return new CommonResult<String>(true,"导入成功");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("导入失败");
        }


    }

    @Override
    public CommonResult<List<BizMqiCheckDetail>> getimportData(MultipartFile file) {
        try {
            List<BizMqiCheckDetail> bizMqiCheckDetailArrayList = new ArrayList<>();
            List<MqiCheckDetailVo> mqiCheckDetailVos = ExcelUtil.readExcel(MqiCheckDetailVo.class, file);
            //方向
            Map<String, List<SysDictionaryDetail>> fx = sysDictionaryManager.queryDictItemsByCode("qlfx");
            //评定等级
            Map<String, List<SysDictionaryDetail>> pddj = sysDictionaryManager.queryDictItemsByCode("MQI-pddj");
            mqiCheckDetailVos.forEach(s->{
                BizMqiCheckDetail bizMqiCheckDetail = s.getBizMqiCheckDetail(s);
                //方向
                List<SysDictionaryDetail> fxDetails = fx.get("qlfx");
                for (int i = 0; i < fxDetails.size(); i++) {
                    Map map = (Map)fxDetails.get(i);
                    SysDictionaryDetail detail = BeanUtil.toBean(map, SysDictionaryDetail.class);
                    if (detail.getName().equals(bizMqiCheckDetail.getDirectionValue())){
                        bizMqiCheckDetail.setDirection(detail.getValue());
                    }
                }
                //评定等级
                List<SysDictionaryDetail> pddjDetails = pddj.get("MQI-pddj");
                for (int i = 0; i < pddjDetails.size(); i++) {
                    Map map = (Map)pddjDetails.get(i);
                    SysDictionaryDetail detail = BeanUtil.toBean(map, SysDictionaryDetail.class);
                    if (detail.getName().equals(bizMqiCheckDetail.getRatingValue())){
                        bizMqiCheckDetail.setRating(Integer.parseInt(detail.getValue()));
                    }
                }
                bizMqiCheckDetailArrayList.add(bizMqiCheckDetail);
            });
            return new CommonResult<List<BizMqiCheckDetail>>(true,"操作成功",bizMqiCheckDetailArrayList);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("操作失败");
        }
    }

    @Override
    public void exportMqiDetail(String id, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(id)){
                throw new RuntimeException("id 不能为空");
            }
            QueryWrapper<BizMqiCheckDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotEmpty(id),"MQI_DATA_ID_",id);
            List<BizMqiCheckDetail> list = this.list(queryWrapper);
            Map<String,String> exportMap = new LinkedHashMap<>();
            exportMap.put("directionValue","方向");
            exportMap.put("startPeg","起点桩号");
            exportMap.put("endPeg","结束桩号");
            exportMap.put("length","长度(m)");
            exportMap.put("mqiAvg","MQI");
            exportMap.put("sciAvg","路基SCI");
            exportMap.put("pqiAvg","路面PQI");
            exportMap.put("pciAvg","路面损坏PCI");
            exportMap.put("rqiAvg","行驶质量RQI");
            exportMap.put("rdiAvg","车辙深度RDI");
            exportMap.put("pbiAvg","跳车PBI");
            exportMap.put("pwiAvg","磨耗PWI");
            exportMap.put("pssiAvg","结构强度PSSI");
            exportMap.put("bciAvg","桥隧构造物BCI");
            exportMap.put("tciAvg","沿线设施TCI");
            exportMap.put("ratingValue","评定等级");
            List<HashMap<String, Object>> collect = list.stream().map(s -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("directionValue", s.getDirectionValue());
                map.put("startPeg",s.getStartPeg());
                map.put("endPeg", s.getEndPeg());
                map.put("length", s.getLength());
                map.put("mqiAvg", s.getMqiAvg());
                map.put("sciAvg", s.getSciAvg());
                map.put("pqiAvg", s.getPqiAvg());
                map.put("pciAvg", s.getPciAvg());
                map.put("rqiAvg", s.getRqiAvg());
                map.put("rdiAvg", s.getRdiAvg());
                map.put("pbiAvg", s.getPbiAvg());
                map.put("pwiAvg", s.getPwiAvg());
                map.put("pssiAvg", s.getPssiAvg());
                map.put("bciAvg", s.getBciAvg());
                map.put("tciAvg", s.getTciAvg());
                map.put("ratingValue", s.getRatingValue());
                return map;
            }).collect(Collectors.toList());
            HSSFWorkbook hssfWorkbook = this.exportExcel("MQI数据详情", 10, exportMap, collect,0);
            ExcelUtil.downloadExcel(hssfWorkbook,"MQI数据详情"+System.currentTimeMillis(),response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private   HSSFWorkbook exportExcel(String title, int rowHeight, Map<String, String> fieldMap, List data,int headerRowIndex)
            throws Exception {

        int size = fieldMap.size();
        Excel excel = new Excel();

        int titleCols = size; // 列数

        if (titleCols == 0) {
            throw new Exception("请设置列！");
        }

        // 设置页名
        excel.sheet().sheetName(title);// 重命名当前处于工作状态的表的名称

        int i = 0;
        // 设置表头，第二行开始
        for (String name : fieldMap.values()) { // 表头已经排序过了

            excel.cell(headerRowIndex, i).value("").border(BorderStyle.MEDIUM, Color.BLACK) // 设置外边框样式
                    .fontHeightInPoint(10).warpText(true).align(Align.LEFT); // 设置水平对齐方式

            excel.cell(headerRowIndex, i).value(name).align(Align.CENTER) // 设置水平对齐方式
                    .bgColor(Color.GREY_25_PERCENT) // 设置背景色
                    .fontHeightInPoint(10).width(256 * 10)// 增加宽度
                    .border(BorderStyle.THIN, Color.BLACK) // 设置外边框样式
                    .font(new IFontEditor() { // 设置字体
                        @Override
                        public void updateFont(Font font) {
                            font.boldweight(BoldWeight.BOLD);// 粗体
                            font.color(Color.BLACK);// 字体颜色
                        }
                    });
            i++;
        }

        // 插入数据，第三行开始
        int rows = headerRowIndex+1;
        for (Object obj : data) {
            Map rowObj = (Map) obj;
            int col = 0;
            for (String key : fieldMap.keySet()) {
                String val = rowObj.get(key) == null ? "" : rowObj.get(key).toString();
                excel.cell(rows, col).value(val).border(BorderStyle.MEDIUM, Color.BLACK) // 设置外边框样式
                        .fontHeightInPoint(10).warpText(true).align(Align.CENTER); // 设置水平对齐方式
                col++;
            }
            rows++;
        }

        return excel.getWorkBook();
    }
}
