package com.xhpc.activity.service.impl;

import com.aliyun.oss.OSSClient;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.activity.config.AliOSSProperties;
import com.xhpc.activity.domain.XhpcTradebillInternetCheckRecordDomain;
import com.xhpc.activity.domain.XhpcTradebillPaymentCheckRecordDomain;
import com.xhpc.activity.domain.XhpcTradebillUploadRecordDomain;
import com.xhpc.activity.mapper.XhpcTradebillUploadRecordMapper;
import com.xhpc.activity.service.CommonService;
import com.xhpc.activity.service.InternetBillService;
import com.xhpc.activity.service.PaymentBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    XhpcTradebillUploadRecordMapper uploadRecordMapper;

    @Resource
    PaymentBillService paymentBillService;

    @Resource
    InternetBillService internetBillService;

    @Resource
    AliOSSProperties ossProperties;

    @Override
    public XhpcTradebillUploadRecordDomain ossUpload(HttpServletRequest request, HttpServletResponse response, XhpcTradebillUploadRecordDomain domain) throws Exception {

        Long userId = SecurityUtils.getUserId();
        domain.setCreateBy(userId);
        domain.setUpdateBy(userId);
        domain.setSource("上传");
        domain.setFileName(domain.getFileName());
        domain.setStatus(0);
        domain.setDelFlag(0);
        domain.setSuccessCount(0);
        domain.setFailCount(0);
        domain.setUncheckCount(0);
        domain.setCheckedCount(0);
       // uploadRecordMapper.insertSelective(domain);

        List<XhpcTradebillPaymentCheckRecordDomain> paymentCheckRecordDomainList = null;
        List<XhpcTradebillInternetCheckRecordDomain> recordDomainList = null;
        Map<String, Integer> totalMap = new HashMap<>();
        int insertCount = 0;
        domain.setStatus(2);
        try {
            switch (domain.getType()) {
                case 1:
                case 2:
                    // 微信支付
                    paymentCheckRecordDomainList = paymentBillService.getWechatDataList(domain.getUrl(), domain.getStartTime(), domain.getEndTime(), domain.getTenantId());
                    insertCount = paymentBillService.insertPaymentCheckList(domain, paymentCheckRecordDomainList);
                    totalMap = computePaymentRecord(paymentCheckRecordDomainList);
                    break;
                case 3:
                case 4:
                    // 支付宝支付
                    paymentCheckRecordDomainList = paymentBillService.getAliPayDataList(domain.getUrl(), domain.getStartTime(), domain.getEndTime(), domain.getTenantId());
                    insertCount = paymentBillService.insertPaymentCheckList(domain, paymentCheckRecordDomainList);
                    totalMap = computePaymentRecord(paymentCheckRecordDomainList);
                    break;
                case 5:
                    // 恒大
                    recordDomainList = internetBillService.getHdInternetDataList(domain.getUrl(), domain.getStartTime(), domain.getEndTime(), domain.getTenantId());
                    insertCount = internetBillService.insertInternetCheckList(domain, recordDomainList);
                    totalMap = computeInternetRecord(recordDomainList);
                    break;
                case 6:
                    // 小桔
                    recordDomainList = internetBillService.getXjInternetDataList(domain.getUrl(), domain.getStartTime(), domain.getEndTime(), domain.getTenantId());
                    insertCount = internetBillService.insertInternetCheckList(domain, recordDomainList);
                    totalMap = computeInternetRecord(recordDomainList);
                    break;
                case 7:
                    // 新电途
                    internetBillService.getXDTInternetDataList(request,response,domain.getUrl(), domain.getStartTime(), domain.getEndTime(), domain.getTenantId());
                   // insertCount = internetBillService.insertInternetCheckList(domain, recordDomainList);
                   // totalMap = computeInternetRecord(recordDomainList);
                    break;
                case 8:
                    // 快电
                    recordDomainList = internetBillService.getKDInternetDataList(domain.getUrl(), domain.getStartTime(), domain.getEndTime(), domain.getTenantId());
                    insertCount = internetBillService.insertInternetCheckList(domain, recordDomainList);
                    totalMap = computeInternetRecord(recordDomainList);
                    break;
                default:
                    domain.setStatus(1);
                    totalMap.put("successCount", 0);
                    totalMap.put("failCount", 0);
                    totalMap.put("checkCount", 0);
                    totalMap.put("uncheckCount", 0);
                    break;
            }
            domain.setStatus(1);
            domain.setSuccessCount(totalMap.get("successCount"));
            domain.setFailCount(totalMap.get("failCount"));
            domain.setCheckedCount(totalMap.get("checkCount"));
            domain.setUncheckCount(totalMap.get("uncheckCount"));
            //uploadRecordMapper.updateByPrimaryKey(domain);
            return domain;
        } catch (Exception exception){
            exception.printStackTrace();
            throw new CustomException("内部错误");
        }

    }


    @Override
    public XhpcTradebillUploadRecordDomain fileUpload(HttpServletRequest request, HttpServletResponse response,String tenantId, MultipartFile file, int type, String startTime, String endTime) throws Exception {

        XhpcTradebillUploadRecordDomain domain = new XhpcTradebillUploadRecordDomain();
        // 创建OSSClient实例
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File dataFile = File.createTempFile("temp_", suffix);

        try{
            file.transferTo(dataFile);

            String ossPath = "bill/" + file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) + "_" + System.currentTimeMillis() + "." + suffix;
            OSSClient ossClient = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessKey(), ossProperties.getSecretKey());
            // 上传文件流
            ossClient.putObject(ossProperties.getBucketName(), ossPath, dataFile);
            ossClient.shutdown();

            domain.setFileName(file.getOriginalFilename());
            domain.setUrl(ossProperties.getDomain() + ossPath);
            domain.setStartTime(startTime);
            domain.setEndTime(endTime);
            domain.setType(type);
            domain.setTenantId(tenantId);
            return ossUpload(request,response,domain);
        } catch (Exception exception){
            throw new CustomException("服务错误");
        }
    }

    @Override
    public List<XhpcTradebillUploadRecordDomain> getFilePage(Map<String, Object> params) {

        return uploadRecordMapper.selectByType(params);
    }


    private Map<String, Integer> computePaymentRecord(List<XhpcTradebillPaymentCheckRecordDomain> domainList) {

        Integer successCount = 0;
        Integer failCount = 0;
        Integer checkCount = 0;
        Integer uncheckCount = 0;
        Map<String, Integer> result = new HashMap<>();
        for (XhpcTradebillPaymentCheckRecordDomain domain : domainList) {
            if (domain.getStatus() == 2) {
                successCount++;
                checkCount++;
            } else if (domain.getStatus() == 1 || domain.getStatus() == 0) {
                failCount++;
                checkCount++;
            } else {
                uncheckCount++;
            }
        }
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("checkCount", checkCount);
        result.put("uncheckCount", uncheckCount);
        return result;
    }


    private Map<String, Integer> computeInternetRecord(List<XhpcTradebillInternetCheckRecordDomain> domainList) {

        Integer successCount = 0;
        Integer failCount = 0;
        Integer checkCount = 0;
        Integer uncheckCount = 0;
        Map<String, Integer> result = new HashMap<>();
        for (XhpcTradebillInternetCheckRecordDomain domain : domainList) {
            if (domain.getStatus() == 2) {
                successCount++;
                checkCount++;
            } else if (domain.getStatus() == 1 || domain.getStatus() == 0) {
                failCount++;
                checkCount++;
            } else {
                uncheckCount++;
            }
        }
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("checkCount", checkCount);
        result.put("uncheckCount", uncheckCount);
        return result;
    }

}
