package com.jeequan.jeepay.pay.ctrl.qr;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.db.entity.SysAdvertConfig;
import com.jeequan.jeepay.pay.ctrl.payorder.AbstractPayOrderController;
import com.jeequan.jeepay.service.impl.MchStoreService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.service.impl.SysAdvertConfigService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
* 微信点金计划controller
*
* @author zx
*
* @date 2022/7/1 17:27
*/
@Controller
@RequestMapping("/api/goldplan")
public class WxGoldPlanController extends AbstractPayOrderController {

    @Autowired private PayOrderService payOrderService;
    @Autowired private MchStoreService mchStoreService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private SysAdvertConfigService advertConfigService;

    /**
     * 点金计划 -- 商家小票链接地址
     **/
    @GetMapping("/custom")
    public String goldplan(){
        try {
            JSONObject paramJSON = getReqParamJSON();
            logger.info("点金计划微信请求参数：{}", paramJSON.toJSONString());

            String platformMchOrderNo = paramJSON.getString("out_trade_no");
            String subMchId = paramJSON.getString("sub_mch_id");
            String checkCode = paramJSON.getString("check_code");

            PayOrder payOrder = payOrderService.selectOneByPlatformMchOrderNo(platformMchOrderNo);
            String transactionId = payOrder.getPlatformOrderNo();
            String paySiteUrl = sysConfigService.getDBApplicationConfig().getPaySiteUrl();
            paySiteUrl = paySiteUrl.endsWith("/") ? paySiteUrl : paySiteUrl + "/";
            String md5Str = String.format(paySiteUrl + "api/goldplan/custom/?sub_mch_id=%s&out_trade_no=%s&transaction_id=%s", subMchId, platformMchOrderNo, transactionId);
            String myCheckCode = JeepayKit.md5(md5Str, CharsetUtil.UTF_8);
            if (!myCheckCode.equals(checkCode)) {
                logger.info("点金计划微信checkCode={}，系统checkCode={}", checkCode, myCheckCode);
                throw new BizException("checkCode校验失败");
            }

            MchStore mchStore = mchStoreService.getById(payOrder.getStoreId());

            request.setAttribute("amount", payOrder.getAmount());
            request.setAttribute("mchShortName", mchStore.getStoreName());
            request.setAttribute("subject", payOrder.getSubject());

            // 商家小票跳转URL优先级：默认取商户传的returnUrl；当为空时，取平台配置的点金计划支付后广告链接；若平台未配置，则隐藏页面上跳转按钮
            if (StringUtils.isNotBlank(payOrder.getReturnUrl())) {
                request.setAttribute("returnUrl", payOrder.getReturnUrl());
            }else {
                // 查询平台点金计划支付后广告
                LambdaQueryWrapper<SysAdvertConfig> wrapper = SysAdvertConfig.gw();
                wrapper.eq(SysAdvertConfig::getAdvertType, SysAdvertConfig.ADVERT_TYPE_AFTER);
                wrapper.eq(SysAdvertConfig::getReleaseState, CS.YES);
                wrapper.eq(SysAdvertConfig::getAppPlace, SysAdvertConfig.APP_PLACE_TOUCH);
                wrapper.orderByDesc(SysAdvertConfig::getCreatedAt);
                List<SysAdvertConfig> list = advertConfigService.list(wrapper);
                if (list.size() > 0) {
                    request.setAttribute("returnUrl", list.get(0).getLinkUrl());
                }else {
                    request.setAttribute("returnUrl", "");
                }
            }

            return "goldplan/custom";

        }catch (Exception e) {
            logger.error("点金计划解析错误", e);
            // 静态CDN地址
            DBApplicationConfig dbApplicationConfig = sysConfigService.getDBApplicationConfig();
            request.setAttribute("staticCdnHost", dbApplicationConfig.getStaticCdnHost());
            request.setAttribute("errMsg", "订单解析错误");
            return "goldplan/error";
        }
    }

}
