package cn.pluss.platform.controller.merchant;

import cn.pluss.platform.channel.ys.impl.YSAuditServiceV3;
import cn.pluss.platform.entity.SubMerchantApplyOrder;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.SubMerchantApplyOrderMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.wx.WxCommonService;
import cn.pluss.platform.ys.impl.v20220527.ReqMethod;
import cn.pluss.platform.ys.impl.v20220527.YsServiceV3;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import static cn.pluss.platform.util.WechatSignUtil.*;

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

    private final SubMerchantApplyOrderMapper subMerchantApplyOrderMapper;
    @Resource
    private MerchantBaseInfoService merchantBaseInfoService;
    @Resource
    private YsServiceV3 ysServiceV3;
    @Resource
    private YSAuditServiceV3 ysAuditServiceV3;
    @Resource
    private WxCommonService wxCommonService;


    /**
     * 跳转到微信商户认证图片
     * @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() + "' />");
    }
//    @PostMapping("/authorisation")
//    public void authorisation(){
////        MerchantBaseInfo merchantBaseInfoByUserId = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);
//        JSONObject bizContentMap = new JSONObject();
////        Map<String,Object> bizContentMap = new HashMap<>();
//        //交易报备渠道编号 CUPS_WECHAT-银联微信；CUPS_ALIPAY-银联支付宝；NUCC_WECHAT-网联微信；NUCC_ALIPAY-网联支付宝
//        bizContentMap.put("channelCode","CUPS_WECHAT");
//        //商户号
//        bizContentMap.put("mercId","QRY230510383416");
//        //商户信息-营业执照营业执照复印件(盖公章)
//        bizContentMap.put("linencePhoto","https://czg-oss.oss-cn-hangzhou.aliyuncs.com/images/7228fde116c14c6380fce592c97e8998.png?Expires=1998984528&OSSAccessKeyId=LTAI5tPdEfYSZcqHbjCrtPRD&Signature=klQgxxm4MgTR1JuJTLW5NZJ9C%2BE%3D");
//        //商户信息-法人身份证复印件（盖私章，签字）/原件扫描件
//        bizContentMap.put("indentityPhoto","");
//        //商户信息-服务协议复印件（盖公章）/原件扫描件
//        bizContentMap.put("protocolPhoto","");
//        //商户信息-组织机构代码证（盖公章）/原件扫描件
//        bizContentMap.put("cocc","");
//        //商户信息-法人身份证正面照
//        bizContentMap.put("sfzFrontPhoto","");
//        //商户信息-法人身份证反面照
//        bizContentMap.put("sfzBackPhoto","");
//        //商户信息法人身份证号码
//        bizContentMap.put("idcarNo","");
//        //商户信息-银盛商户类型
//        bizContentMap.put("mccSubCd","5814");
//        //业务类型0-微信 1-支付宝
//        bizContentMap.put("busiType","0");
//        //商户信息-商户简称
//        bizContentMap.put("mercShortName","会飞的土豆");
//        //商户信息-商户归属省
//        bizContentMap.put("mercProv","7900");
//        //商户信息-商户归属市
//        bizContentMap.put("mercCity","7910");
//        //商户信息-商户归属区
//        bizContentMap.put("mercArea","8081");
//        //商户信息-营业地址（联系地址）
//        bizContentMap.put("busAddr","荣民国际");
//        //商户信息-联系人姓名
//        bizContentMap.put("contactsName","李雯");
//        //商户信息-联系人手机号
//        bizContentMap.put("contactsTel","18710449883");
//        //商户信息-联系人邮箱
//        bizContentMap.put("contactsEmail","1657953836@qq.com");
//        //商户信息-法人姓名
//        bizContentMap.put("crpNm","李雯");
//        //商户信息-法人证件号
//        bizContentMap.put("certNo","610323199812250941");
//        //商户信息-代理商名称
//        bizContentMap.put("agentName","陕西超掌柜科技有限公司");
//        //商户信息-代理商编号
//        bizContentMap.put("agtMercId","801521000002WJW");
//        //商户信息-开户行行别
//        bizContentMap.put("bankType","1051000");
//        //商户信息-开户行名称
//        bizContentMap.put("bankName","中国建设银行陕西省分行");
//        //商户信息-账户类型
//        bizContentMap.put("accountType","11");
//        //商户信息-账户名称
//        bizContentMap.put("accountName","李雯");
//        //商户信息-账户账号
//        bizContentMap.put("accountNo","QRY230510383416");
//        //商户信息-客户号
//        bizContentMap.put("custId","2023051028630896");
//        //商户信息-报备行业类型
//        bizContentMap.put("mchType","139");
//        bizContentMap.put("mercName","");
//        bizContentMap.put("reportName","");
//        //商户信息-商户类别 0或null：普通企业商户，1：小微商户,2：个体商户,3：事业单位，4：社会组织（原其他组织）， 5：政府机关
//        bizContentMap.put("mercType","1");
//        bizContentMap.put("certType","");
//        bizContentMap.put("pId","");
//        bizContentMap.put("shopPhoto","https://czg-oss.oss-cn-hangzhou.aliyuncs.com/images/f2804e6991474b4691bda17d8a644f41.png?Expires=1998984700&OSSAccessKeyId=LTAI5tPdEfYSZcqHbjCrtPRD&Signature=aW28so6wOxOfdJpU7sgA4gr1%2FeE%3D");
//        bizContentMap.put("storeEnvirPhoto","https://czg-oss.oss-cn-hangzhou.aliyuncs.com/images/a71a293015d44006b7db02a911f54775.png?Expires=1998984731&OSSAccessKeyId=LTAI5tPdEfYSZcqHbjCrtPRD&Signature=lkhJ%2F0Rg2%2BA9fd1fQId382g0CO8%3D");
//        bizContentMap.put("idImgHand", "https://czg-oss.oss-cn-hangzhou.aliyuncs.com/images/7228fde116c14c6380fce592c97e8998.png?Expires=1998984528&OSSAccessKeyId=LTAI5tPdEfYSZcqHbjCrtPRD&Signature=klQgxxm4MgTR1JuJTLW5NZJ9C%2BE%3D");
//        bizContentMap.put("bankCardImg","");
//        bizContentMap.put("bdShopPhoto","");
//        bizContentMap.put("bdPosterPhoto","");
//        bizContentMap.put("wxPlatform","");
//        bizContentMap.put("idValidDateBegin","");
//        bizContentMap.put("idValidDateEnd","");
//        bizContentMap.put("busLincenceBegin","");
//        bizContentMap.put("busLincenceEnd","");
//        bizContentMap.put("managementType","");
//        bizContentMap.put("storeName","");
//        bizContentMap.put("wechatCheckStandPhoto","");
//        bizContentMap.put("alipayCheckStandPhoto","");
//        bizContentMap.put("aliPayStoreCashierPhoto","");
//        bizContentMap.put("bookType","");
//        bizContentMap.put("unitPhoto","");
//        bizContentMap.put("hotLine","");
//        //商户信息-证照类型 0:营业执照;1:事业单位法人证书;2:小微商户负责人身份证;3:社会信用等级证书
//        bizContentMap.put("businessLicenseType","2");
//        //商户信息-证件编号
//        bizContentMap.put("businessLicense","610323199812250941");
//        bizContentMap.put("appletAppId","wxc2bb94c0ddda1032");
//        bizContentMap.put("appId1","");
//        bizContentMap.put("appId2","");
//        bizContentMap.put("appId3","");
//        bizContentMap.put("appId4","");
//        bizContentMap.put("applyServices","01;02");
//        bizContentMap.put("picType","2");
//        //商户信息-商户归属机构
//        bizContentMap.put("orgNo","3520000064");
//        ysServiceV3.req(ReqMethod.Reporting, bizContentMap);
//    }
//
//    @PostMapping("/appIdAddOrUpdate")
//    public void appIdAddOrUpdate(){
//        JSONObject bizContentMap = new JSONObject();
//        bizContentMap.put("channelId", "CUPS_WECHAT");
//        bizContentMap.put("mercId", "QRY230511483159");
//        bizContentMap.put("appletId", "wxc2bb94c0ddda1032");
//        ysServiceV3.req(ReqMethod.appIdAddOrUpdate, bizContentMap);
//    }

//    @PostMapping("/auditResult")
//    public void test(String sysFlowId){
//        ysAuditServiceV3.result(sysFlowId);
//    }

    /**
     * 获取公众号权限
     * @param
     * @return
     */
    @PostMapping("/permissions")
    public JSONObject appletPermissions(@RequestBody JSONObject url){
        JSONObject jsApiConfigParam = wxCommonService.getJsApiConfigParam(url.getString("url"));
        return jsApiConfigParam;
    }
}
