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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hzya.frame.cbs8.dto.req.*;
import com.hzya.frame.cbs8.dto.res.*;
import com.hzya.frame.cbs8.service.ICbs8Service;
import com.hzya.frame.cbs8.util.CBSUtil;
import com.hzya.frame.seeyon.cbs8.entity.PaymentEntity;
import com.hzya.frame.seeyon.cbs8.service.IPaymentService;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * @Description cbs8接口
 * @Author xiangerlin
 * @Date 2024/6/7 14:44
 **/
@Service
public class Cbs8ServiceImpl implements ICbs8Service {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IPaymentService paymentService;
    @Override
    public PayResponseDTO payApply(PaymentEntity paymentEntity) {
        Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                .put("apiCode", "8000260001")
                .put("publicKey","ZJYA1vBeY1ai53iNmbAEsw6DImjkXGBkdMailxcBdliFC85Ce7eDIk+3zDUT+v578prj")
                .put("secretKey","7Gp6OjHrIaQ6R3tXGPrI4morjQyWL+qu4JJschQnkBRtv26VDgGFVYKOy5kMZfd/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")
                .put("appId","800026")
                .build();
        String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterfaceToESB").addHeaders(headerMap).body(JSONObject.toJSONString(paymentEntity)).timeout(60000).execute().body();
        //解密响应报文
        String result = decryptResBody(body);
        if (StrUtil.isNotEmpty(result)){
            CbsResponseDTO cbsResponseDTO = JSONObject.parseObject(result, CbsResponseDTO.class);
            List<JSONObject> dataList = cbsResponseDTO.getData();
            if (CollectionUtils.isNotEmpty(dataList)){
                JSONObject o = dataList.get(0);
                PayResponseDTO payResponseDTO = JSON.toJavaObject(o, PayResponseDTO.class);
                return payResponseDTO;
            }
        }
        return new PayResponseDTO();
    }

    /**
     * 通过业务参考号查询交易结果 3.2.6
     *
     * @param resultRequestDTO
     * @return
     * @throws Exception
     */
    @Override
    public List<PayResultResDTO> queryPayResult(PayResultRequestDTO resultRequestDTO) {
        Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                .put("apiCode", "8000260002")
                .put("publicKey","ZJYA1vBeY1ai53iNmbAEsw6DImjkXGBkdMailxcBdliFC85Ce7eDIk+3zDUT+v578prj")
                .put("secretKey","7Gp6OjHrIaQ6R3tXGPrI4morjQyWL+qu4JJschQnkBRtv26VDgGFVYKOy5kMZfd/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")
                .put("appId","800026")
                .build();
        String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterfaceToESB").addHeaders(headerMap).body(JSONObject.toJSONString(resultRequestDTO)).timeout(60000).execute().body();
        String result = decryptResBody(body);
        CbsResponseDTO cbsResponseDTO = JSONObject.parseObject(result, CbsResponseDTO.class);
        if (CollectionUtils.isNotEmpty(cbsResponseDTO.getData())){
            List<JSONObject> dataList = cbsResponseDTO.getData();
            List<PayResultResDTO> payResultList = CBSUtil.convertJsonArrayToList(dataList, PayResultResDTO.class);
            return payResultList;
        }
        return new ArrayList<PayResultResDTO>();
    }

