package com.gxwebsoft.shop.controller;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaQrcodeServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.config.WxMaProperties;
import com.gxwebsoft.shop.entity.Order;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Value;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "微信相关")
@RestController
@RequestMapping("/api/wechat")
public class WeChatController extends BaseController {
    @Resource
    private WxMaProperties wxMaProperties;

    @Value("${config.upload-path}")
    private String uploadPath;

    @ApiOperation("好友代付二维码")
    @PostMapping("/friend-pay-qr")
    public ApiResult<String> makeFriendPayQr(@RequestBody Order order, HttpServletRequest request){
        String filepath = uploadPath + "qrcode/" + getTenantId();
        if (!FileUtil.exist(filepath)) FileUtil.mkdir(filepath);
        String filename = "/friendPay_" + order.getOrderId() + ".png";
        if (FileUtil.exist(filepath + "/" + filename)) return success("生成成功", "file/qrcode/" + getTenantId() + filename);
        try {
            makeQr(request, filename, order.getOrderId().toString(), "pages/index/index");
        } catch (IOException | WxErrorException e) {
            e.printStackTrace();
        }
        return success("生成成功", "file/qrcode/" + getTenantId() + filename);
    }

    public void makeQr(HttpServletRequest request, String filename, String scene, String page) throws IOException, WxErrorException {
//        final RequestUtil requestUtil = new RequestUtil();
//        String access_token = JwtUtil.getAccessToken(request);
//        requestUtil.setAccessToken(access_token);
//        requestUtil.setTenantId(getTenantId().toString());
//        ApiResult<?> res = requestUtil.getWxConfig();
//        System.out.println(res);
        WxMaService wxMaService = wxMaService();
        WxMaQrcodeService wxMaQrcodeService = new WxMaQrcodeServiceImpl(wxMaService);
        WxMaCodeLineColor lineColor = new WxMaCodeLineColor();
        lineColor.setR("0");
        lineColor.setG("0");
        lineColor.setB("0");
        File file = wxMaQrcodeService.createWxaCodeUnlimit(scene, page, false, "develop", 200, false,
                lineColor, false);
        file.renameTo(new File(filename));
    }

    public WxMaService wxMaService() {
        List<WxMaProperties.Config> configs = wxMaProperties.getConfigs();
        if (configs == null) {
            throw new WxRuntimeException("大哥，拜托先看下项目首页的说明（readme文件），添加下相关配置，注意别配错了！");
        }
        WxMaService maService = new WxMaServiceImpl();
        maService.setMultiConfigs(
                configs.stream()
                        .map(a -> {
                            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
                            config.setAppid(a.getAppid());
                            config.setSecret(a.getSecret());
                            config.setToken(a.getToken());
                            config.setAesKey(a.getAesKey());
                            config.setMsgDataFormat(a.getMsgDataFormat());
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        return maService;
    }
}
