package com.yonge.cooleshow.teacher.controller.open;

import com.alibaba.fastjson.JSONObject;
import com.yonge.cooleshow.biz.dal.entity.UserWithdrawalCallback;
import com.yonge.cooleshow.biz.dal.enums.DealStatusEnum;
import com.yonge.cooleshow.biz.dal.service.UserWithdrawalService;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.thirdparty.lingxinpay.RSA;
import com.yonge.toolset.utils.json.JsonUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/open/userWithdrawal")
@Api(value = "开放权限接口-结算", hidden = true)
public class UserWithdrawalClient extends BaseController {
    private final static Logger log = LoggerFactory.getLogger(UserWithdrawalClient.class);

    @Autowired
    private UserWithdrawalService userWithdrawalService;

    @Value("${withdraw.privateKey}")
    private String privateKey;

    /**
     * 异步回调接收-结算
     *
     * @param content
     * @param request
     * @return
     */
    @PostMapping("/callback")
    public String callback(@RequestBody String content, HttpServletRequest request) {
        log.info("交易回调请求地址：{} 请求参数：{}", request.getRemoteAddr(), content);
        try {
            if (StringUtils.isBlank(content)) {
                throw new Exception();
            }
            JSONObject jsonObject = JSONObject.parseObject(content);
            String jsonStr = RSA.decryptPri(jsonObject.getString("sign"), privateKey);
            log.info("jsonStr:{}", jsonStr);

            Map<String, Object> withdrawRecord = JSONObject.parseObject(jsonStr);
            UserWithdrawalCallback callback = JsonUtil.toJavaObject(withdrawRecord, UserWithdrawalCallback.class);

            userWithdrawalService.callback(callback, jsonStr);
        } catch (BizException e) {
            log.error("解密失败e：{}", e.getMessage());
            return "failed";
        } catch (Exception e) {
            log.error("解密失败e：{}", e);
            return "failed";
        }
        return "success";
    }

    /**
     * 异步回调接收-签署协议
     *
     * @param dataStr
     * @param request
     * @return
     */
    @PostMapping("/contractCallback")
    public String contractCallback(@RequestBody String dataStr, HttpServletRequest request) {
        log.info("回调请求地址：{} 请求参数：{}", request.getRemoteAddr(), dataStr);
        try {
            if (StringUtils.isBlank(dataStr)) {
                throw new Exception();
            }
            JSONObject data = JSONObject.parseObject(dataStr);
            JSONObject content = data.getJSONObject("content");

            String return_code = data.getString("return_code");

            if (CollectionUtils.isEmpty(content) || null == content.getString("serialNo")) {
                log.error("签署失败,返回合同编号为空 {}", dataStr);
                return "failed";
            }

            if ("T".equals(return_code)) {
                userWithdrawalService.contractCallback(
                        DealStatusEnum.SUCCESS.getCode(), content.getString("serialNo"),
                        content.getString("contractUrl"), null);
                return "success";
            } else {
                String return_message = data.getString("return_message");
                userWithdrawalService.contractCallback(
                        DealStatusEnum.FAILED.getCode(), content.getString("serialNo"), null, return_message);
                return "failed";
            }
        } catch (Exception e) {
            log.error("签署失败e：{}", e);
            return "failed";
        }
    }
}