    /**
     * 查询电子回单
     *
     * @param elecRequestDTO startDate 开始日期 - 必填
     *                       endDate 结束日期 -必填
     *                       billStatus 回单状态 1-已取回 0-未取回 ，只有已取回的才能下载
     *                       settleBusinessReferenceCode 业务参考号
     * @return List<ElecResponseDTO>
     * bucketFileUrl 回单下载地址
     * billFileName 回单文件名称
     * settleBusinessReferenceCode 业务参考号
     */
    @Override
    public List<ElecResponseDTO> queryElecBill(ElecRequestDTO elecRequestDTO) {
        if (null == elecRequestDTO){
            elecRequestDTO = new ElecRequestDTO();
        }
        if (StrUtil.isEmpty(elecRequestDTO.getStartDate())){
            elecRequestDTO.setStartDate(DateUtil.today());
        }
        if (StrUtil.isEmpty(elecRequestDTO.getEndDate())){
            elecRequestDTO.setEndDate(DateUtil.today());
        }
        String params = JSON.toJSONString(elecRequestDTO, SerializerFeature.WRITE_MAP_NULL_FEATURES, SerializerFeature.QuoteFieldNames);
        logger.info("电子回单查询请求参数为:{}", params);
        Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                .put("apiCode", "8000260005")
                .put("publicKey","ZJYA1vBeY1ai53iNmbAEsw6DImjkXGBkdMailxcBdliFC85Ce7eDIk+3zDUT+v578prj")
                .put("secretKey","7Gp6OjHrIaQ6R3tXGPrI4morjQyWL+qu4JJschQnkBRtv26VDgGFVYKOy5kMZfd/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")
                .put("appId","800026")
                .build();
        String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterfaceToESB").addHeaders(headerMap).body(params).timeout(60000).execute().body();
        String result = decryptResBody(body);
        if (StrUtil.isNotEmpty(result)){
            CbsResponseDTO cbsResponseDTO = JSONObject.parseObject(result, CbsResponseDTO.class);
            if (null != cbsResponseDTO){
                if (CollectionUtils.isNotEmpty(cbsResponseDTO.getData())){
                    List<JSONObject> dataList = cbsResponseDTO.getData();
                    if (CollectionUtils.isNotEmpty(dataList)){
                        JSONObject jsonObject = dataList.get(0);
                        CbsResDataDTO dataDTO = JSON.toJavaObject(jsonObject, CbsResDataDTO.class);
                        List<ElecResponseDTO> elecResponseDTOList = CBSUtil.convertJsonArrayToList(dataDTO.getList(), ElecResponseDTO.class);
                        return elecResponseDTOList;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 查询交易明细
     *
     * @param transactionDetailReqDTO
     * @return
     */
    @Override
    public CbsResDataDTO  queryTransactionDetail(TransactionDetailReqDTO transactionDetailReqDTO) {
        //页码
        int currentPage = transactionDetailReqDTO.getCurrentPage();
        //每页条数
        int pageSize = transactionDetailReqDTO.getPageSize();
        if (currentPage == 0){
            currentPage = CBSUtil.DEFAULT_CURRENT_PAGE;
            transactionDetailReqDTO.setCurrentPage(currentPage);//页码
        }
        if (pageSize == 0){
            pageSize = CBSUtil.DEFAULT_PAGE_SIZE;
            transactionDetailReqDTO.setPageSize(pageSize);
        }
        if (StrUtil.isNotEmpty(transactionDetailReqDTO.getStartDate())){
            transactionDetailReqDTO.setStartDate(DateUtil.today());
        }
        if (StrUtil.isNotEmpty(transactionDetailReqDTO.getEndDate())){
            transactionDetailReqDTO.setEndDate(DateUtil.today());
        }
        String params = JSON.toJSONString(transactionDetailReqDTO);
        Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                .put("apiCode", "8000260006")
                .put("publicKey","ZJYA1vBeY1ai53iNmbAEsw6DImjkXGBkdMailxcBdliFC85Ce7eDIk+3zDUT+v578prj")
                .put("secretKey","7Gp6OjHrIaQ6R3tXGPrI4morjQyWL+qu4JJschQnkBRtv26VDgGFVYKOy5kMZfd/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")
                .put("appId","800026")
                .build();
        String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterfaceToESB").addHeaders(headerMap).body(params).timeout(60000).execute().body();
        String result = decryptResBody(body);
        if (StrUtil.isNotEmpty(result)){
            CbsResponseDTO cbsResponseDTO = JSONObject.parseObject(result, CbsResponseDTO.class);
            if (null != cbsResponseDTO){
                if (CollectionUtils.isNotEmpty(cbsResponseDTO.getData())){
                    List<JSONObject> list = cbsResponseDTO.getData();
                    if (CollectionUtils.isNotEmpty(list)){
                        JSONObject jsonObject = list.get(0);
                        CbsResDataDTO dataDTO = JSON.toJavaObject(jsonObject, CbsResDataDTO.class);
                        return dataDTO;
                    }
                }
            }
        }
        return new CbsResDataDTO();
    }

    /**
     * 代发代扣 支付申请
     * @param paymentApplySubmitReqDTO
     * @param paymentApplyAgentList
     */
    @Override
    public PayResponseDTO agentPayApply(PaymentApplySubmitReqDTO paymentApplySubmitReqDTO, List<PaymentApplyAgentDTO> paymentApplyAgentList) {
        AgentPayRequestDTO param = new AgentPayRequestDTO();
        param.setPaymentApplySubmitReqDTO(paymentApplySubmitReqDTO);
        param.setPaymentApplyAgentDTO(paymentApplyAgentList);
        String params = JSON.toJSONString(param);
        Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                .put("apiCode", "8000260003")
                .put("publicKey","ZJYA1vBeY1ai53iNmbAEsw6DImjkXGBkdMailxcBdliFC85Ce7eDIk+3zDUT+v578prj")
                .put("secretKey","7Gp6OjHrIaQ6R3tXGPrI4morjQyWL+qu4JJschQnkBRtv26VDgGFVYKOy5kMZfd/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")
                .put("appId","800026")
                .build();
        String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterfaceToESB").addHeaders(headerMap).body(params).timeout(60000).execute().body();
        String result = decryptResBody(body);
        if (StrUtil.isNotEmpty(result)){
            CbsResponseDTO cbsResponseDTO = JSONObject.parseObject(result, CbsResponseDTO.class);
            List<JSONObject> dataList = cbsResponseDTO.getData();
            if (CollectionUtils.isNotEmpty(dataList)){
                JSONObject o = dataList.get(0);
               PayResponseDTO payResponseDTO = JSON.toJavaObject(o, PayResponseDTO.class);
                return payResponseDTO;
            }
        }
        return new PayResponseDTO();
    }

    /**
     * 代发代扣 详情查询
     *
     * @param agentPayResultRequestDTO
     * @return
     */
    @Override
    public AgentPayResultResDTO agentPayResult(AgentPayResultRequestDTO agentPayResultRequestDTO) {
        Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                .put("apiCode", "8000260004")//数智办公
                .put("publicKey","ZJYA1vBeY1ai53iNmbAEsw6DImjkXGBkdMailxcBdliFC85Ce7eDIk+3zDUT+v578prj")//数智财资
                .put("secretKey","7Gp6OjHrIaQ6R3tXGPrI4morjQyWL+qu4JJschQnkBRtv26VDgGFVYKOy5kMZfd/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")
                .put("appId","800026")
                .build();
        String params = JSON.toJSONString(agentPayResultRequestDTO);
        String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterfaceToESB").addHeaders(headerMap).body(params).timeout(60000).execute().body();
        //解密报文
        String result = decryptResBody(body);
        if (StrUtil.isNotEmpty(result)){
            CbsResponseDTO cbsResponseDTO = JSONObject.parseObject(result, CbsResponseDTO.class);
            List<JSONObject> dataList = cbsResponseDTO.getData();
            if (CollectionUtils.isNotEmpty(dataList)){
                JSONObject o = dataList.get(0);
                AgentPayResultResDTO agentPayResultResDTO = JSON.toJavaObject(o, AgentPayResultResDTO.class);
                return agentPayResultResDTO;
            }
        }
        return new AgentPayResultResDTO();
    }

    /**
     * 解密响应报文
     * @param body
     * @return
     */
    private String decryptResBody(String body){
        if (StrUtil.isNotEmpty(body)){
            JsonResultEntity resultEntity = JSONObject.parseObject(body,JsonResultEntity.class);
            String bodyBase64 = String.valueOf(resultEntity.getAttribute());
            byte[] bodyBytes = Base64.getDecoder().decode(bodyBase64);
            //这里验证一下，如果系统异常 返回的报文没加密
            String test = new String(bodyBytes);
            if (JSONUtil.isTypeJSON(test)){
                return test;
            }
            //解密报文
            String result = CBSUtil.decrypt(bodyBytes);
            logger.info("银行响应参数:{}",result);
            return result;
        }
        return null;
    }
}
