<?php

namespace app\api\controller;

use app\api\model\Banner;
use app\api\model\Category;
use app\api\model\CoinRecord;
use app\api\model\Detail;
use app\api\model\Goods;
use app\api\model\MoneyRecord;
use app\api\model\Order;
use app\api\model\PriceRange;
use app\api\model\Prizerecord;
use app\api\model\RechargeList;
use app\api\model\RechargeOrder;
use app\api\model\SearchHistory;
use app\api\model\Setting;
use app\api\model\Box;
use app\api\model\Star;
use app\api\model\Text;
use app\common\controller\Api;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use app\api\library\Retail;
use think\Validate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['baseInfo', 'newestOpen', 'hotBox', 'cheapBox', 'recommend', 'categoryList',
        'boxList', 'boxListByCategory', 'boxDetail', 'boxOpenRecord', 'tryBoxDetail', 'priceRange', 'rechargeList', 'getServiceInfo',
        'getWechatLoginUrl', "getVirData", "sumUv", "getServiceurl", "lunbobox", 'boximages'];

    protected $noNeedRight = ['*'];

    protected $lockUserId = ['coinPay'];


    public function sumUv()
    {
        $ip = request()->ip();
        $check = db("uv")->where(['ip' => $ip])->whereTime("createtime", "today")->find();
        if (empty($check)) {
            db("uv")->insert(['ip' => $ip, "createtime" => time()]);
        }
        $this->success("记录成功");
    }

    /**
     *获取开盒假数据
     */
    public function getVirData()
    {
        $page = request()->param("page") ?? 1;
        $limit = request()->param("limit") ?? 10;
        $domain = request()->domain();
        $list = db("virtuial")->alias("a")->join("goods b", "b.id = a.goods_id")->order("a.add_time desc")->field("a.*,FROM_UNIXTIME(a.add_time,'%Y-%m-%d %H:%i') createtime,b.goods_name, b.image,b.coin_price price")->page($page, $limit)->select();
        foreach ($list as $k => $v) {
            $list[$k]['avatar'] = $domain . $v['avatar'];
            //$list[$k]['image'] = $domain.$v['image'];
            $list[$k]['image'] = $v['image'];
        }
        $total = db("virtuial")->order("add_time desc")->count();

        // print_r($list);die;
        $this->success("获取成功", ["list" => $list, "total" => $total]);
    }

    public function lunbobox()
    {


        $status = 1;
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);
        $statusList = [1 => 'bag', 2 => 'exchange'];

        if (!isset($statusList[$status])) {
            $this->error('状态有误');
        }
        $status = $statusList[$status];

        $order = 'prize.id desc';
        if ('exchange' == $status) {
            $order = 'exchange_time desc';
        }

        $list = Prizerecord::alias('prize')
            ->distinct(true)
            ->field('prize.goods_name,prize.goods_image')
            ->field('prize.box_id')
            ->field('user.nickname,user.avatar')
            ->join('user user', 'user.id = prize.user_id')
            ->order($order)
            ->limit(20)
            ->select();

        $this->success('查询成功', $list);

    }

    /**
     * 基础信息
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function baseInfo()
    {
        // 查询设置
        $setting = Setting::get(1);

        // 查询轮播图
        $banner = Banner::where('place', 'index')->order('weigh', 'desc')->select();
        $bannerlist = [];
        foreach ($banner as $item) {
            $bannerlist[] = [
                'type' => $item->type,
                'image' => cdnurl($item->image, true),
                'value' => $item->value
            ];
        }

        $ret = [
            'logo' => cdnurl($setting->logo_image, true), // 首页LOGO
            'banner' => $bannerlist
        ];
        $this->success('查询成功', $ret);
    }


    public function sList()
    {
        $status = input('status/d');
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);
        $statusList = [1 => 'bag', 2 => 'exchange'];

        if (!isset($statusList[$status])) {
            $this->error('状态有误');
        }
        $status = $statusList[$status];

        $order = 'prize.id desc';
        if ('exchange' == $status) {
            $order = 'exchange_time desc';
        }


        $order = Db::table('box_shai')->where('switch', '1')->order('create_time', 'desc')->limit(($page - 1) * $pagesize, $pagesize)->select();


        $list2 = array(

            'id' => 1,
            'stx' => 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic3.zhimg.com%2F50%2Fv2-6f1c492cbdfe3c24aae44e935a796d5a_hd.jpg&refer=http%3A%2F%2Fpic3.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632275904&t=20baefb74a9f7b152b601ec58726f1e7',


            'smc' => '这个是名称',
            'ssj' => '前天',
            'szw' => '这个盲盒很好玩，我很喜欢，我也介绍了很多人过来完',
            'simg' => array(

                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',
                'https://img.alicdn.com/imgextra/i4/0/O1CN01CHW9ak1RdPu9Vg1r6_!!0-rate.jpg_400x400.jpg',


            )
        );


        /*  ->each(function ($item) use ($status) {
              $item->goods_image = $item->goods_image ? cdnurl($item->goods_image, true) : '';

              $item->box_coin_price = intval($item->box_coin_price);
              $item->box_rmb_price = floatval($item->box_rmb_price);

              if ('exchange' == $status) {
                  $item->time = date('Y-m-d H:i:s', $item->exchange_time);
              } else {
                  $item->time = date('Y-m-d H:i:s', $item->create_time);
              }
              $item->hidden(['create_time', 'exchange_time']);
          });
*/

//print_r($list);
//exit;

        $ym = 'https://' . $_SERVER['HTTP_HOST'];
        foreach ($order as $k => $v) {


            //  $order[$k]['box_tx']=$ym.$v['box_tx'];
            $order[$k]['box_img'] = explode(',', $v['box_img']);

            // foreach ($order[$k]['box_img'] as $k2=>$v2){

            //      $order[$k]['box_img'][$k2]=$ym.$v2;


            // }


            if (time() - $v['create_time'] < 60 * 60) {


                $t = round((time() - $v['create_time']) / 60);


                if ($t == 0) {
                    $t = 1;
                }

                $order[$k]['box_sj'] = $t . '分钟前';

            } else if (time() - $v['create_time'] > 60 * 60 && time() - $v['create_time'] < 60 * 60 * 24) {

                $t = round((time() - $v['create_time']) / 60 / 60);
                $order[$k]['box_sj'] = $t . '小时前';


            } else if (time() - $v['create_time'] > 60 * 60 * 24 && time() - $v['create_time'] < 60 * 60 * 24 * 7) {

                $t = round((time() - $v['create_time']) / 60 / 60 / 24);
                $order[$k]['box_sj'] = $t . '天前';


            } else if (time() - $v['create_time'] > 60 * 60 * 24 * 7) {

                $t = round((time() - $v['create_time']) / 60 / 60 / 24 / 7);
                $order[$k]['box_sj'] = $t . '周前';


            }


        }
