package com.ho.filecenter.controller;

import com.alibaba.excel.EasyExcel;
import com.ho.common.tools.annotation.LogAnnotation;
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.service.RedisService;
import com.ho.filecenter.entity.Power;

import com.ho.filecenter.service.PowerDetailService;
import com.ho.filecenter.service.PowerService;
import com.ho.filecenter.vo.PowerDetailVo;
import com.ho.filecenter.vo.PowerImport;
import com.ho.filecenter.vo.QueryPower;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
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 org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gyan
 * @desc: 发电量和收益功能
 * @DateTime: 2023/3/16 10:45
 */
@RestController
@RequestMapping(ContextConstant.MEDIA_CONTEXT + "power")
@Api(tags = "发电量和收益功能-excel基本信息")
@Slf4j
public class PowerController {
    @Autowired
    PowerService powerService;

    @Autowired
    PowerDetailService powerDetailService;

    @Autowired
    private RedisService redisService;

    //查（无入参）
    @PostMapping("/queryList")
    @ApiOperation(value = "发电量和收益功能列表")

    public DataResult<List<Power>> queryList(HttpServletRequest request, @RequestBody QueryPower power) {
        DataResult<List<Power>> result = DataResult.success();
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser user = redisService.getSimpleUserByToken(token);
        List<Power> powerList = powerService.queryList(user.getGroupId(), power);
        List<Power> list =new ArrayList<>();
        //根据项目名称进行过滤
        list = powerList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p -> p.getProjectName()))), ArrayList::new));
        //过滤排序
        if(!list.isEmpty()){
            list = list.stream().sorted(Comparator.comparing(Power::getCreateTime).reversed()).collect(Collectors.toList());
            log.info("list" + list);
        }

        result.setData(list);
        return result;
    }

    //改（先根据id将明细表中的数据重新入库，后将将基本信息进行更新）
    @PostMapping("update")
    @ApiOperation(value = "列表修改")
    @LogAnnotation(title = "发电量和收益", action = "更新发电量和收益")
    public DataResult update(@RequestBody @Valid PowerDetailVo vo) {
        powerService.update(vo);
        return DataResult.success();
    }


    @PostMapping("/importExcel")
    @ApiOperation("导入发电量和收益功能")
    @LogAnnotation(title = "发电量和收益", action = "导入发电量和收益")
    public void importExcel(@RequestBody MultipartFile file, HttpServletRequest request) {
        List<PowerImport> list = null;

        try {
            //默认是从第二行开始读取，也就是去掉表头
            // 直接使用EasyExcel.read(file.getInputStream()).head(TestComplexDao.class).sheet().doReadSync();
            //设置headRowNumber(0)就是从excel第一行读取
            list = EasyExcel.read(file.getInputStream()).headRowNumber(0).head(PowerImport.class).sheet().doReadSync();
        } catch (Exception e) {
            log.error(e.getMessage());
            //请核对excel格式
            throw new BusinessException(BaseResponseCode.PLEASE_CHECK_THE_EXCEL_FORMAT);
        }
        //增加判断list是否为空
        if (list.isEmpty()) {
            throw new BusinessException(BaseResponseCode.EXCEL_DATA_TABLE_EMPTY);
        }
        String token = request.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser user = redisService.getSimpleUserByToken(token);
        if (user.getPlatSuper()) {
            throw new BusinessException(BaseResponseCode.PLATFORM_ADMIN_CANNOT_DIRECTLY_USE);
        }
        powerService.importExcel(user, list);
    }


    @PostMapping("exportTemplate")
    @ApiOperation(value = "导出电费结算单模板")
    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();
            }
        }
    }

    // 导出模板
    private static InputStream getResourcesFileInputStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }

}
