package com.jjt.ws.controller;

import com.jjt.common.annotation.Log;
import com.jjt.common.core.controller.BaseController;
import com.jjt.common.core.domain.AjaxResult;
import com.jjt.common.enums.BusinessType;
import com.jjt.common.utils.DateUtils;
import com.jjt.elec.domain.ElecPrice;
import com.jjt.elec.service.IElecPriceService;
import com.jjt.ws.domain.TwinRzCalcMonth;
import com.jjt.ws.service.ITwinRzCalcMonthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 染整月统计Controller
 *
 * @author wukai
 * @date 2025-04-23
 */
@Api(tags = "染整月统计")
@RestController
@RequestMapping("/ws/rzMonth")
public class TwinRzCalcMonthController extends BaseController {
    @Resource
    private ITwinRzCalcMonthService twinRzCalcMonthService;
    @Resource
    private IElecPriceService elecPriceService;

    /**
     * 查询染整月统计列表
     */
    @ApiOperation("查询染整月统计列表")
    @GetMapping("/list")
    public AjaxResult list(TwinRzCalcMonth twinRzCalcMonth) {
        List<TwinRzCalcMonth> list = twinRzCalcMonthService.selectTwinRzCalcMonthList(twinRzCalcMonth);
        String para = (String) twinRzCalcMonth.getParams().get("month");
        int year = Integer.parseInt(para.split("-")[0]);
        int month = Integer.parseInt(para.split("-")[1]);
        ElecPrice elecPrice = elecPriceService.selectElecPriceByMonth(year, month);
        Map<String, Object> result = new HashMap<>(16);
        result.put("list", getDataTable(list));
        result.put("price", elecPrice);
        return AjaxResult.success(result);
    }

