package cn.pluss.platform.controller.merchant;

import cn.pluss.platform.entity.SubMerchantApplyOrder;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.SubMerchantApplyOrderMapper;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequiredArgsConstructor
@RequestMapping("/wx")
public class WxController {

    private final SubMerchantApplyOrderMapper subMerchantApplyOrderMapper;

    /**
     * 跳转到微信商户认证图片
     * @param merchantCode  商户code
     */
//    @GetMapping("/img/{merchantCode}")
//    public void img(HttpServletResponse response, @PathVariable("merchantCode") String merchantCode) throws IOException {
//        SubMerchantApplyOrder subMerchantApplyOrder = new SubMerchantApplyOrder().setMerchantCode(merchantCode);
//        subMerchantApplyOrder = subMerchantApplyOrderMapper.selectOne(new QueryWrapper<>(subMerchantApplyOrder).orderByDesc("createTime").last("limit 1"));
//        if (subMerchantApplyOrder == null) {
//            throw new MsgException("未进行微信实名认证申请");
//        }
//
//        if ("0".equals(subMerchantApplyOrder.getStatus())) {
//            throw new MsgException("微信实名认证申请审核中");
//        }
//
//        if (StringUtils.isEmpty(subMerchantApplyOrder.getInfoQrcode())) {
//            throw new MsgException("图片不存在");
//        }
//
//        response.setHeader("content-type", "text/html;charset=UTF-8");
//        response.getWriter().write("<img src='" + subMerchantApplyOrder.getInfoQrcode() + "' />");
//    }

    /**
     * 跳转到微信商户认证图片
     * @param merchantCode  商户code
     */
    @GetMapping("/img/{merchantCode}")
    public void img(HttpServletResponse response, @PathVariable("merchantCode") String merchantCode, @RequestParam(required = false, value = "i") String channelId) throws IOException {
        SubMerchantApplyOrder subMerchantApplyOrder = new SubMerchantApplyOrder().setMerchantCode(merchantCode);
        subMerchantApplyOrder = subMerchantApplyOrderMapper.selectOne(
                new QueryWrapper<>(subMerchantApplyOrder).orderByDesc("createTime")
                        .eq("channelId", channelId)
                        .last("limit 1"));
        if (subMerchantApplyOrder == null) {
            throw new MsgException("未进行微信实名认证申请");
        }

        if ("0".equals(subMerchantApplyOrder.getStatus())) {
            throw new MsgException("微信实名认证申请审核中");
        }

        if (StringUtils.isEmpty(subMerchantApplyOrder.getInfoQrcode())) {
            throw new MsgException("图片不存在");
        }

        response.setHeader("content-type", "text/html;charset=UTF-8");
        response.getWriter().write("<img src='" + subMerchantApplyOrder.getInfoQrcode() + "' />");
    }
}
