package com.xhpc.activity.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.xhpc.activity.config.AliOSSProperties;
import com.xhpc.activity.domain.XhpcTradebillUploadRecordDomain;
import com.xhpc.activity.mapper.XhpcTradebillUploadRecordMapper;
import com.xhpc.activity.utils.ExcelExp;
import com.xhpc.activity.utils.ExcelUtilYu;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.utils.poi.ExcelUtil;
import com.xhpc.activity.domain.XhpcHistoryOrderDomain;
import com.xhpc.activity.domain.XhpcTradebillInternetCheckRecordDomain;
import com.xhpc.activity.mapper.XhpcHistoryOrderMapper;
import com.xhpc.activity.mapper.XhpcTradebillInternetCheckRecordMapper;
import com.xhpc.activity.service.InternetBillService;
import com.xhpc.activity.utils.DownloadUtil;
import com.xhpc.activity.vo.HDTradebillVo;
import com.xhpc.activity.vo.KDTradebillVo;
import com.xhpc.activity.vo.XDTTradebillVo;
import com.xhpc.activity.vo.XJTradeBillVo;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.LogUserUtils;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class InternetBillServiceImpl implements InternetBillService {
    @Resource
    LogUserUtils logUserUtils;
    @Resource
    XhpcTradebillInternetCheckRecordMapper internetCheckRecordMapper;

    @Resource
    XhpcHistoryOrderMapper historyOrderMapper;

    @Resource
    TokenService tokenService;

    @Resource
    XhpcTradebillUploadRecordMapper uploadRecordMapper;

    @Resource
    AliOSSProperties ossProperties;

    @Override
    public XhpcTradebillInternetCheckRecordDomain getInfoByPk(int pk) {

        return internetCheckRecordMapper.selectByPrimaryKey(pk);
    }

    @Override
    public boolean updateInfoByDomain(XhpcTradebillInternetCheckRecordDomain domain) {

        domain.setUpdateBy(SecurityUtils.getUserId());
        return internetCheckRecordMapper.updateStatusByPk(domain);
    }


    @Override
    public Integer insertInternetCheckList(XhpcTradebillUploadRecordDomain recordDomain, List<XhpcTradebillInternetCheckRecordDomain> internetCheckRecordDomainList) {

        Long userId = SecurityUtils.getUserId();
        for (XhpcTradebillInternetCheckRecordDomain domain : internetCheckRecordDomainList) {
            domain.setUploadId(recordDomain.getId());
            domain.setTenantId(recordDomain.getTenantId());
            domain.setCreateBy(userId);
            domain.setUpdateBy(userId);
        }
        return internetCheckRecordMapper.insertCheckList(internetCheckRecordDomainList);
    }


    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getInternetCheckList(Map<String, Object> params) {
        //获取登陆用户
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        Long sysUserId = sysUser.getUserId();

        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                params.put("type", 1);
                params.put("logOperatorId", logOperatorId);
                return internetCheckRecordMapper.selectListByParams(params);
            }else{
                //查询赋值的场站
                params.put("type", 2);
                params.put("logOperatorId", sysUserId);
                return internetCheckRecordMapper.selectListByParams(params);
            }
        }else{
            params.put("type", 0);
            params.put("logOperatorId", sysUserId);
            return internetCheckRecordMapper.selectListByParams(params);
        }
    }

    @Override
    public Map<String, Object> getStatusTotal(Map<String, Object> params) {
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        Long sysUserId = sysUser.getUserId();
        //获取登陆用户
        List<Map<String, Object>> resultList =new ArrayList<>();
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                params.put("type", 1);
                params.put("logOperatorId", logOperatorId);
                resultList =  internetCheckRecordMapper.selectTotalGroupbyStatus(params);
            }else{
                //查询赋值的场站
                params.put("type", 2);
                params.put("logOperatorId", sysUserId);
                resultList =  internetCheckRecordMapper.selectTotalGroupbyStatus(params);
            }
        }else{
            params.put("type", 0);
            params.put("logOperatorId", sysUserId);
            resultList =  internetCheckRecordMapper.selectTotalGroupbyStatus(params);
        }
        int successCount = 0;
        int failCount = 0;
        int uncheckCount = 0;
        int checkCount = 0;
        for (Map<String, Object> res : resultList) {
            switch (res.get("status").toString()) {
                case "0":
                    uncheckCount = Integer.parseInt(res.get("total").toString());
                    break;
                case "1":
                    failCount = Integer.parseInt(res.get("total").toString());
                    break;
                case "2":
                    successCount = Integer.parseInt(res.get("total").toString());
                    break;
                default:
                    break;
            }
        }
        checkCount = successCount + failCount;
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("successCount", successCount);
        resultMap.put("failCount", failCount);
        resultMap.put("uncheckCount", uncheckCount);
        resultMap.put("checkCount", checkCount);
        return resultMap;
    }


    /**
     * 获取恒大对账数据
     *
     * @param fileUrl 文件访问地址
     * @return 对账数据
     * @throws Exception 异常
     */
    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getHdInternetDataList(String fileUrl, String startTime, String endTime, String tenantId) throws Exception {

        File dataFile = DownloadUtil.downloadFile(fileUrl);
        return getHdInternetDataList(dataFile, startTime, endTime, tenantId);
    }


    /**
     * 获取小桔对账数据
     *
     * @param fileUrl 文件访问地址
     * @return 对账数据
     * @throws Exception 异常
     */
    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getXjInternetDataList(String fileUrl, String startTime, String endTime, String tenantId) throws Exception {

        File dataFile = DownloadUtil.downloadFile(fileUrl);
        return getXjInternetDataList(dataFile, startTime, endTime, tenantId);
    }


    /**
     * 获取新电途对账数据
     *
     * @param fileUrl 文件访问地址
     * @return 对账数据
     * @throws Exception 异常
     */
    @Override
    public void getXDTInternetDataList(HttpServletRequest request, HttpServletResponse response, String fileUrl, String startTime, String endTime, String tenantId) throws Exception {

        File dataFile = DownloadUtil.downloadFile(fileUrl);
        getXDTInternetDataList(request,response,dataFile, startTime, endTime, tenantId);
    }


    /**
     * 获取快电对账数据
     *
     * @param fileUrl 文件访问地址
     * @return 对账数据
     * @throws Exception 异常
     */
    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getKDInternetDataList(String fileUrl, String startTime, String endTime, String tenantId) throws Exception {

        File dataFile = DownloadUtil.downloadFile(fileUrl);
        return getKDInternetDataList(dataFile, startTime, endTime, tenantId);
    }

    /**
     * 获取恒大对账数据
     *
     * @param dataFile 对账单文件,格式为xlsx
     * @return 对账数据
     */
    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getHdInternetDataList(File dataFile, String startTime, String endTime, String tenantId) throws Exception {

        List<XhpcTradebillInternetCheckRecordDomain> checkRecordDomainList = new ArrayList<>();
        String suffix = dataFile.getName().substring(dataFile.getName().lastIndexOf(".") + 1);
        List<HDTradebillVo> hdTradebillVoList = new ArrayList<>();

        List<String> serialNumberList = new ArrayList<>();
        try {
            switch (suffix.toUpperCase()) {
                case "XLS":
                case "XLSX":
                    ExcelUtil<HDTradebillVo> util = new ExcelUtil<HDTradebillVo>(HDTradebillVo.class);
                    hdTradebillVoList = util.importExcel(new FileInputStream(dataFile));
                    break;
                case "CSV":
                    CsvReader reader = CsvUtil.getReader();
                    FileReader fileReader = new FileReader(dataFile.getAbsolutePath(), Charset.forName("GBK"));
                    hdTradebillVoList = reader.read(fileReader.readString(), HDTradebillVo.class);
                    break;
                default:
                    break;
            }
        } catch (Exception e){
            e.printStackTrace();
            throw new CustomException("文件数据不合规，请检查");
        }

        for (HDTradebillVo vo : hdTradebillVoList) {
            XhpcTradebillInternetCheckRecordDomain domain = new XhpcTradebillInternetCheckRecordDomain();
            domain.setPlatformInternetSerialNumber(vo.getOrderNo().trim());
            domain.setInternetSerialNumber(vo.getOrderNo().trim());
            domain.setSource("恒大");
            domain.setInternetName("恒大");
            domain.setInternetChargeStation(vo.getStationName());
            BigDecimal chargingDegree = vo.getChargeDegree() != null ? BigDecimal.valueOf(vo.getChargeDegree()) : BigDecimal.ZERO;
            domain.setInternetChargingDegree(chargingDegree);

            BigDecimal orderAmount = vo.getOrderTotalAmount() != null ? BigDecimal.valueOf(vo.getOrderTotalAmount()) : BigDecimal.ZERO;
            domain.setInternetOrderAmount(orderAmount);

            BigDecimal powerAmount = vo.getPowerAmount() != null ? BigDecimal.valueOf(vo.getPowerAmount()) : BigDecimal.ZERO;
            domain.setInternetPowerAmount(powerAmount);

            BigDecimal serverAmount = vo.getServerAmount() != null ? BigDecimal.valueOf(vo.getServerAmount()) : BigDecimal.ZERO;
            domain.setInternetServerAmount(serverAmount);
            domain.setInternetDiscountAmount(BigDecimal.ZERO);

            BigDecimal payAmount = vo.getOrderTotalAmount() != null ? BigDecimal.valueOf(vo.getOrderTotalAmount()) : BigDecimal.ZERO;
            domain.setInternetPayAmount(payAmount);

            serialNumberList.add(domain.getInternetSerialNumber());

//            getHistoryOrderInfo(domain);
            checkRecordDomainList.add(domain);
        }
        getHistoryOrderList(checkRecordDomainList, serialNumberList, "2", startTime, endTime, tenantId);

        return checkRecordDomainList;
    }


    /**
     * 获取小桔对账数据
     *
     * @param dataFile 对账单文件,格式为xlsx
     * @return 对账数据
     */
    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getXjInternetDataList(File dataFile, String startTime, String endTime, String tenantId) throws Exception {

        String suffix = dataFile.getName().substring(dataFile.getName().lastIndexOf(".") + 1);
        List<XhpcTradebillInternetCheckRecordDomain> checkRecordDomainList = new ArrayList<>();
        List<XJTradeBillVo> xjTradeBillVoList = new ArrayList<>();

        List<String> serialNumberList = new ArrayList<>();
        try {
            switch (suffix.toUpperCase()) {
                case "XLS":
                case "XLSX":
                    ExcelUtil<XJTradeBillVo> util = new ExcelUtil<XJTradeBillVo>(XJTradeBillVo.class);
                    xjTradeBillVoList = util.importExcel(new FileInputStream(dataFile));
                    break;
                case "CSV":
                    CsvReader reader = CsvUtil.getReader();
                    FileReader fileReader = new FileReader(dataFile.getAbsolutePath(), Charset.forName("GBK"));
                    xjTradeBillVoList = reader.read(fileReader.readString(), XJTradeBillVo.class);
                    break;
                default:
                    break;
            }
        } catch (Exception e){
            e.printStackTrace();
            throw new CustomException("文件数据不合规，请检查");
        }

        for (XJTradeBillVo vo : xjTradeBillVoList) {
            XhpcTradebillInternetCheckRecordDomain domain = new XhpcTradebillInternetCheckRecordDomain();
            domain.setPlatformInternetSerialNumber(vo.getOrderNo().trim());
            domain.setInternetSerialNumber(vo.getOrderNo().trim());
            domain.setSource("小桔");
            domain.setInternetName("小桔");
            domain.setInternetChargeStation(vo.getStationName());
            domain.setInternetStartSoc(vo.getStartSoc());
            domain.setInternetEndSoc(vo.getEndSoc());
            BigDecimal chargingDegree = vo.getChargingDegree() != null ? BigDecimal.valueOf(vo.getChargingDegree()) : BigDecimal.ZERO;
            domain.setInternetChargingDegree(chargingDegree);
            domain.setInternetChargingTime(vo.getChargingTime().toString());
            domain.setInternetStartTime(vo.getChargingStartTime());
            domain.setInternetEndTime(vo.getChargingEndTime());

            BigDecimal orderAmount = vo.getBillAmount() != null ? BigDecimal.valueOf(vo.getBillAmount()) : BigDecimal.ZERO;
            domain.setInternetOrderAmount(orderAmount);

            BigDecimal powerAmount = vo.getOrderPowerAmount() != null ? BigDecimal.valueOf(vo.getOrderPowerAmount()) : BigDecimal.ZERO;
            domain.setInternetPowerAmount(powerAmount);

            BigDecimal serverAmount = vo.getOrderServerAmount() != null ? BigDecimal.valueOf(vo.getOrderServerAmount()) : BigDecimal.ZERO;
            domain.setInternetServerAmount(serverAmount);
            domain.setInternetDiscountAmount(BigDecimal.ZERO);

            BigDecimal payAmount = vo.getOrderTotalAmount() != null ? BigDecimal.valueOf(vo.getOrderTotalAmount()) : BigDecimal.ZERO;
            domain.setInternetPayAmount(payAmount);

            serialNumberList.add(domain.getInternetSerialNumber());
//            getHistoryOrderInfo(domain);
//
            checkRecordDomainList.add(domain);
        }
        getHistoryOrderList(checkRecordDomainList, serialNumberList, "4", startTime, endTime, tenantId);
        return checkRecordDomainList;
    }


    /**
     * 获取新电途对账数据
     *
     * @param dataFile 对账单文件,格式为xlsx
     * @return 对账数据
     */
    @Override
    public void getXDTInternetDataList(HttpServletRequest request, HttpServletResponse response, File dataFile, String startTime, String endTime, String tenantId) throws Exception {

        String suffix = dataFile.getName().substring(dataFile.getName().lastIndexOf(".") + 1);
        XhpcTradebillUploadRecordDomain xhpcTradebillUploadRecordDomain = new XhpcTradebillUploadRecordDomain();
        List<XDTTradebillVo> xdtTradebillVoList = new ArrayList<>();

        List<String> serialNumberList = new ArrayList<>();
        try {
            switch (suffix.toUpperCase()) {
                case "XLS":
                case "XLSX":
                    ExcelUtil<XDTTradebillVo> util = new ExcelUtil<XDTTradebillVo>(XDTTradebillVo.class);
                    xdtTradebillVoList = util.importExcel(new FileInputStream(dataFile));
                    break;
                case "CSV":
                    CsvReader reader = CsvUtil.getReader();
                    FileReader fileReader = new FileReader(dataFile.getAbsolutePath(), Charset.forName("GBK"));
                    xdtTradebillVoList = reader.read(fileReader.readString(), XDTTradebillVo.class);
                    break;
                default:
                    break;
            }
        } catch (Exception e){
           e.printStackTrace();
            throw new CustomException("文件数据不合规，请检查");
        }

  //    String path = "/www/wwwroot/scxhua.cn/dist/moban/xindiantuzuizhangdan.xlsx";
 //       String path = "/www/wwwroot/scxhua.cn/dist/moban/xindiantuzuizhangdan.xlsx";
        String path ="H:\\home\\xindiantuzuizhangdan.xlsx";

        //新电途--总电费
        BigDecimal totalPowerAmount = new BigDecimal(0);
        //新电途--总服务费
        BigDecimal totalServerAmount = new BigDecimal(0);
        //新电途--总电量
        BigDecimal totalChargingDegree = new BigDecimal(0);
        //新电途--总流里方结算平台金额
        BigDecimal totalPayAmount = new BigDecimal(0);
        //新电途--总订单号
        List<String> totalOrderNo = new ArrayList<>();
        for (XDTTradebillVo vo : xdtTradebillVoList) {
            if(vo.getPowerAmount()!=null){
                totalPowerAmount =totalPowerAmount.add(BigDecimal.valueOf(vo.getPowerAmount()));
            }
            if(vo.getServerAmount()!=null){
                totalServerAmount =totalServerAmount.add(BigDecimal.valueOf(vo.getServerAmount()));
            }
            if(vo.getChargingDegree()!=null){
                totalChargingDegree =totalChargingDegree.add(BigDecimal.valueOf(vo.getChargingDegree()));
            }
            if(vo.getPayAmount()!=null){
                totalPayAmount =totalPayAmount.add(BigDecimal.valueOf(vo.getPayAmount()));
            }
            totalOrderNo.add(vo.getOrderNo().trim());
        }
        //获取平台新电途订单
        List<Map<String, Object>> listPage = historyOrderMapper.getListPage(totalOrderNo, 3);
        //平台--总电费
        BigDecimal totalPlatformPowerAmount = new BigDecimal(0);
        //平台--总服务费
        BigDecimal totalPlatformServerAmount = new BigDecimal(0);
        //平台--总电量
        BigDecimal totalPlatformChargingDegree = new BigDecimal(0);
        //平台--流里方总金额抽成
        BigDecimal totalPlatformInternetCommission = new BigDecimal(0);
        //平台--流里方服务费抽成
        BigDecimal totalPlatformInternetSvcCommission = new BigDecimal(0);
        //平台--流里方电量抽成
        BigDecimal totalPlatformInternetDegreeCommissione = new BigDecimal(0);
        //平台--实收电费
        BigDecimal totalPlatformActPowerPrice = new BigDecimal(0);
        //平台--实收服务费
        BigDecimal totalPlatformActServicePrice = new BigDecimal(0);
        //新电途--总流里方结算平台金额
        BigDecimal totalPlatformPayAmount = new BigDecimal(0);
        for (Map<String, Object> vo : listPage) {
            totalPlatformPowerAmount =totalPlatformPowerAmount.add(new BigDecimal(vo.get("powerPriceTotal").toString()));
            totalPlatformServerAmount =totalPlatformServerAmount.add(new BigDecimal(vo.get("servicePriceTotal").toString()));
            totalPlatformChargingDegree =totalPlatformChargingDegree.add(new BigDecimal(vo.get("chargingDegree").toString()));
            totalPlatformInternetCommission =totalPlatformInternetCommission.add(new BigDecimal(vo.get("internetCommission").toString()));
            totalPlatformInternetSvcCommission =totalPlatformInternetSvcCommission.add(new BigDecimal(vo.get("internetSvcCommission").toString()));
            totalPlatformInternetDegreeCommissione =totalPlatformInternetDegreeCommissione.add(new BigDecimal(vo.get("internetDegreeCommission").toString()));
            totalPlatformActPowerPrice =totalPlatformActPowerPrice.add(new BigDecimal(vo.get("actPowerPrice").toString()));
            totalPlatformActServicePrice =totalPlatformActServicePrice.add(new BigDecimal(vo.get("actServicePrice").toString()));
            totalPlatformPayAmount =totalPlatformPayAmount.add(new BigDecimal(vo.get("actPrice").toString()));
        }

        List<Map<String,Object>> mapList =new ArrayList<>();
        Map<String,Object> objectMap =new HashMap<>();
        objectMap.put("PowerAmount",totalPlatformPowerAmount);
        objectMap.put("ServerAmount",totalPlatformServerAmount);
        objectMap.put("totalAmount",totalPlatformPowerAmount.add(totalPlatformServerAmount));
        objectMap.put("ChargingDegree",totalPlatformChargingDegree);
        objectMap.put("InternetCommission",totalPlatformInternetCommission);
        objectMap.put("InternetSvcCommission",totalPlatformInternetSvcCommission);
        objectMap.put("InternetDegreeCommissione",totalPlatformInternetDegreeCommissione);
        objectMap.put("totalInternetAmount",totalPlatformInternetCommission.add(totalPlatformInternetSvcCommission.add(totalPlatformInternetDegreeCommissione)));
        objectMap.put("ActPowerPrice",totalPlatformActPowerPrice);
        objectMap.put("ActServicePrice",totalPlatformActServicePrice);
        objectMap.put("totalInternetSettlementAmount",totalPlatformActServicePrice.add(totalPlatformActPowerPrice));
        objectMap.put("totalPowerAmount",totalPowerAmount);
        objectMap.put("totalServerAmount",totalServerAmount);
        objectMap.put("InternetSettlementAmount",totalPowerAmount.add(totalServerAmount));
        objectMap.put("totalChargingDegree",totalChargingDegree);
        objectMap.put("totalPayAmount",totalPayAmount);
        mapList.add(objectMap);


        List<ExcelExp> list =new ArrayList<>();

        String suzu0[]={"PowerAmount","ServerAmount","totalAmount","ChargingDegree","InternetCommission","InternetSvcCommission","InternetDegreeCommissione","totalInternetAmount","ActPowerPrice","ActServicePrice","totalInternetSettlementAmount","totalPowerAmount","totalServerAmount","InternetSettlementAmount","totalChargingDegree","totalPayAmount"};
        ExcelExp excelExp0 = new ExcelExp("翔桦与新电途对账统计表", suzu0, mapList, "翔桦与新电途对账统计表");

        String suzu1[]={"orderNo","stationName","city","exceptionType","transactionType","paymentType","settlementType","settlementTime","orderAmount","orderUserAmount","offlineAmount","userAmount","badDebt","placeholderBadDebt","platformBadDebt","businessMoney","platformMoney","platformMoneyDifference","platformIncomeMoney","platformProfitSharingMoney","platformServerMoney","payAmount","chargingDegree","powerAmount","serverAmount","surchargeAmount","settlementRules","stationOrder","notes","orderCreateTime","orderType"};
        ExcelExp excelExp1 = new ExcelExp("新电途对账单", suzu1, xdtTradebillVoList, "新电途对账单",3);

        String suzu2[]={"serialNumber","internetSerialNumber","chargingStationName","pileSerialNumber","terminalName","power","startSoc","endSoc","powerPriceTotal","servicePriceTotal","totalPrice","activityPowerPriceTotal","activityServicePriceTotal","activityTotalPrice","promotionDiscount","actPrice","internetCommission","internetSvcCommission","internetDegreeCommission","platformCommission","platformSvcCommisssion","operationCommission","operationSvcCommission","actPowerPrice","actServicePrice","actSumPrice","totalPrice","actPrice","chargingTime","chargingDegree","startTime","endTime","chargingModeName"};
        ExcelExp excelExp2 = new ExcelExp("四川翔桦科技有限公司平台对账单", suzu2, listPage, "四川翔桦科技有限公司平台对账单");

        list.add(excelExp0);
        list.add(excelExp1);
        list.add(excelExp2);

        XSSFWorkbook workbook = ExcelUtilYu.importExcelByOriginYu(response, request, "四川翔桦科技有限公司-新电途与平台对账单.xlsx", path, list, 0, "xlsx", "四川翔桦科技有限公司-新电途与平台对账单", 2);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();

        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

        String bucketName = "xhpc-bucket1";
        String objectName = "exampledir/四川翔桦科技有限公司-新电途与平台对账单_"+ com.xhpc.common.util.DateUtil.date2String(new Date(), com.xhpc.common.util.DateUtil.DEFAULT_DATE_FORMAT) +".xlsx";
        OSS ossClient = new OSSClientBuilder().build(endpoint, ossProperties.getAccessKey(), ossProperties.getSecretKey());
        String url ="https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/"+objectName;
        try{
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(byteArray));
            System.out.println("putObjectResult="+putObjectResult.toString());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        xhpcTradebillUploadRecordDomain.setSource("平台上传");
        xhpcTradebillUploadRecordDomain.setFileName("新电途对账单");
        xhpcTradebillUploadRecordDomain.setDelFlag(0);
        xhpcTradebillUploadRecordDomain.setUrl(url);
        xhpcTradebillUploadRecordDomain.setType(7);
        xhpcTradebillUploadRecordDomain.setStatus(0);
        xhpcTradebillUploadRecordDomain.setSuccessCount(0);
        xhpcTradebillUploadRecordDomain.setFailCount(0);
        xhpcTradebillUploadRecordDomain.setUncheckCount(0);
        xhpcTradebillUploadRecordDomain.setCheckedCount(0);
        xhpcTradebillUploadRecordDomain.setPlatformPower(totalPlatformPowerAmount);
        xhpcTradebillUploadRecordDomain.setPlatformServer(totalPlatformServerAmount);
        xhpcTradebillUploadRecordDomain.setPlatformAmout(totalPlatformPowerAmount.add(totalPlatformServerAmount));
        xhpcTradebillUploadRecordDomain.setPlatformDegree(totalPlatformChargingDegree);
        xhpcTradebillUploadRecordDomain.setPlatformInternetCommission(totalPlatformInternetCommission);
        xhpcTradebillUploadRecordDomain.setPlatformInternetSvcCommission(totalPlatformInternetSvcCommission);
        xhpcTradebillUploadRecordDomain.setPlatformInternetDegreeCommission(totalPlatformInternetDegreeCommissione);
        xhpcTradebillUploadRecordDomain.setPlatformInternetAmout(totalPlatformInternetCommission.add(totalPlatformInternetSvcCommission.add(totalPlatformInternetDegreeCommissione)));
        xhpcTradebillUploadRecordDomain.setPlatformActPower(totalPlatformActPowerPrice);
        xhpcTradebillUploadRecordDomain.setPlatformActServicePowe(totalPlatformActServicePrice);
        xhpcTradebillUploadRecordDomain.setPlatformInternetSettlementAmout(totalPlatformActServicePrice.add(totalPlatformActPowerPrice));
        xhpcTradebillUploadRecordDomain.setInternetPower(totalPowerAmount);
        xhpcTradebillUploadRecordDomain.setInternetServer(totalServerAmount);
        xhpcTradebillUploadRecordDomain.setInternetAmout(totalPowerAmount.add(totalServerAmount));
        xhpcTradebillUploadRecordDomain.setInternetDegree(totalChargingDegree);
        xhpcTradebillUploadRecordDomain.setInternetSettlementAmout(totalPayAmount);
        LoginUser logUser = logUserUtils.getLogUser(request);
        xhpcTradebillUploadRecordDomain.setUserId(logUser.getUserid());
        xhpcTradebillUploadRecordDomain.setReconciliationTime(startTime);
        uploadRecordMapper.insertSelective(xhpcTradebillUploadRecordDomain);

    }

    /**
     * 获取快电对账数据
     *
     * @param dataFile 对账单文件,格式为xlsx
     * @return 对账数据
     */
    @Override
    public List<XhpcTradebillInternetCheckRecordDomain> getKDInternetDataList(File dataFile, String startTime, String endTime, String tenantId) throws Exception {

        String suffix = dataFile.getName().substring(dataFile.getName().lastIndexOf(".") + 1);
        List<XhpcTradebillInternetCheckRecordDomain> checkRecordDomainList = new ArrayList<>();
        List<KDTradebillVo> kdTradebillVoList = new ArrayList<>();
        List<Map<String, Object>> dataList = new ArrayList<>();

        List<String> serialNumberList = new ArrayList<>();
        try {
            switch (suffix.toUpperCase()) {
                case "XLS":
                case "XLSX":
                    ExcelUtil<KDTradebillVo> util = new ExcelUtil<KDTradebillVo>(KDTradebillVo.class);
                    kdTradebillVoList = util.importExcel(new FileInputStream(dataFile), 1);

                    break;
                default:
                    break;
            }
        } catch (Exception e){
            e.printStackTrace();
            throw new CustomException("文件数据不合规，请检查");
        }

        for (KDTradebillVo vo : kdTradebillVoList) {
            if (vo.getOrderNo().equals("交易订单号") || StrUtil.hasBlank(vo.getOrderNo())) {
                continue;
            }
            XhpcTradebillInternetCheckRecordDomain domain = new XhpcTradebillInternetCheckRecordDomain();
            domain.setSource("快电");
            domain.setInternetName("快电");
            domain.setInternetSerialNumber(vo.getOrderNo());
            domain.setPlatformInternetSerialNumber(vo.getOrderNo());

            Date startTime1 = StrUtil.hasBlank(vo.getStartTime()) ? null : DateUtil.parse(vo.getStartTime());
            domain.setInternetStartTime(startTime1);

            Date endTime1 = StrUtil.hasBlank(vo.getEndTime()) ? null : DateUtil.parse(vo.getEndTime());
            domain.setInternetEndTime(endTime1);

            domain.setInternetChargeStation(vo.getStationName());

            BigDecimal chargingDegree = vo.getChargingDegree() == null ? BigDecimal.ZERO : BigDecimal.valueOf(vo.getChargingDegree());
            domain.setInternetChargingDegree(chargingDegree);

            BigDecimal powerAmount = vo.getTotalPowerAmount() == null ? BigDecimal.ZERO : BigDecimal.valueOf(vo.getTotalPowerAmount());
            domain.setInternetPowerAmount(powerAmount);

            BigDecimal serverAmount = vo.getServerAmount() == null ? BigDecimal.ZERO : BigDecimal.valueOf(vo.getServerAmount());
            domain.setInternetServerAmount(serverAmount);

            domain.setInternetDiscountAmount(BigDecimal.ZERO);

            String orderAmount = vo.getOrderAmount() == null ? "0" : vo.getOrderAmount().toString();
            domain.setInternetOrderAmount(new BigDecimal(orderAmount));
            domain.setInternetPayAmount(domain.getInternetOrderAmount());

            serialNumberList.add(domain.getInternetSerialNumber());
            checkRecordDomainList.add(domain);
        }
        getHistoryOrderList(checkRecordDomainList, serialNumberList, "1", startTime, endTime, tenantId);
        return checkRecordDomainList;
    }

    /**
     * 导出对账单
     *
     * @param response 返回体
     * @param params   查询参数
     * @throws Exception 异常
     */
    @Override
    public void export(HttpServletResponse response, Map<String, Object> params) throws Exception {

        List<Map<String, Object>> list = internetCheckRecordMapper.selectByParams(params);

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        writer.addHeaderAlias("internet_name", "流量方名称");
        writer.addHeaderAlias("user_id", "用户账号");

        writer.addHeaderAlias("platform_order_number", "平台-订单编号");
        writer.addHeaderAlias("platform_charge_station", "平台-充电场站名称");
        writer.addHeaderAlias("platform_start_soc", "平台-开始SOC");
        writer.addHeaderAlias("platform_end_soc", "平台-结束SOC");
        writer.addHeaderAlias("platform_charging_degree", "平台-充电电量");
        writer.addHeaderAlias("platform_charging_time", "平台-充电时长");
        writer.addHeaderAlias("platform_start_time", "平台-开始充电时间");
        writer.addHeaderAlias("platform_end_time", "平台-结束充电时间");
        writer.addHeaderAlias("platform_order_amount", "平台-订单总金额");
        writer.addHeaderAlias("platform_power_amount", "平台-电费金额");
        writer.addHeaderAlias("platform_server_amount", "平台-服务费金额");
        writer.addHeaderAlias("platform_discount_amount", "平台-折扣费用");
        writer.addHeaderAlias("platform_pay_amount", "平台-实际支付金额");

        writer.addHeaderAlias("internet_order_number", "流量方-订单编号");
        writer.addHeaderAlias("internet_charge_station", "流量方-充电场站名称");
        writer.addHeaderAlias("internet_start_soc", "流量方-开始SOC");
        writer.addHeaderAlias("internet_end_soc", "流量方-结束SOC");
        writer.addHeaderAlias("internet_charging_degree", "流量方-充电电量");
        writer.addHeaderAlias("internet_charging_time", "流量方-充电时长");
        writer.addHeaderAlias("internet_start_time", "流量方-开始充电时间");
        writer.addHeaderAlias("internet_end_time", "流量方-结束充电时间");
        writer.addHeaderAlias("internet_order_amount", "流量方-订单总金额");
        writer.addHeaderAlias("internet_power_amount", "流量方-电费金额");
        writer.addHeaderAlias("internet_server_amount", "流量方-服务费金额");
        writer.addHeaderAlias("internet_discount_amount", "流量方-折扣费用");
        writer.addHeaderAlias("internet_pay_amount", "流量方-实际支付金额");

        writer.addHeaderAlias("status", "对账状态（0-待对账，1-对账错误，2-对账正确）");
        writer.addHeaderAlias("remark", "备注");

        writer.setOnlyAlias(true);
        writer.write(list, true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @Override
    public List<Map<String, Object>> getListPage(List<String> totalOrderNos, Integer type) {
        return historyOrderMapper.getListPage(totalOrderNos,type);
    }

    @Override
    public List<XhpcTradebillUploadRecordDomain> getXhpcTradebillUploadRecordcheckPage(Map<String, Object> params) {
        return uploadRecordMapper.getXhpcTradebillUploadRecordcheckPage(params);
    }


    private void getHistoryOrderInfo(XhpcTradebillInternetCheckRecordDomain domain) {

        XhpcHistoryOrderDomain orderDomain = historyOrderMapper.findOneByInternetSerialNumber(domain.getInternetSerialNumber());
        if (orderDomain != null) {
            domain.setHistoryOrderNo(orderDomain.getHistoryOrderId());
            domain.setPlatformInternetSerialNumber(orderDomain.getInternetSerialNumber());
            domain.setPlatformSerialNumber(orderDomain.getSerialNumber());
            domain.setPlatformChargeStation(orderDomain.getChargingStationName());
            domain.setPlatformStartSoc(orderDomain.getStartSoc());
            domain.setPlatformEndSoc(orderDomain.getEndSoc());
            BigDecimal chargingDegree = orderDomain.getChargingDegree() != null ?
                    BigDecimal.valueOf(orderDomain.getChargingDegree()) : BigDecimal.ZERO;
            domain.setPlatformChargingDegree(chargingDegree);
            domain.setPlatformChargingTime(orderDomain.getChargingTime());
            domain.setPlatformStartTime(orderDomain.getStartTime());
            domain.setPlatformEndTime(orderDomain.getEndTime());
            domain.setPlatformOrderAmount(orderDomain.getTotalPrice());
            domain.setPlatformPowerAmount(orderDomain.getPowerPriceTotal());
            domain.setPlatformServerAmount(orderDomain.getServicePriceTotal());
            domain.setPlatformDiscountAmount(orderDomain.getPromotionDiscount());
            domain.setPlatformPayAmount(orderDomain.getActPrice());
        }
        checkoutOrderResult(domain);
    }


    private List<XhpcTradebillInternetCheckRecordDomain> getHistoryOrderList(List<XhpcTradebillInternetCheckRecordDomain> domainList,
                                                                             List<String> serialNumberList, String chargingMode,
                                                                             String startTime, String endTime, String tenantId) {

        List<XhpcHistoryOrderDomain> orderDomainList = historyOrderMapper.findListByTimeBetween(startTime, endTime, chargingMode, tenantId);
        Map<String, XhpcHistoryOrderDomain> orderDomainMap = new HashMap<>();
//        for (XhpcHistoryOrderDomain orderDomain : orderDomainList) {
//            orderDomainMap.put(orderDomain.getInternetSerialNumber(), orderDomain);
//        }
        orderDomainList.stream().collect(Collectors.toMap(XhpcHistoryOrderDomain:: getInternetSerialNumber, d->d));

        for (XhpcTradebillInternetCheckRecordDomain domain : domainList) {
            XhpcHistoryOrderDomain orderDomain = orderDomainMap.get(domain.getInternetSerialNumber());
            if (orderDomain != null) {
                domain.setHistoryOrderNo(orderDomain.getHistoryOrderId());
                domain.setPlatformInternetSerialNumber(orderDomain.getInternetSerialNumber());
                domain.setPlatformSerialNumber(orderDomain.getSerialNumber());
                domain.setPlatformChargeStation(orderDomain.getChargingStationName());
                domain.setPlatformStartSoc(orderDomain.getStartSoc());
                domain.setPlatformEndSoc(orderDomain.getEndSoc());
                BigDecimal chargingDegree = orderDomain.getChargingDegree() != null ?
                        BigDecimal.valueOf(orderDomain.getChargingDegree()) : BigDecimal.ZERO;
                domain.setPlatformChargingDegree(chargingDegree);
                domain.setPlatformChargingTime(orderDomain.getChargingTime());
                domain.setPlatformStartTime(orderDomain.getStartTime());
                domain.setPlatformEndTime(orderDomain.getEndTime());
                domain.setPlatformOrderAmount(orderDomain.getTotalPrice());
                domain.setPlatformPowerAmount(orderDomain.getPowerPriceTotal());
                domain.setPlatformServerAmount(orderDomain.getServicePriceTotal());
                domain.setPlatformDiscountAmount(orderDomain.getPromotionDiscount());
                domain.setPlatformPayAmount(orderDomain.getActPrice());
            }
            orderDomainMap.remove(domain.getInternetSerialNumber());
            checkoutOrderResult(domain);
        }
        
        if (orderDomainMap.size() > 0){
            for(XhpcHistoryOrderDomain orderDomain: orderDomainMap.values()){
                XhpcTradebillInternetCheckRecordDomain domain = new XhpcTradebillInternetCheckRecordDomain();
                domain.setHistoryOrderNo(orderDomain.getHistoryOrderId());
                domain.setPlatformInternetSerialNumber(orderDomain.getInternetSerialNumber());
                domain.setPlatformSerialNumber(orderDomain.getSerialNumber());
                domain.setPlatformChargeStation(orderDomain.getChargingStationName());
                domain.setPlatformStartSoc(orderDomain.getStartSoc());
                domain.setPlatformEndSoc(orderDomain.getEndSoc());
                BigDecimal chargingDegree = orderDomain.getChargingDegree() != null ?
                        BigDecimal.valueOf(orderDomain.getChargingDegree()) : BigDecimal.ZERO;
                domain.setPlatformChargingDegree(chargingDegree);
                domain.setPlatformChargingTime(orderDomain.getChargingTime());
                domain.setPlatformStartTime(orderDomain.getStartTime());
                domain.setPlatformEndTime(orderDomain.getEndTime());
                domain.setPlatformOrderAmount(orderDomain.getTotalPrice());
                domain.setPlatformPowerAmount(orderDomain.getPowerPriceTotal());
                domain.setPlatformServerAmount(orderDomain.getServicePriceTotal());
                domain.setPlatformDiscountAmount(orderDomain.getPromotionDiscount());
                domain.setPlatformPayAmount(orderDomain.getActPrice());
                checkoutOrderResult(domain);
                domainList.add(domain);
            }
        }

        domainList.sort(Comparator.comparing(XhpcTradebillInternetCheckRecordDomain::getStatus));
        return domainList;
    }

    private void checkoutOrderResult(XhpcTradebillInternetCheckRecordDomain domain) {

        int checkoutStatus = 0;
        // 流量方的订单金额大于本平台的历史订单的订单金额，就可以判断成功
        if (domain.getPlatformOrderAmount() != null && domain.getInternetOrderAmount() != null && domain.getPlatformOrderAmount().compareTo(domain.getInternetOrderAmount()) == 0
                && domain.getPlatformPowerAmount() != null && domain.getInternetPowerAmount() != null && domain.getPlatformPowerAmount().compareTo(domain.getInternetPowerAmount()) == 0
                && domain.getPlatformServerAmount() != null && domain.getInternetServerAmount() != null && domain.getPlatformServerAmount().compareTo(domain.getInternetServerAmount()) == 0
                && domain.getPlatformChargingDegree() != null && domain.getInternetChargingDegree() != null && domain.getPlatformChargingDegree().compareTo(domain.getInternetChargingDegree()) == 0) {
            checkoutStatus = 2;
        }
        domain.setStatus(checkoutStatus);
    }


}
