<?php

namespace app\controller;


use app\model\chatgpt\ChatgptRecharge;
use app\model\chatgpt\ChatgptOrder;
use app\model\chatgpt\UserChatgptUseRecord;
use app\model\User;
use app\model\wxpay\Wxpay;
use think\facade\Db;
use think\facade\Request;

/**
 * chatgpt
 */
class Chatgpt extends CommonController
{

    /**
     * 检测计数
     * 833456167
     */
    public function getAnswerByChatgpt()
    {
        $uid      = Request::param('uid')      ?? '';
        $question = Request::param('question') ?? '';
        if( ! $uid || ! $question) {
            return $this->_json_error('请求错误！');
        }
        $user = User::find($uid);
        if( ! $user) {
            return $this->_json_succ('请先注册后使用！');
        }

        if($user->chatgpt_num <= 0) {
            return $this->_json_succ('请支付使用！' , 1007);
        }

        $answer = Request::param('answer') ?? '';

        /**
         * 启用事务
         */
        Db::startTrans();
        try {
            /**
             * 同步使用记录
             */
            UserChatgptUseRecord::create(
                [
                    'uid'        => $uid ,
                    'question'   => $question,
                    'answer'     => $answer ,
                    'createtime' => time()
                ]
            );
            /**
             * 更新使用次数
             */
            $user->chatgpt_num -= 1;
            $user->save();
            Db::commit();
        }catch(\Exception $e) {
            Db::rollback();
            return $this->_json_error(
                $e->getMessage()
            );
        }

        //$answer = $this->requestChatgpt($question);
        return $this->_json_succ(
            [
                'question' => $question,
                'answer'   => $answer
            ]
        );
    }


    /**
     * chatgpt 请求
     * http://3.15.12.98:5000/chat?content=XXX
     * 3.5.12.98:8009
     *  http://3.15.12.98:5001/chatstream
     */
    protected function requestChatgpt($question)
    {
        $url = "http://3.15.12.98:5000/chat?content=".$question;
        $result = file_get_contents($url);
        return $result;
    }


    /**
     * chatgpt充值次数列表
     */
    public function chatgptNumList()
    {
        return $this->_json_succ(
            ChatgptRecharge::field('id as recharge_id , name , money , num')->where('status' , 1)->select()->toArray()
        );
    }


    /**
     * 下单
     */
    public function generateOrder()
    {
        $params = Request::only(
            [
                'uid' , 'recharge_id'
            ]
        );

        $user = User::find($params['uid'] ?? '');
        if( ! $user) {
            return $this->_json_error('未注册用户，请先注册！');
        }

        $chatgptRecharge = ChatgptRecharge::find($params['recharge_id'] ?? '');
        if( ! $chatgptRecharge) {
            return $this->_json_error('充值信息有误！');
        }

        $orderNo = $this->createOrderNum();
        $params['order_no']    = $orderNo;
        $params['pay_price']   = $chatgptRecharge->money;
        $params['createtime']  = time();
        $result = ChatgptOrder::create(
            $params
        );
        if( ! $result) {
            return $this->_json_error('订单创建失败！');
        }

        $result = (new Wxpay())->createOrder($orderNo , $chatgptRecharge->money);
        $order = $params;
        $order['num']        = $chatgptRecharge->num;
        $order['createtime'] = date('Y-m-d H:i');

        return $this->_json_succ(
            array_merge($result , $order)
        );
    }


    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $orderNo = Request::param('order_no') ?? '';
        $order   = ChatgptOrder::field('order_no , pay_time , createtime , pay_price , recharge_id , order_status')->where('order_no' , $orderNo)->find()->toArray();
        if( ! $order) {
            return $this->_json_error('未查到相关订单！');
        }
        $chatgptRecharge = ChatgptRecharge::find($order['recharge_id'])->toArray();

        $order['num'] = $chatgptRecharge['num'];
        return $this->_json_succ(
            $order
        );
    }


    /**
     * 用户信息
     */
    public function user()
    {
        return $this->_json_succ(
            User::field('chatgpt_num')->find(Request::param('uid') ?? '') ?? []
        );
    }

    /**
     * 绑定邀请码
     */
    public function inviteCode()
    {
        $params = Request::only(
            [
                'order_no' , 'invite_code'
            ]
        );

        if( ! isset($params['invite_code'])) {
            return $this->_json_error('参数错误！');
        }

        $order   = ChatgptOrder::where('order_no' , $params['order_no'])->find();
        if( ! $order) {
            return $this->_json_error('未查到相关订单！');
        }

        $order->invite_code = $params['invite_code'];
        $order->save();
        return $this->_json_succ();
    }


    /**
     * 问答历史记录
     */
    public function historyList()
    {
        $uid      = Request::param('uid')  ?? '';
        $page     = Request::param('page') ?? 1;

        $pageSize = 50;
        $limit = ($page - 1) * $pageSize;

        return $this->_json_succ(
            UserChatgptUseRecord::field('uid , question , answer , createtime')->where('uid' , $uid)->limit($limit , $pageSize)->select()->toArray()
        );
    }

}