package com.ruoyi.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.cos.TxApiHttpUtils;
import com.ruoyi.common.cos.TxApiSdkUtils;
import com.ruoyi.controller.req.ContentCanUseReq;
import com.ruoyi.controller.req.TxContentReq;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.level.entity.Level;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.RyController;
import com.ruoyi.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文本/图片安全验证
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/appletAuth")
@Api(tags = "文本/图片安全验证")
public class ApiAppletAuthController extends RyController {

    @Value("${DD_drawing.appid}")
    private String DD_drawingAppId;

    @Value("${DD_drawing.secret}")
    private String DD_drawingSecret;

    @Value("${DD_co_creation.appid}")
    private String DD_co_creationAppId;

    @Value("${DD_co_creation.secret}")
    private String DD_co_creationSecret;

    @Autowired
    private CustomerService customerService;
    @Autowired
    private StoreService storeService;


    @PostMapping("/checkContext")
    @ApiOperation(value = "腾讯云文本内容安全识别", notes = "腾讯云文本内容安全识别")
    public JSONObject checkContext(@RequestBody TxContentReq txContentReq) {
        if (StrUtil.isEmpty(txContentReq.getContent())) {
            return null;
        }
        return TxApiSdkUtils.checkContext(txContentReq.getContent());
    }


    @PostMapping("/checkImages")
    @ApiOperation(value = "腾讯云图片内容安全识别", notes = "腾讯云图片内容安全识别")
    public JSONObject checkImages(@RequestBody TxContentReq txContentReq) {
        if (StrUtil.isEmpty(txContentReq.getContent())) {
            return null;
        }
        return TxApiSdkUtils.checkImages(txContentReq.getContent());
    }

    @PostMapping("/msgSecCheck/{type}")
    @ApiOperation(value = "微信小程序文本内容安全识别", notes = "微信小程序文本内容安全识别")
    public ResponseData msgSecCheck(@PathVariable("type") String type, @RequestBody ContentCanUseReq msgSecReq) {
        if (StrUtil.isEmpty(msgSecReq.getContent())) {
            return ResponseData.error("暂未授权！");
        }

        UserVo userVo = getUserVo();
        String openId = "";
        if (userVo.getUserType().equals(UserEnums.customer.getCode())) {
            Customer customer = customerService.getById(userVo.getUserId());
            openId = customer.getWechatAppletOpenid();
        } else if (userVo.getUserType().equals(UserEnums.store.getCode())) {
            Store store = storeService.getById(userVo.getUserId());
            openId = store.getWechatAppletOpenid();
        } else {
            return ResponseData.success();
        }

        if (StrUtil.isNotEmpty(openId)) {
            String str = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + getToken(type);
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("openid", openId);
            bodyMap.put("version", 2);
            bodyMap.put("scene", msgSecReq.getScene());
            bodyMap.put("content", msgSecReq.getContent());
            String result = HttpUtil.createPost(str).body(JSONObject.toJSONString(bodyMap)).execute().body();

            System.out.println(result);
            //判断是否获取成功
            if (ObjectUtil.isEmpty(result)) {
                return ResponseData.error("获取参数错误");
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            return ResponseData.success(jsonObject);

        }
        return ResponseData.success();
    }


    @PostMapping("/mediaCheckAsync/{type}")
    @ApiOperation(value = "微信小程序图片内容安全识别", notes = "微信小程序图片内容安全识别")
    public ResponseData mediaCheckAsync(@PathVariable("type") String type, @RequestBody ContentCanUseReq msgSecReq) {
        if (StrUtil.isEmpty(msgSecReq.getMediaUrl())) {
            return ResponseData.error("暂未授权！");
        }

        UserVo userVo = getUserVo();
        String openId = "";
        if (userVo.getUserType().equals(UserEnums.customer.getCode())) {
            Customer customer = customerService.getById(userVo.getUserId());
            openId = customer.getWechatAppletOpenid();
        } else if (userVo.getUserType().equals(UserEnums.store.getCode())) {
            Store store = storeService.getById(userVo.getUserId());
            openId = store.getWechatAppletOpenid();
        } else {
            return ResponseData.success();
        }
        if (StrUtil.isNotEmpty(openId)) {
            String str = "https://api.weixin.qq.com/wxa/media_check_async?access_token=" + getToken(type);
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("openid", openId);
            bodyMap.put("version", 2);
            bodyMap.put("media_type", 2);
            bodyMap.put("scene", msgSecReq.getScene());
            bodyMap.put("media_url", msgSecReq.getMediaUrl());
            String result = HttpUtil.createPost(str).body(JSONObject.toJSONString(bodyMap)).execute().body();

            System.out.println(result);
            //判断是否获取成功
            if (ObjectUtil.isEmpty(result)) {
                return ResponseData.error("获取参数错误");
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            return ResponseData.success(jsonObject);
        }
        return ResponseData.success();
    }


    /**
     * 获取access_token
     *
     * @return
     */
    public String getToken(String type) {

        String appid = "";

        String secret = "";

        //type :  DD_drawing DD画图, DD_co_creation DD共创
        if (ObjectUtil.equal(type, "DD_drawing")) {
            appid = DD_drawingAppId;

            secret = DD_drawingSecret;
        } else {
            appid = DD_co_creationAppId;

            secret = DD_co_creationSecret;
        }

        String url = "https://api.weixin.qq.com/cgi-bin/token" + "?grant_type=" + "client_credential" + "&appid=" + appid + "&secret=" + secret;
        String result = HttpRequest.get(url).execute().body();
        System.err.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //服务断了status会有值
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode == null) {
            String access_token = (String) jsonObject.get("access_token");
            return access_token;
        } else {
            log.info("获取access_token失败:{}", jsonObject.toJSONString());
        }
        return "";
    }




    /*@UserLoginToken
    @PostMapping("/textCanUse")
    @ApiOperation(value = "文本是否可用", notes = "是否可以体验app或者小程序")
    public ResponseData textCanUse(@RequestBody ContentCanUseReq req) {

        UserVo userVo = getUserVo();
        String openId = "";
        if (userVo.getUserType().equals(UserEnums.customer.getCode())) {
            Customer customer = customerService.getById(userVo.getUserId());
            openId = customer.getWechatAppletOpenid();
        } else if (userVo.getUserType().equals(UserEnums.store.getCode())) {
            Store store = storeService.getById(userVo.getUserId());
            openId = store.getWechatAppletOpenid();
        } else {
            return ResponseData.success();
        }
        if (StrUtil.isBlank(openId)) {
            return ResponseData.success();
        }


        return ResponseData.success();
    }*/


}
