package com.ruoyi.hezhi.api.kaoshi;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.aspose.words.Document;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.asPose.AsposeUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.weixin.config.WeiXinPayConfig;
import com.ruoyi.hezhi.domain.TbMemberOrder;
import com.ruoyi.hezhi.service.*;
import io.swagger.annotations.Api;
import org.springframework.data.repository.init.ResourceReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: LCL
 * @Date: 2024/10/08
 * @Description:通用API
 */
@Api("测试")
@RestController
@RequestMapping("/api/test")
public class ApiTestController {

    @Resource
    private ITbStudyCenterService studyCenterService;
    @Resource
    private ITbStudentService studentService;
    @Resource
    private ITbConferenceRegistrationService conferenceRegistrationService;
    @Resource
    private ITbExamRegistrationService examRegistrationService;
    @Resource
    private ITbMemberOrderService memberOrderService;
    @Resource
    private WeiXinPayConfig weiXinPayConfig;


    /**
     * test1
     *
     * @return success
     */
    @GetMapping("/test1")
    public AjaxResult test1(Long memberUserId, Long examRegistrationId, BigDecimal price) {
        try {
            TbMemberOrder memberOrder = new TbMemberOrder();
            memberOrder.setOrderNo(DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSSSSS,new Date()));
            memberOrder.setMemberUserId(memberUserId);
            memberOrder.setDataId(examRegistrationId);
            memberOrder.setPayPrice(price);
            memberOrder.setOrderType(2);
            memberOrder.setPayType(0);
            memberOrder.setPayStatus(0);
            memberOrder.setRemarks("考试报名费");
            memberOrderService.insertTbMemberOrder(memberOrder);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("test1异常");
        }
    }

    /**
     * test2
     *
     * @return success
     */
    @GetMapping("/test2")
    public AjaxResult test2(HttpServletResponse response) {
        try {
            System.out.println("____________________--wxLogin");

            //redirect_url是回调地址 注意要转换成UrlEncode格式
            String redirectUrl = URLEncoder.encode("https://web.xuexin.com/wxCallback","UTF-8");
            //构造二维码链接地址
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weiXinPayConfig.getAppIdLogin()+"&redirect_uri="+redirectUrl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            //生成的二维码，扫描后跳转上面的地址
            // response.setContentType("image/png");
            // QrCodeUtil.generate(url,300,300,"jpg", response.getOutputStream());

            // 根据实际需求填写 保存文件路径
            // String filePath = "E:\\java\\项目\\IDEA\\学信考试\\图片" + IdUtil.simpleUUID() + ".png";
            // 生成二维码图片并保存到本地
            // QrCodeUtil.generate(url, 300, 300, FileUtil.file(filePath));


            QrConfig config = new QrConfig(300, 300);
            // 设置边距，既二维码和背景之间的边距
            config.setMargin(3);
            // 设置前景色，既二维码颜色（青色）
            config.setForeColor(Color.BLUE);
            // 设置背景色（灰色）
            config.setBackColor(Color.gray);
            // 生成二维码到文件，也可以到流
            BufferedImage image = QrCodeUtil.generate(url, config);

            //将newImage写入字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ImageIO.write(image, "jpg", baos );
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 获取字节数组
            byte[] data = baos.toByteArray();
            String base64String = Base64.getEncoder().encodeToString(data);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("qrcodeUrlBase64", base64String);

            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("test2异常");
        }
    }

    /**
     * 微信登录二维码
     *
     * @param
     * @return 结果
     */
    @GetMapping("/wxLoginQRCode")
    public AjaxResult wxLoginQRCode() {
        // 微信开放平台授权baseUrl，固定的地址
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 回调地址
        String redirectUrl = weiXinPayConfig.getRedirectUrl(); //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException(e.getMessage());
        }
        // 防止csrf攻击（跨站请求伪造攻击）
        String state = IdUtils.randomUUID().replaceAll("-", "");//一般情况下会使用一个随机数
        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                weiXinPayConfig.getAppIdLogin(),
                redirectUrl,
                state);
        HashMap<String, Object> map = new HashMap<>();
        map.put("qrcodeUrl", qrcodeUrl);
        return AjaxResult.success(map);
    }

    public static void main(String[] args) {



    }

    /**
     * 渲染doc
     * @param stream
     * @param saveUrl
     * @param paramMap
     * @param watermark
     * @param flag
     */
    public static void test(InputStream stream, String saveUrl, Map<String, String> paramMap, String watermark, Boolean flag){
//        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("$姓名$", "彭于晏");
//        paramMap.put("$性别$", "男");
//        paramMap.put("$曾用名$", "刘德华");
//        paramMap.put("$民族$", "汉族");
//        paramMap.put("$身份证号$", "411111111111111111");
//        paramMap.put("$出生年$", "2002");
//        paramMap.put("$出生月$", "11");
//        paramMap.put("$出生日$", "13");
//        paramMap.put("$生源类型$", "河南");
//        paramMap.put("$籍贯$", "河南");
//        paramMap.put("$政治面貌$", "群众");
//        paramMap.put("$蓝底证件照$", "$pic:https://image.xnszz.com/IMG_787_443@FjG6j3N87NSxvu29laajrnE33VBN.jpg");
//        paramMap.put("$学历$", "硕士");
//        paramMap.put("$专业$", "计算机科学与技术");
//        paramMap.put("$所在学校$", "郑州轻工业大学");
//        paramMap.put("$入学年份$", "2019");
//        paramMap.put("$联系方式$", "18595927131");
//        paramMap.put("$通信地址$", "河南省郑州市金水区天伦路9号院");
//        paramMap.put("$邮编$", "450000");
//        paramMap.put("$联系电话$", "18595927131");
//        paramMap.put("$电子邮箱$", "wny1123@163.com");
//        paramMap.put("$机构名称$", "工业和信息化部教育与考试中心");
//        paramMap.put("$职业名称$", "高级网络与信息安全工程师");
//        paramMap.put("$报名批次$", "202407");
//        paramMap.put("$学习中心$", "河南省数字商务中心");
//        paramMap.put("$机构代码$", "91410183MA9NBKTX3U");
//        paramMap.put("$年$", "2024");
//        paramMap.put("$月$", "12");
//        paramMap.put("$日$", "16");
//        paramMap.put("$身份证正面$", "$pic:http://www.chsie.com.cn/img/logo.34210b2b.png");
//        paramMap.put("$身份证反面$", "$pic:http://www.chsie.com.cn/img/logo.34210b2b.png");

        InputStream inputStream = ResourceReader.class.getClassLoader().getResourceAsStream("reportForm/学信考试卷报名表（新）.docx");
        Document nodes = AsposeUtil.replace4Doc(
                inputStream,
                "C:\\Users\\lenovo\\Desktop\\新建 Microsoft Word 文档.docx",
                paramMap,
                "0",
                false);
    }

}
