package com.yn.bftl.thirdparty.modules.chinaums.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yn.bftl.thirdparty.modules.chinaums.dto.MchApplicationsNoticeDTO;
import com.yn.bftl.thirdparty.modules.chinaums.dto.byx.ByxMchApplicationsNoticeDTO;
import com.yn.bftl.thirdparty.modules.chinaums.service.ChinaumsCallBackService;
import com.yn.bftl.thirdparty.modules.chinaums.vo.ChinaumsCallBackVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.util.ByteArrayWrapper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @Author：Vance
 * @Description：回调controller
 * @Date：2022/12/8 15:05
 */
@Slf4j
@Api(value = "ChinaumsCallBackController", tags = "公共端-银联回调")
@RestController
@RequestMapping("/chinaums/call_back")
@Validated
public class ChinaumsCallBackController {

    @Resource
    private ChinaumsCallBackService chinaumsCallBackService;


    @ApiOperation(value = "回调")
    @RequestMapping(value = "/byx/result", method = RequestMethod.POST)
    public ChinaumsCallBackVO callbackForByx(HttpServletRequest request) {
        log.info("comming");
        ByxMchApplicationsNoticeDTO byxMchApplicationsNoticeDTO = getByxMchApplicationsNoticeDTOFromStream(request);
        log.info("消息类型 - {},回调时间 - ｛｝",byxMchApplicationsNoticeDTO.getMsgType(),byxMchApplicationsNoticeDTO.getMsgTime());
        return chinaumsCallBackService.callbackForByx(byxMchApplicationsNoticeDTO);
    }

    private static ByxMchApplicationsNoticeDTO getByxMchApplicationsNoticeDTOFromStream(HttpServletRequest request) {
        String requestBody = "";
        try {
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            reader.close();
            inputStream.close();
            requestBody = stringBuilder.toString();

        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        ByxMchApplicationsNoticeDTO byxMchApplicationsNoticeDTO = JSON.parseObject(requestBody, ByxMchApplicationsNoticeDTO.class);
        validateParams(byxMchApplicationsNoticeDTO);
        byxMchApplicationsNoticeDTO.setMsgBodyObject(JSON.parseObject(byxMchApplicationsNoticeDTO.getMsgBody(), JSONObject.class));
        return byxMchApplicationsNoticeDTO;
    }

    private static void validateParams(ByxMchApplicationsNoticeDTO byxMchApplicationsNoticeDTO) {
        if (byxMchApplicationsNoticeDTO == null) {
            log.error("byxMchApplicationsNoticeDTO is null.");
            throw new RuntimeException("参数不正确");
        }
        if (StringUtils.isEmpty(byxMchApplicationsNoticeDTO.getMsgType())) {
            log.error("getMsgType is null.");
            throw new RuntimeException("参数不正确");
        }
        if (StringUtils.isEmpty(byxMchApplicationsNoticeDTO.getMsgBody())) {
            log.error("getMsgBody is null.");
            throw new RuntimeException("参数不正确");
        }
    }

    private static ByxMchApplicationsNoticeDTO byteToObject(byte[] data) {
        if (data == null) {
            log.error("回调参数异常");
            throw new RuntimeException("回调参数异常");
        }
        ObjectMapper mapper = new ObjectMapper();
        ByteArrayWrapper wrapper = new ByteArrayWrapper(data);
        String json = "";
        try {
            json = mapper.writeValueAsString(wrapper);
        } catch (JsonProcessingException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        ByxMchApplicationsNoticeDTO byxMchApplicationsNoticeDTO = JSON.parseObject(json, ByxMchApplicationsNoticeDTO.class);
        return byxMchApplicationsNoticeDTO;
    }

    @ApiOperation(value = "回调")
    @RequestMapping(value = "/result", method = RequestMethod.POST)
    public ChinaumsCallBackVO mchApplicationsResult(@Valid @RequestBody MchApplicationsNoticeDTO mchApplicationsNoticeDTO) {
        return chinaumsCallBackService.mchApplicationsResult(mchApplicationsNoticeDTO);
    }
}
