package com.rf.psychological.douyin.controller;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.douyin.service.DouYinService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.utils.Result;
import com.rf.psychological.wxpay.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Description:抖音相关接口
 * @Author: mimang
 * @Date: 2023/8/15
 */
@CrossOrigin //跨域
@RestController
@RequestMapping("/api/douyin")
@Api(tags = "抖音相关接口")
@Slf4j
@ConditionalOnProperty(prefix="douyin",name = "isDouYin", havingValue = "true")
public class DouYinController extends BaseController {

    @Autowired
    private DouYinService douYinService;


    @PostMapping("/code2Session")
    @ApiOperation(value = "抖音小程序登录",notes = "code：临时code，获取openid")
    @SafetyProcess
    public Result code2openid2(@RequestBody String json) throws Exception {
        JSONObject resultJson = new JSONObject();

        try {
            JSONObject data = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
            //校验参数
            if (data==null){
                return fail(null,"参数错误");
            }
            String code = data.getString("code");
            if (StringUtils.isEmpty(code)){
                return fail(null,"参数错误");
            }
            //获取session
            String openid = douYinService.jscode2session(code);
            if (StringUtils.isEmpty(openid)){
                return fail(null,"获取openId异常");
            }
            //静默注册登录
            resultJson.put("openId",openid);
            resultJson = douYinService.douyinLogin(openid,resultJson);

            return success(resultJson);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return fail(null,"操作失败"+e.getMessage());
        }
    }

    @PostMapping("/getRQCode")
    @ApiOperation(value = "获取小程序二维码",notes = "appname：是打开二维码的字节系app名称(toutiao:今日头条,toutiao_lite:今日头条极速版,douyin:抖音,douyin_lite:抖音极速版,huoshan:抖音火山版);" +
            "path:小程序/小游戏启动参数，小程序则格式为 encode({path}?{query})，小游戏则格式为 JSON 字符串，默认为空")
    @SafetyProcess
    public Result getRQCode(@RequestBody String json) throws Exception {
        try {
            JSONObject data = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
            //校验参数
            if (data==null){
                return fail(null,"参数错误");
            }
            String path = data.getString("path");
            String appname = data.getString("appname");
            //获取二维码
            String resultCode = douYinService.getRQCode(appname,path);
            return success(resultCode);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return fail(null,"操作失败"+e.getMessage());
        }
    }

    @PostMapping("/createOrder")
    @ApiOperation(value = "预下单接口",notes = "resultId:测试结果id；total_amount：支付价格（单位为[分]）；subject：商品描述。 长度限制不超过 128 字节且不超过 42 字符；" +
            "body：商品详情 长度限制不超过 128 字节且不超过 42 字符；msgPage：支付完成后推送给用户的抖音消息跳转页面，开发者需要传入在app.json中定义的链接，如果不传则跳转首页" )
    @SafetyProcess
    public Result createOrder(@RequestBody String json)  {
        try {
            JSONObject data = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
            //校验参数
            if (data==null){
                return fail(null,"参数错误");
            }
            int totalAmount = data.getIntValue("total_amount");
            String subject = data.getString("subject");
            String body = data.getString("body");
            String resultId = data.getString("resultId");
            String path = data.getString("msgPage");
            Map<String,Object> map = douYinService.createOrder(totalAmount,subject,body,resultId,path);
            return success(map);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return fail(null,"操作失败"+e.getMessage());
        }
    }

    @SafetyProcess
    @ApiOperation("查询订单")
    @GetMapping("/queryOrder/{orderNo}")
    public Result queryOrder(@PathVariable String orderNo)  {
        try {
            Map<String, Object> map = douYinService.queryOrder(orderNo);
            return success(map);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return fail(null,"操作失败"+e.getMessage());
        }
    }

    @ApiOperation(value = "抖音微信订单回调接口")
    @RequestMapping(value = "/notify", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object notify(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            String responseJson = HttpUtils.readData(request);
            log.info("responseJson：{}",responseJson);
            JSONObject jsonObject = JSONObject.parseObject(responseJson);
            JSONObject msgJson = jsonObject.getJSONObject("msg");
            String resultCode = jsonObject.getString("type");
            JSONObject resultJson = douYinService.notifyOrder(jsonObject,msgJson,resultCode);
            return resultJson.toString();
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resultJson = new JSONObject();
            resultJson.put("err_no",8);
            resultJson.put("err_tips","error");
            return resultJson.toString();
        }
    }

    @SafetyProcess
    @ApiOperation("根据报告Id查询用户结果支付情况")
    @GetMapping("/queryOrderByResultId/{resultId}")
    public Result queryOrderByResultId(@PathVariable("resultId") String resultId ){
        try {
            return success(douYinService.queryOrderByResultId(resultId));
        }catch (Exception e){
            return fail();
        }
    }

    @PostMapping("/pushOrder")
    @ApiOperation(value = "订单同步",notes = "resultId:测试结果id；total_amount：支付价格（单位为[分]）；subject：量表名称；path:量表详情路径" +
            "orderNo：订单号；openId：用户openid ；orderStatus：0：待支付1：已支付 2：已取消；imgPath：商品图片" )
    //@SafetyProcess
    public Result pushOrder(@RequestBody String json)  {
        try {
            JSONObject data = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
            //校验参数
            if (data==null){
                return fail(null,"参数错误");
            }
            int totalAmount = data.getIntValue("total_amount");
            String subject = data.getString("subject");
            String orderNo = data.getString("orderNo");
            String openId = data.getString("openId");
            int orderStatus = data.getIntValue("orderStatus");
            String resultId = data.getString("resultId");
            String imgPath = data.getString("imgPath");
            String path = data.getString("msgPage");
            JSONObject map = douYinService.pushOrder(orderNo,resultId,subject,openId,totalAmount,path,orderStatus,imgPath);
            return success(map);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return fail(null,"操作失败"+e.getMessage());
        }
    }

}
