package com.szxgl.nft.controller;

import com.alibaba.fastjson.JSONObject;
import com.szxgl.nft.entity.UserNftPhoto;
import com.szxgl.nft.service.NftPhotoService;
import com.szxgl.nft.service.UserService;
import com.szxgl.nft.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/nft")
@Slf4j
public class NFTPhotoController {

    @Autowired
    private NftPhotoService nftPhotoService;

    @Autowired
    private UserService userService;

    /**
     * 获取entropy
     * @param seed 手机号   随机获取图片hash值 select id from nft_photo where LENGTH(phone) = 0 and `status` = 1 order by rand() LIMIT 1
     * @return
     */
    @PostMapping("/getEntropy")
    public R getEntropy(String seed,HttpServletRequest request){
        String openid = CookieUtil.getCookie(request.getCookies());
        if(StringUtils.isBlank(openid)){
            log.error("openid为空："+openid);
            return R.error("openid为空");
        }
        if(StringUtils.isBlank(seed)){
            log.error("seed不能为空："+seed);
            return R.error("手机号不能为空");
        }

        //查询用户通过手机是否绑定Nft图片
        UserNftPhoto userNftPhoto = nftPhotoService.getNftPhoto(seed);
        if(userNftPhoto != null ){
            //手机号加密
            String phone = encrypt(seed);
            phone = String.format("{'seed':'%s'}",phone);
            JSONObject jsonObject = JSONObject.parseObject(phone);
            System.out.println(jsonObject);
            //调用第三方接口
            JSONObject json = HttpClientUtils.httpPost("https://stg-nft-gallery.pingan.com.cn/PABankNewsConference/entropy", jsonObject);
            //JSONObject json = HttpClientUtils.httpPost("https://nft-gallery.pingan.com.cn/PABankNewsConference/entropy", jsonObject);
            if(!"SUCCESS".equals(json.get("code"))){
                log.error( "获取entropy失败！json:"+json);
                return R.error("获取entropy失败！");
            }
            return R.ok(json);
        }else {
            return R.error("手机号没有领取NFT图片资格，获取entropy失败！");
        }
    }

    /**
     * 领取数字藏品
     * @param walletAddr 钱包地址
     * @return
     */
    @PostMapping("/addNFTs")
    public R addNFTs(String walletAddr,HttpServletRequest request,String nickname){
        String openid = CookieUtil.getCookie(request.getCookies());
        if(StringUtils.isBlank(openid)){
            log.error("openid为空："+openid);
            return R.error("openid为空");
        }
        if(StringUtils.isBlank(walletAddr)){
            log.error("walletAddr不能为空:"+walletAddr);
            return R.error("walletAddr不能为空");
        }
        //获取用户的手机号和图片hash值
        Map<String,Object> map = nftPhotoService.getPhoneAndHash(openid);
        if(map == null ){
            return R.error("openid不存在！");
        }
        String phone = (String)map.get("phone");
        phone = encrypt(phone);
        String format = String.format("{'seed':'%s','walletAddr':'%s','paintingHash':'%s','message':'%s'}",phone,walletAddr, map.get("painting_hash"),nickname);
        System.out.println(format);
        JSONObject jsonObject = JSONObject.parseObject(format);
        JSONObject json = HttpClientUtils.httpPost("https://stg-nft-gallery.pingan.com.cn/PABankNewsConference/nfts", jsonObject);
        //JSONObject json = HttpClientUtils.httpPost("https://nft-gallery.pingan.com.cn/PABankNewsConference/nfts", jsonObject);
        //第三方备份用户和NFT图片对应关系操作成功
        if("SUCCESS".equals(json.get("code"))){
            //绑定用户昵称
            userService.addUserNftPhoto(openid,nickname,walletAddr);
        }
        return R.ok(json);
    }

    /**
     * 领取数字藏品展示页面和数字藏品详情
     * @return
     */
    @PostMapping("/getNftPhoto")
    public R getNftPhoto(HttpServletRequest request){
        String openid = CookieUtil.getCookie(request.getCookies());
        if(StringUtils.isBlank(openid)){
            log.error("openid为空："+openid);
            return R.error("openid为空");
        }
        //查询数字藏品详情
        Map<String, Object> map = nftPhotoService.getNftPhotoUrl(openid);
        if(map != null ){
            if(map.get("url") != null){
                int status = (int)map.get("status");
                String url = (String) map.get("url");
                if(status == 1 ){
                    url = String.format("https://cdn.xglpa.com/pars-nft/directional200/%s.png",url);
                }else if(status == 2){
                    url = String.format("https://cdn.xglpa.com/pars-nft/scene200/%s.png",url);
                }else if(status == 3 ){
                    url = String.format("https://cdn.xglpa.com/pars-nft/nonDirectional500/%s.png",url);
                }
                map.remove("status");
                map.put("url",url);
                //获取数字藏品数量
                int count = nftPhotoService.getNftCount();
                map.put("count",count);
            }
            return R.ok(map);
        }
        return R.ok("openid不存在！");
    }


    //字符串加密
    public String encrypt(String seed){
        String phone = "";
        try {
            EncryptUtil encryptUtil = new EncryptUtil();
            phone = encryptUtil.encrypt(seed);
        } catch (Exception e) {
            log.error("加密失败！");
            e.printStackTrace();
        }
        return phone;
    }

    public static void main(String[] args) {
        String format = String.format("{'seed':'%s','walletAddr':'%s','paintingHash':'%s','message':''}","seed", "walletAddr", "paintingHash");
        JSONObject jsonObject = JSONObject.parseObject(format);
        System.out.println(jsonObject);
        //cdn访问路径：https://cdn.xglpa.com/pars-nft/directional200/0306chunfen_29_1583466279_0000519.png

    }

}
