package com.ho.business.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.github.pagehelper.PageInfo;
import com.ho.business.service.EarningsCalculateService;
import com.ho.business.vo.req.report.ReportReqVO;
import com.ho.business.vo.resp.income.RevenueOverview;
import com.ho.business.vo.resp.income.RevenueOverviewData;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.util.PageResult;
import com.ho.common.tools.util.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author yule
 * @Date 2024/2/28 9:15
 * @desc ${}
 */
@RestController
@RequestMapping(ContextConstant.BUSINESS + "revenueOverview")
@Api(tags = "收益总览")
@Slf4j
public class RevenueOverviewController {

    @Autowired
    EarningsCalculateService earningsCalculateService;

    @PostMapping("chargingAndDischargingData")
    @ApiOperation("充放电数据")
    public DataResult<PageResult<RevenueOverviewData>> getRevenueOverviewData(@RequestBody @Valid ReportReqVO vo) {
        List<RevenueOverviewData> dataList = earningsCalculateService.getRevenueOverviewData(vo);
        //java内存分页
        PageResult pageResult = new PageResult<>();
        if (!dataList.isEmpty()) {
            List list = new ArrayList(0);
            // 如果别的电站数量比较多,翻到最后一页切换电站会出现页码超过现有数组长度
            Integer pageNum = vo.getPageNum();
            Integer pageSize = vo.getPageSize();
            if ( pageNum <= dataList.size() / pageSize + 1 ) {
                list = PageUtils.dealList(dataList, pageNum, pageSize);
            }
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(dataList.size());
            pageResult.setTotalPages(dataList.size() / pageSize + 1);
        } else {
            pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }
        return DataResult.success(pageResult);
    }

    @PostMapping("incomeFromInvestment")
    @ApiOperation("投资收益")
    public DataResult<RevenueOverview> getInvestment(@RequestBody @Valid ReportReqVO vo) {
        RevenueOverview revenueOverview = earningsCalculateService.getInvestment(vo);
        return DataResult.success(revenueOverview);
    }

    @GetMapping("elecPrice")
    @ApiOperation(value = "电价曲线")
    public DataResult getElecPrice(Integer stationId) {
        List<Map<String,Object>> list = earningsCalculateService.getElecPrice(stationId);
        return DataResult.success(list);
    }


    @PostMapping("revenue")
    @ApiOperation("收益曲线")
    public DataResult<List<RevenueOverviewData>> getRevenue(@RequestBody @Valid ReportReqVO vo) {
        List<RevenueOverviewData> dataList = earningsCalculateService.getRevenueOverviewData(vo);
        return DataResult.success(dataList);
    }

    @PostMapping("export")
    @ApiOperation(value = "导出")
    public void export(@RequestBody @Valid ReportReqVO vo, HttpServletResponse response, HttpServletRequest request) {
        String lang = request.getHeader(CommonConstant.LANG);
        List<RevenueOverviewData> revenueOverviewData = earningsCalculateService.getRevenueOverviewData(vo);
        RevenueOverview investment = earningsCalculateService.getInvestment(vo);
        //在内存操作，写到浏览器
        String fileName = "demo.xlsx";
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" +  new String(fileName.getBytes("UTF-8")));
            //文件模板输入流
            String path="template/RevenueOverview.xlsx";
            if(CommonConstant.langTemp.EN_US.equals(lang)){
                path="template/RevenueOverviewen_US.xlsx";
            }else if (CommonConstant.langTemp.FR_FR.equals(lang)){
                path="template/RevenueOverviewen_FRA.xlsx";
            }else if (CommonConstant.langTemp.ES_ES.equals(lang)){
                path="template/RevenueOverviewen_SPA.xlsx";
            }else if (CommonConstant.langTemp.DE_DE.equals(lang)){
                path="template/RevenueOverviewen_DE.xlsx";
            }else if (CommonConstant.langTemp.PL_PL.equals(lang)){
                path="template/RevenueOverviewen_PL.xlsx";
            }else if (CommonConstant.langTemp.AR_EG.equals(lang)){
                path="template/RevenueOverviewen_ARA.xlsx";
            }
            InputStream inputStream = new ClassPathResource(path).getInputStream();

            ExcelWriter writer = EasyExcel.write(out).withTemplate(inputStream).build();
            WriteSheet sheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(true).build();

            writer.fill(new FillWrapper("data", revenueOverviewData), fillConfig, sheet);
            //填充数据
            writer.fill(investment,fillConfig,sheet);
            //填充完成
            writer.finish();
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
