package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.MallMemberUser;
import com.ruoyi.mall.domain.MallPayLog;
import com.ruoyi.mall.domain.VipGuide;
import com.ruoyi.mall.service.IMallMemberUserService;
import com.ruoyi.mall.service.IMallPayLogService;
import com.ruoyi.mall.service.IVipGuideService;
import com.ruoyi.web.controller.utils.PayCommonUtil;
import com.ruoyi.web.controller.utils.XiaochengxuPayService;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName 命题创作接口
 * @Description 命题创作接口
 * @Author LCL
 * @Date 2023/10/18
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/propositionCreation")
public class ApiPropositionCreationController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IMallMemberUserService mallMemberUserService;

    /**
     * 获取千帆AccessToken
     *
     * @return
     */
    @GetMapping("/getQFAccessToken")
    @ResponseBody
    public AjaxResult getQFAccessToken() {
        try {
            String qianFanAccessToken = getQianFanAccessToken();
            if (StringUtils.isBlank(qianFanAccessToken)) {

                logger.info("获取千帆AccessToken");
                // 获取token
                RestTemplate restTemplate = new RestTemplate();
                Map<String, String> params = new HashMap<>();
                params.put("clientId", "XPt4ARctnOvbOqiGHGelSjsc");
                params.put("clientSecret", "6MTG1yroquWRLzb01f7sGC9FNe2oxz7Z");
                ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}", String.class, params);
                String body = responseEntity.getBody();
                JSONObject object = JSON.parseObject(body);
                String Access_Token = object.getString("access_token");
                redisTemplate.boundValueOps("qianFanAccessToken").set(Access_Token, 30, TimeUnit.DAYS);

                String t = (String) redisTemplate.boundValueOps("qianFanAccessToken").get();
            }


            // 删除原来的token
            // redisTemplate.delete("qianFanAccessToken");
            // 重新设置最新token
            // redisTemplate.boundValueOps("qianFanAccessToken").set(qianFanAccessToken, 30, TimeUnit.DAYS);

            return AjaxResult.success(getQianFanAccessToken());

        } catch (Exception e) {
            return AjaxResult.error("获取AccessToken失败!");
        }
    }

    /**
     * 命题创作
     *
     * @param params userId 用户ID
     * @param params prompt 提示词
     * @return
     */
    @PostMapping("/createPicture")
    @ResponseBody
    public AjaxResult createPicture(@RequestBody Map<String, Object> params) {
        try {
            if (!params.containsKey("prompt") || StringUtils.isEmpty(params.get("prompt").toString())) {
                return AjaxResult.error("缺少提示词prompt");
            }
            if (!params.containsKey("userId") || StringUtils.isEmpty(params.get("userId").toString())) {
                return AjaxResult.error("缺少用户IDuserId");
            }
            long userId = Long.parseLong(params.get("userId").toString());

            MallMemberUser memberUser = mallMemberUserService.selectMallMemberUserById(userId);
            if (memberUser == null) {
                return AjaxResult.error("用户信息异常！！！");
            }
            if ("0".equals(memberUser.getIsOpen()) && memberUser.getCreateNum() < 1) {
                return AjaxResult.error(300,"创作次数已用完");
            }

            String qianFanAccessToken = getQianFanAccessToken();
            if (StringUtils.isBlank(qianFanAccessToken)) {

                logger.info("获取千帆AccessToken");
                // 获取token
                RestTemplate restTemplate = new RestTemplate();
                Map<String, String> map = new HashMap<>();
                map.put("clientId", "hco0U4TGdVpA73F5mGBZliai");
                map.put("clientSecret", "kBwPxP7PxRy5fTtIalW81GN7A3LFBrEN");
                ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}", String.class, map);
                String body = responseEntity.getBody();
                JSONObject object = JSON.parseObject(body);
                String Access_Token = object.getString("access_token");
                redisTemplate.boundValueOps("qianFanAccessToken").set(Access_Token, 30, TimeUnit.DAYS);
            }

            // 提示词，即用户希望图片包含的元素。长度限制为1024字符，建议中文或者英文单词总数量不超过150个
            String prompt = params.get("prompt").toString();

            RestTemplate restTemplate = new RestTemplate();
            String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/text2image/sd_xl?access_token=" + getQianFanAccessToken();
            SortedMap<String, String> signMap = new TreeMap<>();
            signMap.put("prompt", prompt); // 提示词，即用户希望图片包含的元素。长度限制为1024字符，建议中文或者英文单词总数量不超过150个

            // signMap.put("negative_prompt", ""); // 反向提示词，即用户希望图片不包含的元素。长度限制为1024字符，建议中文或者英文单词总数量不超过150个
            // signMap.put("size", "1024x1024"); // 生成图片长宽，默认值 1024x1024，取值范围如下：["512x512", "768x768", "768x1024", "1024x768", "576x1024", "1024x576", "1024x1024"]注意：比例，不是实际size ["1:1","1:1","3:4","4:3","9:16","16:9","1:1"]
            // signMap.put("n", 1); // 生成图片数量，说明：· 默认值为1· 取值范围为1-4· 单次生成的图片较多及请求较频繁可能导致请求超时
            // signMap.put("steps", 20); // 迭代轮次，说明：· 默认值为20· 取值范围为10-50

            ResponseEntity<String> entity = restTemplate.postForEntity(url, signMap, String.class);
            JSONObject data = JSON.parseObject(entity.getBody());
            String data2 = data.getString("data");

            if ("0".equals(memberUser.getIsOpen()) && memberUser.getCreateNum() > 0) {
                MallMemberUser user = new MallMemberUser();
                user.setId(userId);
                user.setCreateNum(memberUser.getCreateNum() - 1);
                mallMemberUserService.updateMallMemberUser(user);
            }

            return AjaxResult.success().put("data", data2);

        } catch (Exception e) {
            return AjaxResult.error("命题创作失败!");
        }
    }

    /**
     * 从缓存中拿到千帆AccessToken
     *
     * @return
     */
    public String getQianFanAccessToken() {
        String qianFanAccessToken = (String) redisTemplate.boundValueOps("qianFanAccessToken").get();
        return qianFanAccessToken;
    }

}
