package com.ho.business.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ho.business.common.BusiTool;
import com.ho.business.entity.IncomeQRate;
import com.ho.business.entity.IncomeRate;
import com.ho.business.entity.IncomeRateMapping;
import com.ho.business.entity.IncomeTotal;
import com.ho.business.service.IncomeMeasurementService;
import com.ho.common.tools.annotation.LogAnnotation;
import com.ho.common.tools.annotation.TokenIgnore;
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.entity.SimpleUser;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.util.BigDecimalUtil;
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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(ContextConstant.BUSINESS + "income")
@Api(tags = "收益预测")
@Slf4j
public class IncomeMeasurementController {

    @Autowired
    BigDecimalUtil bigDecimalUtil;

    @PostMapping("exportTemplate")
    @ApiOperation(value = "导出模板")
    @LogAnnotation(title = "收益预测", action = "导出模板")
    public void exportTemplate(HttpServletResponse response){
        ServletOutputStream out =null;
        try {
            String fileName = URLEncoder.encode("template.xls", "utf-8");
            InputStream fis = getResourcesFileInputStream("template/template.xls");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            out = response.getOutputStream();
            out.write(buffer);
        } catch (Exception ex) {
            System.out.println("下载失败");
        }finally {
            try {
                assert out != null;
                out.flush();
                out.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    @Autowired
    private IncomeMeasurementService incomeMeasurementService;

    @Autowired
    BusiTool busiTool;
    // 查询费率模板

    @PostMapping("getRateTemplateList")
    @ApiOperation(value = "查询费率模板")
    public DataResult getRateTemplateList( @RequestBody IncomeRate incomeRate)
    {
        return DataResult.success(incomeMeasurementService.getRateTemplateList(incomeRate.getStationId()));
    }
    // 根据模板查询费率

    @PostMapping("getRateList")
    @ApiOperation(value = "根据费率模板查询费率")
    public DataResult getRateList( @RequestBody IncomeRate incomeRate)
    {
        return DataResult.success(incomeMeasurementService.getRateList(incomeRate.getTemplateId()));
    }
    // 查询费率详情

    @PostMapping("getRateDetails")
    @ApiOperation(value = "查询费率详情")
    public DataResult getRateDetails(@RequestBody IncomeRate incomeRate)
    {
        return DataResult.success(incomeMeasurementService.getRateDetails(incomeRate.getRateId(),incomeRate.getTemplateId()));
    }
    //查询收益测算-企业用电-费率设置表数据

    @PostMapping("selectIncomeRates")
    @ApiOperation(value = "企业用电费率查询")
    public DataResult<List<IncomeRate>> selectIncomeRates(@RequestBody IncomeRate incomeRate){
        return DataResult.success(incomeMeasurementService.selectIncomeRates(incomeRate));
    }
    // 查询上网用电数据

    @PostMapping("selectQRate")
    @ApiOperation(value = "查询上网用电数据")
    public DataResult<List<IncomeQRate>> selectQRate(@RequestBody IncomeQRate surfQRate){
        return DataResult.success(incomeMeasurementService.selectQRate(surfQRate));
    }


    @PostMapping("insertOrUpdateIncomeRates")
    @ApiOperation(value = "增删改费率")
    @LogAnnotation(title = "费率模版", action = "增删改费率")
    public DataResult insertOrUpdateIncomeRates(@RequestBody List<IncomeRate> incomeRates,HttpServletRequest request){
        //下一个月才能新增上网用电数据上一个月的收益
        String dataDate = incomeRates.get(0).getDataDate();
        DateTime end = DateUtil.parse(dataDate, CommonConstant.DATE_YM);
        Date now = new Date();
        if ( DateUtil.isIn(end, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now))){
            throw new BusinessException(BaseResponseCode.INCOME_ADD_AT_THE_END_OF_THE_MONTH);
        }
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = busiTool.getSimpleUser(token);
        return DataResult.success(incomeMeasurementService.insertOrUpdateIncomeRates(incomeRates,simpleUser));
    }
    // 新增上网用电数据

    @PostMapping("insertSurfQRate")
    @ApiOperation(value = "新增上网用电数据")
    @LogAnnotation(title = "费率模版", action = "新增上网用电数据")
    public DataResult insertSurfQRate(@RequestBody IncomeQRate surfQRate,HttpServletRequest request){
        //下一个月才能新增上网用电数据上一个月的收益
        String dataDate = surfQRate.getDataDate();
        DateTime end = DateUtil.parse(dataDate, CommonConstant.DATE_YM);
        Date now = new Date();
        if ( DateUtil.isIn(end, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now))){
            throw new BusinessException(BaseResponseCode.INCOME_ADD_AT_THE_END_OF_THE_MONTH);
        }
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = busiTool.getSimpleUser(token);
        return DataResult.success(incomeMeasurementService.insertSurfQRate(surfQRate,simpleUser));
    }
    // 修改上网用电数据
    @PostMapping("modifySurfRate")
    @ApiOperation(value = "修改上网用电数据")
    @LogAnnotation(title = "费率模版", action = "修改上网用电数据")
    public DataResult modifySurfRate(@RequestBody IncomeQRate surfQRate,HttpServletRequest request){
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = busiTool.getSimpleUser(token);
        return DataResult.success(incomeMeasurementService.modifySurfRate(surfQRate,simpleUser.getUserId()));
    }
    // 确认按钮

    @PostMapping("confirm")
    @ApiOperation(value = "确认按钮")
    @LogAnnotation(title = "费率模版", action = "确认")
    public DataResult confirm(@RequestBody IncomeTotal incomeTotal){
        //下一个月才能新增上网用电数据上一个月的收益
        String dataDate = incomeTotal.getDataDate();
        DateTime end = DateUtil.parse(dataDate, CommonConstant.DATE_YM);
        Date now = new Date();
        if ( DateUtil.isIn(end, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now))){
            throw new BusinessException(BaseResponseCode.INCOME_CONFIRMATION_AT_THE_END_OF_THE_MONTH);
        }
        return DataResult.success(incomeMeasurementService.confirm(incomeTotal));
    }
    // 导出模板
    private static InputStream getResourcesFileInputStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }

    // 导入excel
    @PostMapping("uploadExcel")
    @ApiOperation(value = "导入excel")
    @LogAnnotation(title = "收益预测", action = "导入excel")
    public DataResult uploadExcel(@RequestBody List<IncomeRate> incomeRates,HttpServletRequest request){
        //下一个月才能新增上网用电数据上一个月的收益
        //下一个月才能新增上网用电数据上一个月的收益
        String dataDate = incomeRates.get(0).getDataDate();
        DateTime end = DateUtil.parse(dataDate, CommonConstant.DATE_YM);
        Date now = new Date();
        if ( DateUtil.isIn(end, DateUtil.beginOfMonth(now), DateUtil.endOfMonth(now))){
            throw new BusinessException(BaseResponseCode.INCOME_ADD_AT_THE_END_OF_THE_MONTH);
        }
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser simpleUser = busiTool.getSimpleUser(token);
        return DataResult.success(incomeMeasurementService.excelInput(incomeRates,simpleUser));
    }

    @PostMapping("selectRates")
    @ApiOperation(value = "查询费率号(下拉框数据)")
    public DataResult<List<IncomeRateMapping>> selectRates(){
        return DataResult.success(incomeMeasurementService.selectRates());
    }

    @PostMapping("selectTotal")
    @ApiOperation(value = "查询累计收益")
    public DataResult<IncomeTotal> selectTotal(@RequestBody IncomeTotal incomeTotal){
        IncomeTotal result = incomeMeasurementService.selectTotal(incomeTotal);
        if (result != null) {
            bigDecimalUtil.keepTwoDecimalPlaces(result);
        }
        return DataResult.success(result);
    }


    @PostMapping("selectIncomeDetails")
    @ApiOperation(value = "查询企业用电详情")
    public DataResult<IncomeTotal> selectIncomeDetails(@RequestBody IncomeRate incomeRate) {
        return DataResult.success(incomeMeasurementService.selectIncomeDetails(incomeRate));
    }

    @PostMapping("jobDataManage")
    @TokenIgnore
    public DataResult jobDataManage(){
        log.info("15分钟 收益计算开始");

        incomeMeasurementService.jobDataManage();
        //15分钟收益计算结束
        return DataResult.success();
    }

}
