package com.hzya.frame.cbs8.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.cbs8.dto.req.*;
import com.hzya.frame.cbs8.service.ICbs8ExtService;
import com.hzya.frame.cbs8.util.CBSUtil;
import com.hzya.frame.cbs8.util.CbsAccessToken;
import com.hzya.frame.seeyon.cbs8.entity.PaymentEntity;
import com.hzya.frame.stringutil.StringUtil;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * @Description
 * @Author xiangerlin
 * @Date 2024/6/7 14:20
 **/

@Service(value = "cbs8Ext")
public class Cbs8ExtServiceImpl implements ICbs8ExtService {

    Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 支付经办
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity payApply(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            PaymentEntity paymentEntity = JSONObject.parseObject(bodys,PaymentEntity.class);
            if (null != paymentEntity){
                PayRequestDTO payRequestDTO = new PayRequestDTO();
                String ferenceNum = Convert.toStr(paymentEntity.getReferenceNumNew(),paymentEntity.getReferenceNum());
                payRequestDTO.setReferenceNum(ferenceNum);
                payRequestDTO.setBusType(paymentEntity.getBusType());
                payRequestDTO.setAmount(paymentEntity.getAmount());
                payRequestDTO.setCurrency(paymentEntity.getCurrency());
                payRequestDTO.setPayAccount(StringUtil.replaceBlank(paymentEntity.getPayAccount()));
                payRequestDTO.setRevAccount(StringUtil.replaceBlank(paymentEntity.getRevAccount()));
                payRequestDTO.setRevAccountName(StringUtil.replaceBlank(paymentEntity.getRevAccountName()));
                payRequestDTO.setRevBankType(StringUtil.replaceBlank((paymentEntity.getRevBankType())));
                payRequestDTO.setRevBankName(StringUtil.replaceBlank(paymentEntity.getRevBankName()));
                payRequestDTO.setCnapsCode(StringUtil.replaceBlank((paymentEntity.getCnapsCode())));
                payRequestDTO.setPurpose(paymentEntity.getPurpose());
                payRequestDTO.setErpExtend1(paymentEntity.getPayType());
                //集中支付模式
                if (CBSUtil.CENTRALIZED_PAYMENT_TYPE.equals(payRequestDTO.getBusType())){
                    payRequestDTO.setBusiStep("1");
                    payRequestDTO.setApplyUnitCode(paymentEntity.getPayCompanyCode());
                    payRequestDTO.setPayAccount(null);
                }
                List<PayRequestDTO> list = Arrays.asList(payRequestDTO);
                String requestData = JSONObject.toJSONString(list);
                //加密 签名
                encrypAndsign(entity,requestData);
            }
        }
        return entity;
    }

    /**
     * 代发代扣 支付申请
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity agentPayApply(SysExtensionApiEntity entity) {
        String boyds = entity.getBodys();
        if (StrUtil.isNotEmpty(boyds)){
            AgentPayRequestDTO agentPayRequest = JSONObject.parseObject(boyds,AgentPayRequestDTO.class);
            String requestData = JSONObject.toJSONString(agentPayRequest);
            //加密签名
            encrypAndsign(entity, requestData);
        }
        return entity;
    }

    /**
     * 交易结果查询
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity payResult(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            PayResultRequestDTO payResultRequest = JSONObject.parseObject(bodys,PayResultRequestDTO.class);
            if (null != payResultRequest && StrUtil.isNotEmpty(payResultRequest.getReferenceNum())){
                String requestData = JSONObject.toJSONString(payResultRequest);
                //加密 签名
               encrypAndsign(entity,requestData);
            }else {
                throw new BaseSystemException("业务参考号不能为空！！！！");
            }
        }
        return entity;
    }

    /**
     * 交易明细查询
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity transactionDetailQuery(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            TransactionDetailReqDTO transactionDetailReqDTO = JSONObject.parseObject(bodys,TransactionDetailReqDTO.class);
            String requestData = JSONObject.toJSONString(transactionDetailReqDTO);
            ////加密签名
            encrypAndsign(entity, requestData);
        }
        return entity;
    }

    /**
     * 代发代扣
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity payApplyAgent(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            AgentPayRequestDTO agentPayRequest = JSONObject.parseObject(bodys,AgentPayRequestDTO.class);
            String requestData = JSONObject.toJSONString(agentPayRequest);
            ////加密签名
            encrypAndsign(entity, requestData);
        }
        return entity;
    }



    /**
     * 代发代扣结果查询
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity payApplyAgentResult(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            AgentPayResultRequestDTO agentPayResultRequestDTO = JSONObject.parseObject(bodys,AgentPayResultRequestDTO.class);
            String requestData = JSONObject.toJSONString(agentPayResultRequestDTO);
            encrypAndsign(entity,requestData);
        }
        return entity;
    }

    /**
     * 电子回单查询
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity elecQuery(SysExtensionApiEntity entity) {
        String bodys = entity.getBodys();
        if (StrUtil.isNotEmpty(bodys)){
            ElecRequestDTO elecRequestDTO = JSONObject.parseObject(bodys,ElecRequestDTO.class);
            String requestData = JSONObject.toJSONString(elecRequestDTO);
            //加密 签名
            encrypAndsign(entity,requestData);
        }
        return entity;
    }


    /**
     * 请求头
     * @param sign
     * @param timestamp
     * @return
     */
    private Map<String,String> headersValueOf(String sign, long timestamp){
        Map<String,String> header = new HashMap();
        header.put(CBSUtil.SIGN_HEADER_NAME,sign);
        header.put(CBSUtil.TIMESTAMP_HEADER,Long.toString(timestamp));
        header.put(HTTP.CONTENT_TYPE,CBSUtil.TARGET_CONTENT_TYPE);
        header.put(CBSUtil.AUTHORIZATION,CBSUtil.BEARER+ CbsAccessToken.getToken());
        return header;
    }

    /**
     * 加密 签名
     * @param entity 接口转发参数对象
     * @param requestData 请求参数json字符串
     */
    private void encrypAndsign(SysExtensionApiEntity entity, String requestData) {
        //签名
        long timestamp = System.currentTimeMillis();
        logger.info("CBS请求参数明文:{}",requestData);
        String sign = CBSUtil.sign(requestData,timestamp);
        //加密
        byte[] encryptedData = CBSUtil.encrypt(requestData);
        Map<String,String> header = headersValueOf(sign,timestamp);
        entity.setByteBodys(encryptedData);
        entity.setHeaders(header);
    }
}