//print_r($order);

        $list = array(


            'data' => $order
        );


//$list=$order;
        foreach ($list as $k => $v) {


            //  print_r($v);

        }
        $this->success('查询成功', $list);
    }


    /**
     * 最新开箱的盲盒列表
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function newestOpen()
    {
        // 查询数量
        $limit = 5;

        // 查询用户最新购买的100个盲盒ID
        $boxIds = Order::field('box_id')->order('id', 'desc')->limit(100)->column('box_id');

        //Array ( [0] => 36 [1] => 37 [2] => 38 [3] => 39 [4] => 40 [5] => 36 [6] => 36 [7] => 36 [8] => 36 [9] => 41 [10] => 39 [11] => 39 [12] => 36 [13] => 37 [14] => 41 [15] => 41 )


        $boxIds = array_unique($boxIds);

        $boxAdd = [];
        // 新开箱不足5个，则按盲盒上架顺序补齐
        if (count($boxIds) < $limit) {
            $boxAdd = Box::whereNotIn('id', $boxIds)->order('update_time', 'desc')->limit($limit - count($boxIds))->column('id');
        }
//Array ( [0] => 36 [1] => 37 [2] => 38 [3] => 39 [4] => 40 [5] => 41 )
        $boxIds = array_merge($boxIds, $boxAdd);

        // 查询空盲盒
        $existboxid = Detail::field('box_id')->distinct(true)->buildSql();
        $emptyBoxIds = Box::where('id', 'exp', 'not in ' . $existboxid)->column('id');

        $list = Box::alias('box')
            ->field('id box_id,box_name,coin_price,box_banner_images')
            ->whereNotIn('id', $emptyBoxIds)
            ->whereIn('id', $boxIds)
            ->order('id', 'desc')
            ->select();
//print_r($list);die;
        foreach ($list as $item) {
            // 查询前5个商品图片
            $firstGoods = Detail::where('box_id', $item->box_id)->order('weigh', 'desc')->limit(4)->column('goods_id');
            $goods_images = Goods::whereIn('id', $firstGoods)->column('image');
            foreach ($goods_images as &$image) {
                $image = cdnurl($image, true);
            }

            // 查询最低价
            $allGoods = Detail::where('box_id', $item->box_id)->column('goods_id');
            $item->goods_num = count($allGoods);

            $min_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'asc')->value('coin_price');
            $item->price_min = round(Setting::getRmbFromCoin($min_coin_price ?: 0), 2);

            $max_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'desc')->value('coin_price');
            $item->price_max = round(Setting::getRmbFromCoin($max_coin_price ?: 0), 2);

            $item->goods_images = $goods_images;
        }
//print_r($list);die;
        $this->success('查询成功', $list);
    }


    public function boximages()
    {
        $box_id = input('box_id');


        $tagName = [
            'normal' => '普通',
            'rare' => '稀有',
            'supreme' => '史诗',
            'legend' => '传说',
        ];
        // $firstGoods =  db('box_detail')->where('box_id', 49)->find();
        // 查询商品id及概率
        $detail = db('box_detail')->where('box_id', $box_id)->order('weigh', 'desc')->column('goods_id');


        // 查询全部商品
        $moreGoods = db('goods')->field('image')
            ->where('status', 'online')
            ->whereIn('id', $detail)
            ->select();


        $ret = [

            'goodsimagelist' => $moreGoods,

        ];


        $this->success('查询成功', $ret);
    }

    /**
     * 热门盲盒
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function hotBox()
    {
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);

        // 查询空盲盒
        $existboxid = Detail::field('box_id')->distinct(true)->buildSql();
        $emptyBoxIds = Box::where('id', 'exp', 'not in ' . $existboxid)->column('id');

        $list = Box::alias('box')
            ->field('id box_id,box_name,coin_price')
            ->where('is_hot', 1)
            ->whereNotIn('box.id', $emptyBoxIds)
            ->order('box.id', 'desc')
            ->paginate($pagesize, false, ['page' => $page])
            ->each(function ($item) {
                // 查询前6个商品图片
                $firstGoods = Detail::where('box_id', $item->box_id)->order('weigh', 'desc')->limit(6)->column('goods_id');
                $goods_images = Goods::whereIn('id', $firstGoods)->column('image');
                foreach ($goods_images as &$image) {
                    $image = cdnurl($image, true);
                }

                // 查询最低价
                $allGoods = Detail::where('box_id', $item->box_id)->column('goods_id');
                $item->goods_num = count($allGoods);

                $min_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'asc')->value('coin_price');
                $item->price_min = round(Setting::getRmbFromCoin($min_coin_price ?: 0), 2);

                $max_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'desc')->value('coin_price');
                $item->price_max = round(Setting::getRmbFromCoin($max_coin_price ?: 0), 2);

                $item->goods_images = $goods_images;
            });

        $ret = [
            'banner' => cdnurl(Setting::getSetting('hot_box_banner'), true),
            'list' => $list
        ];

        $this->success('查询成功', $ret);
    }

    /**
     * 低价盲盒
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function cheapBox()
    {
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);

        // 查询空盲盒
        $existboxid = Detail::field('box_id')->distinct(true)->buildSql();
        $emptyBoxIds = Box::where('id', 'exp', 'not in ' . $existboxid)->column('id');

        $list = Box::alias('box')
            ->field('id box_id,box_name,coin_price')
            ->where('is_cheap', 1)
            ->whereNotIn('box.id', $emptyBoxIds)
            ->order('box.id', 'desc')
            ->paginate($pagesize, false, ['page' => $page])
            ->each(function ($item) {
                // 查询前6个商品图片
                $firstGoods = Detail::where('box_id', $item->box_id)->order('weigh', 'desc')->limit(6)->column('goods_id');
                $goods_images = Goods::whereIn('id', $firstGoods)->column('image');
                foreach ($goods_images as &$image) {
                    $image = cdnurl($image, true);
                }

                // 查询最低价
                $allGoods = Detail::where('box_id', $item->box_id)->column('goods_id');
                $item->goods_num = count($allGoods);

                $min_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'asc')->value('coin_price');
                $item->price_min = round(Setting::getRmbFromCoin($min_coin_price ?: 0), 2);

                $max_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'desc')->value('coin_price');
                $item->price_max = round(Setting::getRmbFromCoin($max_coin_price ?: 0), 2);

                $item->goods_images = $goods_images;
            });

        $ret = [
            'banner' => cdnurl(Setting::getSetting('cheap_box_banner'), true),
            'list' => $list
        ];

        $this->success('查询成功', $ret);
    }

    /**
     * 推荐盲盒
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function recommend()
    {
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);

        // 查询空盲盒
        $existboxid = Detail::field('box_id')->distinct(true)->buildSql();
        $emptyBoxIds = Box::where('id', 'exp', 'not in ' . $existboxid)->column('id');

        $list = Box::alias('box')
            ->field('id box_id,box_name,coin_price,box_banner_images,box_foot_images')
            ->whereNotIn('id', $emptyBoxIds)
            ->order('sort', 'asc')
            ->where("switch", 1)
            ->paginate($pagesize, false, ['page' => $page])
            ->each(function ($item) {
                // 查询前6个商品图片
                // $firstGoods = Detail::where('box_id', $item->box_id)->order('weigh', 'desc')->limit(6)->column('goods_id');
                // $goods_images = Goods::whereIn('id', $firstGoods)->column('image');
                $goods_images = Detail::alias('a')->join("goods b", "b.id = a.goods_id")->where('a.box_id', $item->box_id)->order('a.weigh', 'desc')->limit(6)->column('b.image');

                foreach ($goods_images as &$image) {
                    $image = cdnurl($image, true);
                }

                // 查询最低价
                $allGoods = Detail::where('box_id', $item->box_id)->column('goods_id');
                $item->goods_num = count($allGoods);

                $min_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'asc')->value('coin_price');
                $item->price_min = round(Setting::getRmbFromCoin($min_coin_price ?: 0), 2);

                $max_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'desc')->value('coin_price');
                $item->price_max = round(Setting::getRmbFromCoin($max_coin_price ?: 0), 2);

                $item->goods_images = $goods_images;
                $box_banner_images = explode(',', $item->box_banner_images);
                foreach ($box_banner_images as &$v) {
                    $v = cdnurl($v, true);
                }
                $item->box_banner_images = $box_banner_images;
                $box_foot_images = explode(',', $item->box_foot_images);
                foreach ($box_foot_images as &$v) {
                    $v = cdnurl($v, true);
                }
                $item->box_foot_images = $box_foot_images;
            });

        $this->success('查询成功', $list);
    }

    /**
     * 分类列表
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function categoryList()
    {
        $list = Category::field('id category_id,name')->order('weigh', 'desc')->select();
        $this->success('查询成功', $list);
    }

    /**
     * 盲盒列表
     * @throws \think\exception\DbException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function boxListByCategory()
    {
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);
        $category_id = input('category_id/d');
        $search = input('search', '');
        $sort = input('sort', '');
        $price = input('price', '');

        // 构建筛选条件
        $wherePrice = [];
        if ($price) {
            list($price_low, $price_heigh) = array_slice(explode('-', $price), 0, 2);
            if (!is_numeric($price_low) || !is_numeric($price_heigh)) {
                $this->error('价格筛选有误');
            }
            $wherePrice = ['coin_price' => ['between', [$price_low, $price_heigh]]];
        }

        // 构建排序条件
        $order = "";
        switch ($sort) {
            case '':
                $order = "id desc";
                break;
            case 'new':
                $order = "id desc";
                break;
            case 'combine_desc':
                $order = "sales desc";
                break;
            case 'combine_asc':
                $order = "sales asc";
                break;
            case 'price_desc':
                $order = "coin_price desc";
                break;
            case 'price_asc':
                $order = "coin_price asc";
                break;
            default:
                $this->error('排序方式有误');
                break;
        }

        if (empty($category_id) && empty($search)) {
            $this->error('查询条件有误');
        }

        $whereCategory = [];
        if (!empty($category_id)) {
            $whereCategory = ['category_id' => $category_id];
        }

        $whereSearch = [];
        if (!empty($search)) {
            // 过滤非法字符
            $search = preg_replace("/[!@#$%^&*=\-+_\[\]{};':\"\/<>?]+/", '', $search);

            // 创建搜索记录
            if ($this->auth->isLogin()) {
                if (!SearchHistory::where(['user_id' => $this->auth->id, 'search' => $search])->value('id')) {
                    SearchHistory::create(['user_id' => $this->auth->id, 'search' => $search]);
                }
            }

            $whereSearch = "box_name like '%{$search}%'";
        }

        // 查询空盲盒
        $existboxid = Detail::field('box_id')->distinct(true)->buildSql();
        $emptyBoxIds = Box::where('id', 'exp', 'not in ' . $existboxid)->column('id');

        $list = Box::field('id box_id,box_name,coin_price,box_banner_images')
            ->order($order)
            ->whereNotIn('id', $emptyBoxIds)
            ->where($wherePrice)
            ->where($whereCategory)
            ->where($whereSearch)
            ->paginate($pagesize, false, ['page' => $page])
            ->each(function ($item) {
                // 查询第一张图片
                $goodsid = Detail::order('weigh', 'desc')->where('box_id', $item->box_id)->value('goods_id');
                $item->image = '';
                if ($goodsid) {
                    $image = Goods::where('id', $goodsid)->value('image');
                    $item->image = $image ? cdnurl($image, true) : '';
                }
            });

        $this->success('查询成功', $list);
    }

    /**
     * 搜索
     * @throws DbException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function search()
    {
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);
        $category_id = input('category_id/d');
        $search = input('search', '');
        $sort = input('sort', '');
        $price = input('price', '');

        // 构建筛选条件
        $wherePrice = [];
        if ($price) {
            list($price_low, $price_heigh) = array_slice(explode('-', $price), 0, 2);
            if (!is_numeric($price_low) || !is_numeric($price_heigh)) {
                $this->error('价格筛选有误');
            }
            $wherePrice = ['coin_price' => ['between', [$price_low, $price_heigh]]];
        }

        // 构建排序条件
        $order = "";
        switch ($sort) {
            case '':
                $order = "id desc";
                break;
            case 'new':
                $order = "id desc";
                break;
            case 'combine_desc':
                $order = "sales desc";
                break;
            case 'combine_asc':
                $order = "sales asc";
                break;
            case 'price_desc':
                $order = "coin_price desc";
                break;
            case 'price_asc':
                $order = "coin_price asc";
                break;
            default:
                $this->error('排序方式有误');
                break;
        }

        $whereCategory = [];
        if (!empty($category_id)) {
            $whereCategory = ['category_id' => $category_id];
        }

        $whereSearch = [];
        if (!empty($search)) {
            // 过滤非法字符
            $search = preg_replace("/[!@#$%^&*=\-+_\[\]{};':\"\/<>?]+/", '', trim($search));
            if (!empty($search)) {
                // 创建搜索记录
                if ($this->auth->isLogin()) {
                    if (!SearchHistory::where(['user_id' => $this->auth->id, 'search' => $search])->value('id')) {
                        SearchHistory::create(['user_id' => $this->auth->id, 'search' => $search]);
                    }
                }

                // 构建商品ID搜索
                $condition_goods_ids = Goods::field('id')->where('status', 'online')->where("goods_name like '%{$search}%'")->buildSql();

                // 构建商品、盲盒绑定
                $condition_box_detail = Detail::field('box_id')->where("goods_id in {$condition_goods_ids}")->buildSql();

                $whereSearch = "box_name like '%{$search}%' or id in $condition_box_detail";
            }

        }

        // 查询空盲盒
        $existboxid = Detail::field('box_id')->distinct(true)->buildSql();
        $emptyBoxIds = Box::where('id', 'exp', 'not in ' . $existboxid)->column('id');

        $list = Box::alias('box')
            ->field('id box_id,box_name,coin_price,box_banner_images')
            ->whereNotIn('id', $emptyBoxIds)
            ->where($wherePrice)
            ->where($whereCategory)
            ->where($whereSearch)
            ->where(['switch' => 1])
            ->order($order)
            ->paginate($pagesize, false, ['page' => $page])
            ->each(function ($item) {
                // 查询前6个商品图片
                $firstGoods = Detail::where('box_id', $item->box_id)->order('weigh', 'desc')->limit(6)->column('goods_id');
                $goods_images = Goods::whereIn('id', $firstGoods)->column('image');
                foreach ($goods_images as &$image) {
                    $image = cdnurl($image, true);
                }

                // 查询最低价
                $allGoods = Detail::where('box_id', $item->box_id)->column('goods_id');
                $item->goods_num = count($allGoods);

                $min_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'asc')->value('coin_price');
                $item->price_min = round(Setting::getRmbFromCoin($min_coin_price ?: 0), 2);

                $max_coin_price = Goods::whereIn('id', $allGoods)->order('coin_price', 'desc')->value('coin_price');
                $item->price_max = round(Setting::getRmbFromCoin($max_coin_price ?: 0), 2);

                $item->goods_images = $goods_images;
            });


        $this->success('查询成功', $list);
    }

    /**
     * 盲盒详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function boxDetail()
    {
        $box_id = input('box_id/d');
        if (empty($box_id)) {
            $this->error('请选择盲盒');
        }

        // 查询金币余额
        $mycoin = $this->auth->isLogin() ? $this->auth->coin : 0;

        // 查询是否收藏
        $is_star = $this->auth->isLogin() ? Star::check($this->auth->id, $box_id) : 0;

        // 查询盲盒基础信息
        $box = Box::field('box_banner_images,box_banner_images_desc,box_name,coin_price,box_banner_images')->where('id', $box_id)->find();
        if (empty($box)) {
            $this->error('盲盒有误');
        }

        $tagName = [
            'normal' => '普通',
            'rare' => '稀有',
            'supreme' => '史诗',
            'legend' => '传说',
        ];

        // 查询商品id及概率
        $detail = Detail::where('box_id', $box_id)->order('weigh desc')->column('rate', 'goods_id');

        // // 查询前6个商品
        // $firstGoods = Goods::field('image,coin_price,goods_name,tag')
        //     ->where('status', 'online')
        //     ->whereIn('id', array_slice(array_keys($detail), 0, 1000))
        //     ->select();

        $firstGoods = Detail::alias("a")->join("goods b", "b.id = a.goods_id")->where('a.box_id', $box_id)->field("b.image,b.xiangqing,b.coin_price,b.goods_name,b.tag")->order("a.weigh desc")->select();

        foreach ($firstGoods as &$first) {
            $first->image = $first->image ? cdnurl($first->image, true) : $first->image;
            $first->tag = $tagName[$first->tag];
            // $first->price = round(Setting::getRmbFromCoin($first->coin_price ?: 0), 2);
            $first->price = $first->coin_price;
            if (!empty($first->xiangqing)) {
                if (strstr($first['xiangqing'], ',')) {
                    $first['xiangqing'] = explode(',', $first['xiangqing']);
                    // var_dump($first);
                    // exit();

                }
            }

            $first->hidden(['coin_price']);
        }
        // var_dump($first);exit();

        // 查询全部商品
        $moreGoods = Goods::field('id,image,xiangqing,coin_price,goods_name,tag')
            ->where('status', 'online')
            ->whereIn('id', array_keys($detail))
            ->select();

        // 整理商品信息并记录每个类别的概率总合
        $rateList = [];
        foreach ($moreGoods as &$more) {
            if (isset($rateList[$more->tag])) {
                $rateList[$more->tag] += $detail[$more->id];
            } else {
                $rateList[$more->tag] = $detail[$more->id];
            }
            $more->image = $more->image ? cdnurl($more->image, true) : $more->image;
            $more->tag = $tagName[$more->tag];
            $more->price = round(Setting::getRmbFromCoin($more->coin_price ?: 0), 2);
            if (strstr($more->xiangqing, ',')) {
                $more->xiangqing = explode(',', $more->xiangqing);

            }
            $more->hidden(['id,coin_price']);
        }

        $tags = [
            'normal' => 0,
            'rare' => 0,
            'supreme' => 0,
            'legend' => 0
        ];
        // 没有的商品概率设为0
        foreach ($tags as $tag => &$rate) {
            if (isset($rateList[$tag])) {
                $rate = $rateList[$tag];
            }
        }

        // 计算全部类别概率总和
        $rate_sum = array_sum(array_values($tags));
        // 计算每个类别概率
        foreach ($tags as $tag => &$rate) {
            $rate = $rate_sum ? (round($rate / $rate_sum, 4) * 100) : 0 . '%';
        }

        // 查询该盲盒开箱记录
        $prize = Prizerecord::alias('prize')
            ->field('prize.goods_name,prize.goods_image,prize.goods_rmb_price,prize.create_time')
            ->field('user.nickname,user.avatar')
            ->join('user user', 'user.id = prize.user_id')
            ->where('prize.box_id', $box_id)
            ->order('prize.id', 'desc')
            ->limit(10)
            ->select();

        foreach ($prize as $prize_item) {
            $prize_item->create_time = date('Y-m-d H:i:s', $prize_item->create_time);
            $prize_item->avatar = $prize_item->avatar ? cdnurl($prize_item->avatar, true) : letter_avatar($prize_item->nickname);
            $prize_item->goods_image = $prize_item->goods_image ? cdnurl($prize_item->goods_image, true) : '';
        }

        $box_banner_images = [];
        $box_banner = [];
        $box->box_banner_images = explode(',', $box->box_banner_images);
        $banner_desc = $box->box_banner_images_desc;
        $banner_desc = $banner_desc ? json_decode($banner_desc, true) : [];
        foreach ($box->box_banner_images as $index => $image) {
            $image = $image ? cdnurl($image, true) : '';
            $box_banner_images[] = $image;
            $box_banner[] = [
                'desc' => $banner_desc[$index] ?? '',
                'image' => $image
            ];
        }

        $ret = [
            'mycoin' => $mycoin,
            'is_star' => $is_star,
            'box_banner_images' => $box_banner_images,
            'box_banner' => $box_banner,
            'box_name' => $box->box_name,
            'coin_price' => intval($box->coin_price),
            'goodslist' => $firstGoods,
            'more' => [
                'goodslist' => $moreGoods,
                'tags' => $tags
            ],
            'record' => $prize
        ];

        $this->success('查询成功', $ret);
    }

    /**
     * 查询更多盲盒开箱记录
     * @throws DbException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function boxOpenRecord()
    {
        $box_id = input('box_id/d');
        $pagesize = input('pagesize/d', 10);
        $page = input('page/d', 1);

        if (empty($box_id)) {
            $this->error('请选择盲盒');
        }

        // 查询该盲盒开箱记录
        $record = Prizerecord::alias('prize')
            ->field('prize.goods_name,prize.goods_image,prize.goods_rmb_price,prize.create_time')
            ->field('user.nickname,user.avatar')
            ->join('user user', 'user.id = prize.user_id')
            ->where('prize.box_id', $box_id)
            ->order('prize.id', 'desc')
            ->paginate($pagesize, false, ['page' => $page])
            ->each(function ($item) {
                $item->create_time = date('Y-m-d H:i:s', $item->create_time);
                $item->avatar = $item->avatar ? cdnurl($item->avatar, true) : letter_avatar($item->nickname);
                $item->goods_image = $item->goods_image ? cdnurl($item->goods_image, true) : '';
            });

        $this->success('查询成功', $record);
    }

    /**
     * 试一试盲盒详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function tryBoxDetail()
    {
        // 查询试一试盲盒
        $box_id = Box::where('is_try', 1)->value('id');

        // 查询金币余额
        $mycoin = $this->auth->isLogin() ? $this->auth->coin : 0;

        // 查询是否收藏
        $is_star = $this->auth->isLogin() ? Star::check($this->auth->id, $box_id) : 0;

        // 查询盲盒基础信息
        $box = Box::field('box_banner_images,box_name,coin_price')->where('id', $box_id)->find();
        if (empty($box)) {
            $this->error('盲盒有误');
        }

        $tagName = [
            'normal' => '普通',
            'rare' => '稀有',
            'supreme' => '史诗',
            'legend' => '传说',
        ];

        // 查询商品id及概率
        $detail = Detail::where('box_id', $box_id)->order('weigh', 'desc')->column('rate', 'goods_id');

        // 查询前6个商品
        $firstGoods = Goods::field('image,coin_price,goods_name,tag')
            ->where('status', 'online')
            ->whereIn('id', array_slice(array_keys($detail), 0, 6))
            ->select();
        foreach ($firstGoods as &$first) {
            $first->image = $first->image ? cdnurl($first->image, true) : $first->image;
            $first->tag = $tagName[$first->tag];
            $first->price = round(Setting::getRmbFromCoin($first->coin_price ?: 0), 2);
            $first->hidden(['coin_price']);
        }

        // 查询全部商品
        $moreGoods = Goods::field('id,image,coin_price,goods_name,tag')
            ->where('status', 'online')
            ->whereIn('id', array_keys($detail))
            ->select();

        // 整理商品信息并记录每个类别的概率总合
        $rateList = [];
        foreach ($moreGoods as &$more) {
            if (isset($rateList[$more->tag])) {
                $rateList[$more->tag] += $detail[$more->id];
            } else {
                $rateList[$more->tag] = $detail[$more->id];
            }
            $more->image = $more->image ? cdnurl($more->image, true) : $more->image;
            $more->tag = $tagName[$more->tag];
            $more->price = round(Setting::getRmbFromCoin($more->coin_price ?: 0), 2);
            $more->hidden(['id,coin_price']);
        }

        $tags = [
            'normal' => 0,
            'rare' => 0,
            'supreme' => 0,
            'legend' => 0
        ];
        // 没有的商品概率设为0
        foreach ($tags as $tag => &$rate) {
            if (isset($rateList[$tag])) {
                $rate = $rateList[$tag];
            }
        }

        // 计算全部类别概率总和
        $rate_sum = array_sum(array_values($tags));
        // 计算每个类别概率
        foreach ($tags as $tag => &$rate) {
            $rate = round($rate / $rate_sum, 4) * 100 . '%';
        }

        // 查询该盲盒开箱记录
        $prize = Prizerecord::alias('prize')
            ->field('prize.goods_name,prize.goods_image,prize.goods_rmb_price,prize.create_time')
            ->field('user.nickname,user.avatar')
            ->join('user user', 'user.id = prize.user_id')
            ->where('prize.box_id', $box_id)
            ->order('prize.id', 'desc')
            ->limit(3)
            ->select();

        foreach ($prize as $prize_item) {
            $prize_item->create_time = date('Y-m-d H:i:s', $prize_item->create_time);
            $prize_item->avatar = $prize_item->avatar ? cdnurl($prize_item->avatar, true) : letter_avatar($prize_item->nickname);
            $prize_item->goods_image = $prize_item->goods_image ? cdnurl($prize_item->goods_image, true) : '';
        }

        $box_banner_images = [];
        $box->box_banner_images = explode(',', $box->box_banner_images);
        foreach ($box->box_banner_images as $box_banner_image) {
            $box_banner_images[] = cdnurl($box_banner_image, true);
        }

        $ret = [
            'box_id' => $box_id,
            'mycoin' => $mycoin,
            'is_star' => $is_star,
            'box_banner_images' => $box_banner_images,
            'box_name' => $box->box_name,
            'coin_price' => intval($box->coin_price),
            'goodslist' => $firstGoods,
            'more' => [
                'goodslist' => $moreGoods,
                'tags' => $tags
            ],
            'record' => $prize
        ];

        $this->success('查询成功', $ret);
    }

    /**
     * 抽奖测试
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function test()
    {
        $prize = [];
        $times = $index = 1000;

        while (--$index >= 0) {
            $p = Detail::getOne(1);
            if (isset($prize[$p])) {
                $prize[$p]++;
            } else {
                $prize[$p] = 1;
            }
        }
        foreach ($prize as $goods => &$rate) {
            $rate = round($rate / $times, 2) * 100;
        }
        arsort($prize);
        de($prize);
    }

    /**
     * 点赞
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function star()
    {
        $box_id = input('box_id/d');
        try {
            $res = Star::click($this->auth->id, $box_id);
        } catch (Exception $e) {
            $this->error('收藏失败');
        }

        if ($res) {
            $this->success('收藏成功', ['is_star' => 1]);
        }

        $this->success('取消收藏成功', ['is_star' => 0]);
    }

    /**
     * 试玩
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function haveATry()
    {
        $box_id = input('box_id/d');
        $num = input('num/d');
        $select = input('select', '随机');

        if (empty($box_id)) {
            $this->error('请选择盲盒');
        }
        if (!in_array($num, [1, 5])) {
            $this->error('开箱数量有误');
        }

        // 检查盲盒是否可以试玩
        // $box = Box::where('id', $box_id)->where('is_try', 1)->value('id');
        // if (empty($box)) {
        //     $this->error('该盲盒暂时不可试玩');
        // }


        try {
            if (1 == $num) {
                $goodsIds = [Detail::getOnes($box_id)];


            } else {
                $goodsIds = Detail::getMores($box_id, $num);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        foreach ($goodsIds as $goodsId) {
            $goodsInfo[] = Goods::field('image,goods_name,tag')->where('id', $goodsId)->find();
        }

        if (empty($goodsInfo)) {
            $this->error('抽奖失败');
        }

        foreach ($goodsInfo as $item) {
            if ($item->image) {
                $item->image = cdnurl($item->image, true);
            }
        }

        $ret = [
            'select' => $select,
            'goodsInfo' => $goodsInfo
        ];
        $this->success('抽奖成功', $ret);

    }

    /**
     * 创建盲盒订单
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function createOrder()
    {
        $box_id = input('box_id/d');
        $num = input('num/d');
        $select = input('select', '');

        if (empty($box_id)) {
            $this->error('未选择盲盒');
        }

        if (!in_array($num, [1, 5, 9])) {
            $this->error('选择的盲盒数量有误');
        }

        // 检查盲盒
        $box = Box::field('id,box_name,box_banner_images,coin_price,box_banner_images')->where('id', $box_id)->find();
        if (empty($box)) {
            $this->error('选择的盲盒有误');
        }

        // 检查盲盒奖品
        $prize = Detail::where('box_id', $box_id)->order('weigh desc,id asc')->value('goods_id');
        if (empty($prize)) {
            $this->error('这个盲盒太火爆吧，商品暂时缺货！');
        }

        // 查询前6个商品的图片
        $goodsIds = Detail::where('box_id', $box_id)->order('weigh desc,id asc')->column('goods_id');
        $goodsImages = Goods::where('status', 'online')
            ->whereIn('id', $goodsIds)
            ->column('image');
        foreach ($goodsImages as &$image) {
            $image = cdnurl($image, true);
        }

        Db::startTrans();
        try {

            $rmb_price = round(Setting::getRmbFromCoin($box->coin_price ?: 0), 2);
            $res = Order::create([
                'box_id' => $box_id,
                'box_name' => $box->box_name,
                'image' => $goodsImages[0] ?? '',
                'coin_price' => $box->coin_price,
                'rmb_price' => $rmb_price,
                'num' => $num,
                'coin_amount' => $box->coin_price * $num,
                'rmb_amount' => $rmb_price * $num,
                'user_id' => $this->auth->id,
                'select' => $select,
                'out_trade_no' => date('YmdHis') . mt_rand(10000, 99999)
            ]);

            $ret = [
                'order_id' => intval($res->id),
                'box_name' => $res->box_name,
                'images' => $goodsImages,
                'coin_amount' => $res->coin_amount,
                'rmb_amount' => $res->rmb_amount,
                'notice' => Text::getText('pay_tipstips'),
                'coin_not_enough' => !!(intval($this->auth->coin) < intval($res->coin_amount)),
                'alipay' => $this->request->domain() . '/api/alipay/boxpay/orderid/' . intval($res->id),
                'wechat' => '/api/wechat/boxpay/orderid/' . intval($res->id),
            ];
        } catch (Exception $e) {
            Db::rollback();
            $this->error('创建订单失败');
        }
        Db::commit();

        $this->success('创建订单成功', $ret);
    }

    /**
     * 创建充值订单
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function createRechargeOrder()
    {
        $amount = input('amount/d');
        if (empty($amount)) {
            $this->error('金额不能为空');
        }

        // 检查金额是否允许
        $rmb = RechargeList::where('coin', intval($amount))->value('rmb');
        if (empty($rmb)) {
            $this->error('充值金额有误');
        }

        Db::startTrans();
        try {
            $res = RechargeOrder::create([
                'user_id' => $this->auth->id,
                'coin_amount' => intval($amount),
                'rmb_amount' => round($rmb, 2),
                'out_trade_no' => date('YmdHis') . mt_rand(10000, 99999)
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('创建订单出错');
        }

        Db::commit();

        $ret = [
            'alipay' => $this->request->domain() . '/api/alipay/rechargepay/orderid/' . intval($res->id),
            'wechat' => '/api/wechat/rechargepay/orderid/' . intval($res->id),
            'eepay' => '/api/eepay/rechargepay/orderid/' . intval($res->id),
        ];

        $this->success('创建订单成功', $ret);
    }

    /**
     * 创建充值订单
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function createRechargeOrder_bak()
    {
        $amount = input('amount/d');
        if (empty($amount)) {
            $this->error('金额不能为空');
        }

        // 检查金额是否允许
        $rmb = RechargeList::where('coin', intval($amount))->value('rmb');
        if (empty($rmb)) {
            $this->error('充值金额有误');
        }

        Db::startTrans();
        try {
            $res = RechargeOrder::create([
                'user_id' => $this->auth->id,
                'coin_amount' => intval($amount),
                'rmb_amount' => round($rmb, 2),
                'out_trade_no' => date('YmdHis') . mt_rand(10000, 99999)
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('创建订单出错');
        }

        Db::commit();

        $ret = [
            'alipay' => $this->request->domain() . '/api/alipay/rechargepay/orderid/' . intval($res->id),
            'wechat' => '/api/wechat/rechargepay/orderid/' . intval($res->id),
        ];

        $this->success('创建订单成功', $ret);
    }

    /**
     * 金币支付
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function coinPay()
    {
        $order_id = input('order_id/d');
        if (empty($order_id)) {
            $this->error('请选择支付订单');
        }
        $order = Order::field('id,box_id,num,status,coin_amount,out_trade_no,select')
            ->where('id', $order_id)
            ->where('user_id', $this->auth->id)
            ->find();
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ('unpay' != $order->status) {
            $this->error('该订单已支付，请勿重复支付');
        }
        // 查询用户余额
        if (intval($this->auth->coin) < $order->coin_amount) {
            $this->error('您的金币不足');
        }
        Db::startTrans();
        try {
            // 更新订单信息
            $order->pay_method = 'coin';
            $order->pay_coin = $order->coin_amount;
            $order->pay_time = time();
            $order->status = 'unused';// 状态:unpay=待支付,unused=待抽奖,used=已使用
            $order->backend_read = 0;
            $order->save();

            $coin_before = $this->auth->coin;

            // 减少金币余额
            $user = $this->auth->getUser();
            $user->setDec('coin', $order->pay_coin);

            // 创建金币使用记录
            CoinRecord::create([
                'user_id' => $this->auth->id,
                'before' => $coin_before,
                'after' => $this->auth->coin,
                'coin' => -$order->pay_coin,
                'order_id' => $order->id,
                'type' => 'pay_box', // 变更类型:pay_box=支付盲盒,recharge=充值,fromwallet=余额转入
            ]);
            $users = Db::table('box_user')->where('id', $this->auth->pid)->find();

            $orderadd = Order::where('id', $order_id)->where('user_id', $this->auth->id)->find();
            $lou = Db::table('box_setting')->where('id', 1)->find();
            $kou = $lou['kou'];
            if ($users['recharnum'] == 1) {
                Db::table('box_user')->where('id', $users['id'])->setInc("recharnum", 1);
                Retail::giveMoneys($orderadd);

            } else {
                Db::table('box_user')->where('id', $users['id'])->setInc("recharnum", 1);
                $userarr = Db::table('box_user')->where('id', $users['id'])->find();
                if (bcmod($userarr['recharnum'], $kou) == 0) {
                } else {
                    Retail::giveMoneys($orderadd);
                };
            }

            //      print_r(bcmod($users['recharnum'],$kou);

        } catch (\Exception $e) {
            Db::rollback();
            dta('用户支付失败，订单已回滚到待支付');
            $this->error('支付失败');
        }

        Db::commit();

        // 开箱
        $prize = $this->open($order);

        $this->success('支付成功', ['prize' => $prize]);
    }


    /**
     * 余额支付
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function cmoneyPay()
    {
        $order_id = input('order_id/d');
        if (empty($order_id)) {
            $this->error('请选择支付订单');
        }
        $order = Order::field('id,box_id,num,status,rmb_amount,out_trade_no,select')
            ->where('id', $order_id)
            ->where('user_id', $this->auth->id)
            ->find();
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ('unpay' != $order->status) {
            $this->error('该订单已支付，请勿重复支付');
        }
        // 查询用户余额
        if (intval($this->auth->money) < $order->rmb_amount) {
            $this->error('您的余额不足');
        }
        Db::startTrans();
        try {
            // 更新订单信息
            $order->pay_method = 'money';
            $order->rmb_amount = $order->rmb_amount;
            $order->pay_time = time();
            $order->status = 'unused';// 状态:unpay=待支付,unused=待抽奖,used=已使用
            $order->backend_read = 0;
            $order->save();

            $coin_before = $this->auth->money;

            // 减少余额
            $user = $this->auth->getUser();
            $user->setDec('money', $order->rmb_amount);


            // 创建余额使用记录
            MoneyRecord::create([
                'user_id' => $this->auth->id,
                'before' => $this->auth->money,
                'after' => $this->auth->money - $order->rmb_amount,
                'money' => -$order->rmb_amount,
                'order_id' => $order->id,
                'type' => 'yezhifu', // 变更类型:box_exchange=盲盒回收,refund=库存不足，支付返回,withdrawal=提现,to_coin=转到钱包，withdrawal_fail=提现失败,yezhifu=余额支付
            ]);
            // $users= Db::table('box_user') ->where('id',$this->auth->pid)->find();

            //  $orderadd = Order::where('id', $order_id)->where('user_id', $this->auth->id)->find();
            //  $lou = Db::table('box_setting')->where('id', 1)->find();
            //  $kou = $lou['kou'];
            //     if($users['recharnum'] == 1){
            //         Db::table('box_user') ->where('id',$users['id'])->setInc("recharnum", 1);
            //      Retail::giveMoneys($orderadd);

            //   }else{
            //       Db::table('box_user') ->where('id',$users['id'])->setInc("recharnum", 1);
            //       $userarr= Db::table('box_user') ->where('id',$users['id'])->find();
            //     //   if(bcmod($userarr['recharnum'],$kou) == 0){
            //     //   }else{
            //     //       Retail::giveMoneys($orderadd);
            //     //   };
            //   }

            //      print_r(bcmod($users['recharnum'],$kou);

        } catch (\Exception $e) {
            Db::rollback();
            dta('用户支付失败，订单已回滚到待支付');
            $this->error('支付失败');
        }

        Db::commit();

        // 开箱
        $prize = $this->open($order);

        $this->success('支付成功', ['prize' => $prize]);
    }

    /**
     * 价格区间
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function priceRange()
    {
        $list = PriceRange::order('weigh desc,id asc')->column('range');
        $this->success('查询成功', ['range' => $list]);
    }

    /**
     * 充值列表
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function rechargeList()
    {
        $coinList = RechargeList::order('weigh desc,id desc')->column('coin,rmb', 'id');

        $list = [];
        foreach ($coinList as $item) {
            $list[] = [
                'coin' => $item['coin'],
                'rmb' => floatval($item['rmb'])
            ];
        }
        $num = Setting::getSetting('one_rmb_to_coin_num');
        $ret = [
            'tips' => '充值金额数值比例1：' . round(Setting::getSetting('one_rmb_to_coin_num'), 2),
            'list' => $list,
            'bili' => $num,
            'notice' => Text::getText('recharge_introduction')
        ];

        $this->success('查询成功', $ret);
    }

    /**
     * 开箱
     * @param Order $order 订单
     * @return array|bool
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    private function open(Order $order)
    {
        // 检查订单状态
        if ('unused' != $order->status) { // 状态:unpay=待支付,unused=待抽奖,used=已使用
            return false;
        }

        if (empty($order->box_id)) {
            $this->error('请选择盲盒');
        }
        if (!in_array($order->num, [1, 5, 9])) {
            $this->error('开箱数量有误');
        }

        // 检查盲盒是否可以试玩
        $box = Box::where('id', $order->box_id)->value('id');
        if (empty($box)) {
            $this->error('盲盒有误');
        }

        try {
            // 抽奖 begin
            if (1 == $order->num) {
                $goodsIds = [Detail::getOne($order->box_id)];


            } else {
                $goodsIds = Detail::getMore($order->box_id, $order->num);
            }
        } catch (\Exception $e) {

            // 退款
            if (!$this->refund($order)) {
                $logID = "";
                try {
                    $logID = dta($order->toArray(), '用户退款失败');
                } catch (Exception $e) {
                    $logID = dta(['order_id' => $order->id], '用户退款失败');
                }
                $this->error('库存不足退款失败,请截屏联系平台:' . $logID);
            }

            $this->error('抽奖失败，已退款');
        }
        // 抽奖 end

        // 查询抽中的奖品信息
        foreach ($goodsIds as $goodsId) {
            $goodsInfo[] = Goods::field('id,image,tag,coin_price,goods_name,delivery_fee')->where('id', $goodsId)->find();
        }

        // 抽奖失败
        if (empty($goodsInfo)) {

            // 退款
            if (!$this->refund($order)) {
                $logID = "";
                try {
                    $logID = dta($order->toArray(), '用户退款失败');
                } catch (Exception $e) {
                    $logID = dta(['order_id' => $order->id], '用户退款失败');
                }
                $this->error('库存不足退款失败,请截屏联系平台:' . $logID);
            }

            $this->error('抽奖失败，已退款');
        }

        $prizeInfo = [];

        Db::startTrans();
        try {
            foreach ($goodsInfo as &$goods) {

                // 创建开箱记录
                $prize = Prizerecord::create([
                    'box_id' => $order->box_id,
                    'order_id' => $order->id,
                    'out_trade_no' => $order->out_trade_no,
                    'user_id' => $this->auth->id,
                    'goods_id' => $goods->id,
                    'goods_name' => $goods->goods_name,
                    'goods_image' => $goods->image,
                    'goods_coin_price' => $goods->coin_price,
                    'goods_rmb_price' => round(Setting::getRmbFromCoin($goods->coin_price ?: 0), 2),
                    'delivery_fee' => round($goods->delivery_fee, 2),
                    'status' => 'bag', // 奖品状态:bag=盒柜,exchange=已回收,delivery=申请发货,received=已收货
                ]);

                // 减少商品库存
                Goods::where('id', $goods->id)->setDec('stock');

                $prizeInfo[] = [
                    'prize_id' => intval($prize->id),
                    'image' => $prize->goods_image ? cdnurl($prize->goods_image, true) : '',
                    'goods_name' => $prize->goods_name,
                    'tag' => $goods->tag
                ];
            }

            // 增加盲盒销量
            Box::where('id', $order->box_id)->setInc('sales', $order->num);

        } catch (\Exception $e) {
            dta(['order_id' => $order->id, 'error' => $e->getMessage()], '保存开箱记录、减少商品库存失败');
            Db::rollback();

            // 退款
            if (!$this->refund($order)) {
                $logID = "";
                try {
                    $logID = dta($order->toArray(), '用户退款到金币失败');
                } catch (Exception $e) {
                    $logID = dta(['order_id' => $order->id], '用户退款失败');
                }
                $this->error('库存不足退款失败,请截屏联系平台:' . $logID);
            }

            $this->error('抽奖失败，已退款');
        }

        Db::commit();

        // 订单状态改为已使用
        $order->save(['status' => 'used', 'backend_read' => 0]);

        $ret = [
            'select' => $order->select,
            'prizeInfo' => $prizeInfo
        ];

        return $ret;
    }

    /**
     * 通过订单号打开盲盒
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function openByOrderTrade()
    {
        $out_trade_no = input('out_trade_no');
        $order_id = input('order_id');
        if (empty($out_trade_no) && empty($order_id)) {
            $this->error('参数有误');
        }
        $where = [];
        if (!empty($out_trade_no)) {
            $where['out_trade_no'] = $out_trade_no;
        }
        if (!empty($order_id)) {
            $where['id'] = $order_id;
        }
        $order = Order::where($where)->where('user_id', $this->auth->id)->where('status', 'unused')->find();
        if (empty($order)) {
            $this->error('订单有误');
        }

        // 开箱
        $prize = $this->open($order);

        $this->success('开箱成功', ['prize' => $prize]);
    }

    /**
     * 退款自动选择
     * @param Order $order
     * @return bool
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    private function refund(Order $order)
    {
        switch ($order->pay_method) {
            case 'coin' :
                return $this->refundToCoin($order);
                break;
            case 'wechat':
                return $this->refundToMoney($order);
                break;
            case 'alipay':
                return $this->refundToMoney($order);
                break;
            default:
                return false;
        }
    }

    /**
     * 退款到金币
     * @param Order $order 订单
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    private function refundToCoin(Order $order)
    {
        $coin_before = $this->auth->coin;

        Db::startTrans();

        try {
            // 增加金币余额
            $user = $this->auth->getUser();
            $user->setInc('coin', $order->pay_coin);

            // 创建金币记录
            CoinRecord::create([
                'user_id' => $this->auth->id,
                'before' => $coin_before,
                'after' => $this->auth->coin,
                'coin' => $order->pay_coin,
                'order_id' => $order->id,
                'type' => 'refund', // 变更类型:pay_box=支付盲盒,recharge=充值,fromwallet=余额转入,refund=退款
            ]);

            // 更新订单状态为已退款
            $order->save(['status' => 'refund', 'backend_read' => 0]);
        } catch (\Exception $e) {
            dta(['order_id' => $order->id, 'error' => $e->getMessage()], '用户退款到金币失败');
            Db::rollback();
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 退款到余额
     * @param Order $order 订单
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    private function refundToMoney(Order $order)
    {
        $money_before = $this->auth->money;

        Db::startTrans();

        try {
            // 增加金币余额
            $user = $this->auth->getUser();
            $user->setInc('money', $order->pay_rmb);

            // 创建余额记录
            MoneyRecord::create([
                'user_id' => $this->auth->id,
                'before' => $money_before,
                'after' => $this->auth->money,
                'money' => $order->pay_rmb,
                'order_id' => $order->id,
                'type' => 'refund', // 变更类型:box_exchange=盲盒回收,refund=库存不足，支付返回,withdrawal=提现,to_coin=转到钱包，withdrawal_fail=提现失败
            ]);

            // 更新订单状态为已退款
            $order->save(['status' => 'refund', 'backend_read' => 0]);
        } catch (\Exception $e) {
            dta(['order_id' => $order->id, 'error' => $e->getMessage()], '用户退款到余额失败');
            Db::rollback();
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 获取客服信息
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function getServiceInfo()
    {
        $ret = [
            'number' => Setting::getSetting('service_number') ?: '',
            'qrcode' => ($qrcode = Setting::getSetting('service_qrcode')) ? cdnurl($qrcode, true) : '',
        ];
        $this->success('查询成功', $ret);
    }

    /**
     * 获取落地域名
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function getServiceurl()
    {
        $ret = Setting::where('id', 1)->find();
        // $curl = Setting::getSetting('curl');
        // $abs  = explode('|',$curl);
        // $ret = [
        //     'url' => Setting::getSetting('url')
        // ];


        $this->success('查询成功', $ret['url']);
    }

    /**
     * 获取微信登录地址
     * @author fuyelk <fuyelk@fuyelk.com>
     */
    public function getWechatLoginUrl()
    {
        $redirect = input('redirect');
        if (empty($redirect)) {
            $this->error('重定向地址不能为空');
        }

        $redirect = preg_match("/^http(.*)/", $redirect) ? $redirect : $this->request->domain() . $redirect;

        $ret = [
            'url' => $this->request->domain() . '/index/wechat/bootToUrl?url=' . base64_encode($redirect)
        ];

        $this->success('查询成功', $ret);
    }

    /**
     * 添加晒图
     */
    public function setShai()
    {
        $validate = new \think\Validate([
            'box_zw' => 'require',
            'box_img' => 'require',
            'token' => 'require',
        ]);
        $validate->message([
            'box_zw.require' => '盲盒详情banner文字不能为空',
            'box_img.require' => '盲盒详情banner不能为空',
            'token.require' => 'token不能为空',
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }


        $params = [
            'box_mc' => $this->auth->nickname,
            'box_tx' => $this->auth->avatar ? cdnurl($this->auth->avatar, true) : '',
            'box_zw' => $data['box_zw'],
            'box_img' => $data['box_img'],
            'create_time' => time()
        ];

        Db::table('box_shai')->insertGetId($params);
        $this->success();
    }


}