    /**
     * 导出染整月统计列表
     */
    @ApiOperation("导出染整月统计列表")
    @RequestMapping("/export")
    public void export(HttpServletResponse response, TwinRzCalcMonth twinRzCalcMonth) {
        List<TwinRzCalcMonth> list = twinRzCalcMonthService.selectTwinRzCalcMonthList(twinRzCalcMonth);
        String para = (String) twinRzCalcMonth.getParams().get("month");
        int year = Integer.parseInt(para.split("-")[0]);
        int month = Integer.parseInt(para.split("-")[1]);
        ElecPrice elecPrice = elecPriceService.selectElecPriceByMonth(year, month);
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("tpl/yr-energy-month.xlsx"); Workbook wb = new XSSFWorkbook(inputStream); OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            AtomicInteger colNum = new AtomicInteger(2);
            int rowNum = 31;
            list.forEach(vo -> {
                Cell[] cells = new Cell[rowNum];
                for (int i = 0; i < rowNum; i++) {
                    Row row = sheet.getRow(i);
                    cells[i] = row.getCell(colNum.get());
                }
                cells[0].setCellValue(DateUtils.parseDateToStrCN(vo.getDataDate()));
                cells[1].setCellValue(vo.getQzUse().doubleValue());
                cells[2].setCellValue(vo.getQzFUse().doubleValue());
                cells[3].setCellValue(vo.getQzGUse().doubleValue());
                cells[4].setCellValue(vo.getQzPUse().doubleValue());
                if (vo.getQzJfUse() != null) {
                    cells[5].setCellValue(vo.getQzJfUse().doubleValue());
                }
                cells[6].setCellValue(vo.getQzPrice().doubleValue());

                cells[7].setCellValue(vo.getHzUse().doubleValue());
                cells[8].setCellValue(vo.getHzFUse().doubleValue());
                cells[9].setCellValue(vo.getHzGUse().doubleValue());
                cells[10].setCellValue(vo.getHzPUse().doubleValue());
                if (vo.getHzJfUse() != null) {
                    cells[11].setCellValue(vo.getHzJfUse().doubleValue());
                }
                cells[12].setCellValue(vo.getHzPrice().doubleValue());

                cells[13].setCellValue(vo.getYrUse().doubleValue());
                cells[14].setCellValue(vo.getYrFUse().doubleValue());
                cells[15].setCellValue(vo.getYrGUse().doubleValue());
                cells[16].setCellValue(vo.getYrPUse().doubleValue());
                if (vo.getYrJfUse() != null) {
                    cells[17].setCellValue(vo.getYrJfUse().doubleValue());
                }
                cells[18].setCellValue(vo.getYrPrice().doubleValue());
                cells[19].setCellValue(vo.getDPrice().doubleValue());

                cells[20].setCellValue(vo.getSUse().doubleValue());
                cells[21].setCellValue(vo.getSPrice().doubleValue());

                cells[22].setCellValue(vo.getQLowUse().doubleValue());
                cells[23].setCellValue(vo.getQLowPrice().doubleValue());
                if (vo.getQMidUse() != null) {
                    cells[24].setCellValue(vo.getQMidUse().doubleValue());
                    cells[25].setCellValue(vo.getQMidPrice().doubleValue());
                }

                cells[26].setCellValue(vo.getTotalPrice().doubleValue());
                if (vo.getLength() != null) {
                    cells[27].setCellValue(vo.getLength().doubleValue());
                    cells[29].setCellValue(vo.getLengthPrice().doubleValue());
                }
                if (vo.getWeight() != null) {
                    cells[28].setCellValue(vo.getWeight().doubleValue());
                    cells[30].setCellValue(vo.getWeightPrice().doubleValue());
                }
                colNum.getAndIncrement();
            });

            Cell[] cells = new Cell[rowNum];
            for (int i = 0; i < rowNum; i++) {
                Row row = sheet.getRow(i);
                cells[i] = row.getCell(1);
            }

            cells[2].setCellValue("峰电(kwh/" + elecPrice.getPricePeak() + "）");
            cells[3].setCellValue("谷电(kwh/" + elecPrice.getPriceValley() + "）");
            cells[4].setCellValue("平电(kwh/" + elecPrice.getPriceFlat() + "）");
            cells[5].setCellValue("尖峰(kwh/" + elecPrice.getPriceSuperPeak() + "）");

            cells[8].setCellValue("峰电(kwh/" + elecPrice.getPricePeak() + "）");
            cells[9].setCellValue("谷电(kwh/" + elecPrice.getPriceValley() + "）");
            cells[10].setCellValue("平电(kwh/" + elecPrice.getPriceFlat() + "）");
            cells[11].setCellValue("尖峰(kwh/" + elecPrice.getPriceSuperPeak() + "）");

            cells[14].setCellValue("峰电(kwh/" + elecPrice.getPricePeak() + "）");
            cells[15].setCellValue("谷电(kwh/" + elecPrice.getPriceValley() + "）");
            cells[16].setCellValue("平电(kwh/" + elecPrice.getPriceFlat() + "）");
            cells[17].setCellValue("尖峰(kwh/" + elecPrice.getPriceSuperPeak() + "）");

            cells[20].setCellValue("工业水(m³/" + elecPrice.getWaterPrice().doubleValue() + "）");
            cells[22].setCellValue("低压蒸汽(GJ/" + elecPrice.getLowStreamPrice().doubleValue() + "）");
            cells[24].setCellValue("中亚蒸汽(GJ/" + elecPrice.getMidStreamPrice().doubleValue() + "）");

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("染整线统计" + DateUtils.dateTimeNow() + ".xlsx", "UTF-8"));
            response.setContentType("application/octet-stream");
            wb.write(outputStream);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取染整月统计详细信息
     */
    @ApiOperation("获取染整月统计详细信息")
    //@PreAuthorize("@ss.hasPermi('rzMonth:rzMonth:query')")
    @GetMapping(value = "/{calcId}")
    public AjaxResult getInfo(@PathVariable("calcId") Long calcId) {
        return success(twinRzCalcMonthService.selectTwinRzCalcMonthByCalcId(calcId));
    }

    /**
     * 新增染整月统计
     */
    @ApiOperation("新增染整月统计")
    //@PreAuthorize("@ss.hasPermi('rzMonth:rzMonth:add')")
    @Log(title = "染整月统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TwinRzCalcMonth twinRzCalcMonth) {
        return toAjax(twinRzCalcMonthService.insertTwinRzCalcMonth(twinRzCalcMonth));
    }

    /**
     * 修改染整月统计
     */
    @ApiOperation("修改染整月统计")
    //@PreAuthorize("@ss.hasPermi('rzMonth:rzMonth:edit')")
    @Log(title = "染整月统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TwinRzCalcMonth twinRzCalcMonth) {
        return toAjax(twinRzCalcMonthService.updateTwinRzCalcMonth(twinRzCalcMonth));
    }

    /**
     * 删除染整月统计
     */
    @ApiOperation("删除染整月统计")
    //@PreAuthorize("@ss.hasPermi('rzMonth:rzMonth:remove')")
    @Log(title = "染整月统计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{calcIds}")
    public AjaxResult remove(@PathVariable Long[] calcIds) {
        return toAjax(twinRzCalcMonthService.deleteTwinRzCalcMonthByCalcIds(calcIds));
    }
}
