package com.mvc.service.external;

import com.mvc.model.StationAccModel;
import com.mvc.model.TAffiliatedunitModel;
import com.mvc.model.TAireadModel;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.service.TAffiliatedunitService;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 中北大学数据处理
 */
@Service
public class ZbdxDataService {
    private static Logger log = LoggerFactory.getLogger(ZbdxDataService.class);

    @Resource
    private Environment env;

    @Resource
    private TAireadService aireadService;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private TAffiliatedunitService affiliatedunitService;

    private static final String UNIT_CODE = "ce0d78d2e18f4016ac4153f0cc9be356";

    /**
     * 导出中北大学数据
     *
     * @param response
     * @param unitCode
     * @param date     yyyyMMdd
     */
    public void exportZbdxExcel(HttpServletResponse response, String unitCode, String date) {
        String templatePath = env.getProperty(ResourceTag.DownloadPathTag.getTag()) + "tj_template" + File.separator + "中北大学.xlsx";
        File file = new File(templatePath);
        if (!file.exists()) {
            return;
        }

        String startTime = date + "000000";
        String endTime = date + "235959";
        String temp = DateUtil.formateDate(DateUtil.parseTimeStr(endTime, DateUtil.PATTERN_DATA_UNSIGNED), "yyyy-MM-dd");
        Map<String, TAireadModel> map = getAireadData(unitCode, startTime, endTime);

        try {
            FileInputStream in = new FileInputStream(templatePath);
            //创建一个excel文件，名称为：
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Date now = new Date();
            int lastRowNum = sheet.getLastRowNum();
            String deviceSn = "";
            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                XSSFCell cell1 = row.getCell(1);
                if (cell1 != null) {
                    deviceSn = cell1.getStringCellValue();
                }
                TAireadModel model = null;
                if (StringUtils.isNotEmpty(deviceSn) && map.containsKey(deviceSn)) {
                    model = map.get(deviceSn);
                }

                XSSFCell cell3 = row.getCell(3);
                XSSFCell cell4 = row.getCell(4);
                cell4.setCellValue(temp);
                if (model == null || model.getResultValue() == null || model.getResultValue().compareTo(BigDecimal.ZERO) == 0) {
                    cell3.setCellValue("");
                } else {
                    cell3.setCellValue(model.getResultValue().doubleValue());
                }
            }

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] bytes = os.toByteArray();

            String fileName = "用水抄表数据(日)" + DateUtil.formateDate(now, "yyyyMMdd") + ".xlsx";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.close();
            os.close();
            workbook.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private Map<String, TAireadModel> getAireadData(String unitCode, String startTime, String endTime) {
        Map<String, TAireadModel> mapData = new HashMap<>();

        //同单位下多块表,合并计算
        List<TAffiliatedunitModel> unitModels = affiliatedunitService.findAffiliatedunitByCreateUnitCode2(unitCode);
        for (TAffiliatedunitModel model : unitModels) {
            List<StationAccModel> accModels = stationAccService.findStationAccByUnitCode(model.getUnitCode());

            BigDecimal sum = BigDecimal.ZERO;
            for (StationAccModel accModel : accModels) {
                Map<String, Object> map = aireadService.findAllTAireadByStationCode(accModel.getStationCode(), startTime, endTime, 1, 3);
                List<TAireadModel> list = (List<TAireadModel>) map.get("list");
                Optional<TAireadModel> optional = list.stream().filter(s -> s.getResultValue() != null).findFirst();
                if (optional.isPresent()) {
                    sum = sum.add(list.get(0).getResultValue());
                }else {
                    System.out.println("中北数据导出:" + accModel.getStationCode() + "数据无效");
                }
            }

            TAireadModel aireadModel = new TAireadModel();
            aireadModel.setStationCode(model.getUnitArea());
            aireadModel.setResultValue(sum);

            mapData.put(model.getUnitArea(), aireadModel);
        }

        return mapData;
    }
}
