<?php

namespace app\controller;


use app\business\LoginBusiness;
use app\business\StreamBusiness;
use Illuminate\Support\Arr;
use Respect\Validation\Validator;
use support\Db;
use support\Redis;
use support\Request;
use hg\apidoc\annotation as Apidoc;
use Webman\Captcha\CaptchaBuilder;
use Webman\Captcha\PhraseBuilder;

#[Apidoc\Title("抽奖管理")]
#[Apidoc\Group("Raffle")]
#[Apidoc\Sort(1)]
class RaffleController
{

    #[Apidoc\Title("抽奖列表")]
    #[Apidoc\Url("api/raffle.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Returned(name: "raffle_num", type: "int", require: true, desc: '抽奖次数', default: 10)]
    #[Apidoc\Returned(name: "accumulate_raffle_num", type: "int", require: true, desc: '累计抽奖次数', default: 10)]
    #[Apidoc\Returned(name: "raffle", type: "array", desc: '抽奖列表', default: '', children: [
        ['name' => "id", 'type' => 'int', 'require' => true, 'default' => '奖励标识,抽奖结果会返回', 'desc' => 1],
        ['name' => "name", 'type' => 'int', 'require' => true, 'default' => '获奖名称', 'desc' => 1],
        ['name' => "img", 'type' => 'int', 'require' => true, 'default' => '获奖图片', 'desc' => 1],
        ['name' => "money", 'type' => 'int', 'require' => true, 'default' => '中奖金额', 'desc' => 1],
    ])]
    public function index(Request $request)
    {
        $data = Db::table('wa_raffle')
            ->where('status', 1)
            ->select(['id', 'money', 'img', 'name'])
            ->orderBy('sort')
            ->get()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]->img = imageToBase64($v->img);
        }
        return success([
            'raffle'                => $data,
            'raffle_num'            => $request->user_data['raffle_num'],
            'accumulate_raffle_num' => $request->user_data['accumulate_raffle_num']
        ], '获取成功');
    }

    #[Apidoc\Title("抽奖")]
    #[Apidoc\Url("api/raffle/buy.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Returned(name: "id", type: "int", require: true, desc: '奖品ID', default: 10)]
    #[Apidoc\Returned(name: "name", type: "int", require: true, desc: '名称', default: 10)]
    #[Apidoc\Returned(name: "img", type: "int", require: true, desc: '图片', default: 10)]
    public function buy(Request $request)
    {
        $param = $request->param_data;
        Db::beginTransaction();
        try {
            if ($request->user_data['raffle_num'] <= 0) {
                throw new \Exception('你当前没有抽奖次数了');
            }
            $prize_list = Db::table('wa_raffle')->where('status', 1)->get()->toArray();
            $arr        = [];
            foreach ($prize_list as $key => $vo) {
                if ($vo->pro >= 1) {
                    for ($i = 1; $i <= $vo->pro; $i++) {
                        array_push($arr, (int)$vo->id);
                    }
                }
            }
            //随机打算数组内中奖id的顺序
            shuffle($arr);
            $lucky_index = array_rand($arr, 1);          //随机从中奖的集合中获取一个中奖的元素（这里返回的是当前元素所在的索引）
            $lucky_id    = $arr[$lucky_index];           //这里最终确定了抽中的奖品id


            $raffledata = Db::table('wa_raffle')->where('id', $lucky_id)->first();

            $raffle_log_id = Db::table('wa_raffle_log')->insertGetId([
                'user_id'    => $request->user_data['id'],
                'raffle_id'  => $lucky_id,
                'type'       => $raffledata->type,
                'created_at' => date("Y-m-d H:i:s"),
            ]);
            if (!empty($raffledata->money)) {
                StreamBusiness::addStream($request->user_data['id'], $raffledata->money, streamType12, moldType2, moldTypefild2, $raffle_log_id);
            }
            /** 减少抽奖次数 */
            Db::table('wa_users')->where('id', $request->user_data['id'])->decrement('raffle_num');

        } catch (\Throwable $exception) {
            Db::rollBack();
            return error($exception->getMessage());
        }
        Db::commit();
        return success([
            'id'            => $lucky_id,
            'raffle_log_id' => $raffle_log_id,
            'type'          => $raffledata->type,
            'name'          => $raffledata->name,
            'img'           => imageToBase64($raffledata->img),
        ], '抽奖成功，恭喜获得：' . $raffledata->name);
    }

    #[Apidoc\Title("中奖列表")]
    #[Apidoc\Url("api/raffle/user_raffle.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Param("page", type: "int", require: true, desc: "页面", mock: 1)]
    #[Apidoc\Param("limit", type: "int", require: true, desc: "输出条数", mock: 10)]
    #[Apidoc\Returned(name: "good_name", type: "int", require: true, desc: '产品名称', default: 10)]
    #[Apidoc\Returned(name: "created_at", type: "int", require: true, desc: '中奖时间', default: 10)]
    #[Apidoc\Returned(name: "name", type: "int", require: true, desc: '收货人', default: 10)]
    #[Apidoc\Returned(name: "mobile", type: "int", require: true, desc: '手机号', default: 10)]
    #[Apidoc\Returned(name: "address", type: "int", require: true, desc: '收货地址', default: 10)]
    #[Apidoc\Returned(name: "type", type: "int", require: true, desc: '类型：1=实物，2=虚拟', default: 10)]
    #[Apidoc\Returned(name: "statename", type: "int", require: true, desc: '状态描述', default: 10)]
    public function userRaffle(Request $request)
    {
        $param = $request->param_data;
        try {
            Validator::input($param, [
                'page'  => Validator::notEmpty()->intType()->setName('页面'),
                'limit' => Validator::notEmpty()->intType()->setName('输出条数'),
            ]);
            $data = Db::table('wa_raffle_log')
                ->where('user_id', $request->user_data['id'])
                ->orderByDesc('id')
                ->paginate(Arr::get($param, 'limit', 10), ['*'], 'page', Arr::get($param, 'page'))
                ->toArray();
            $arr  = [];
            foreach ($data['data'] as $k => $v) {
                $raffle = Db::table('wa_raffle')->where('id', $v->raffle_id)->first();
                if (!empty($raffle->money)) {
                    $statename = '调货中，请耐心等待';
                } else {
                    $statename = '已发送至银联卡余额';
                }
                $arr[] = [
                    'id'         => $v->id,
                    'good_name'  => $raffle->name,
                    'img'        => imageToBase64($raffle->img),
                    'created_at' => date('Y-m-d', strtotime($v->created_at)),
                    'name'       => $v->name,
                    'mobile'     => $v->mobile,
                    'address'    => $v->address,
                    'type'       => $v->type,
                    'statename'  => $statename,
                ];
            }
        } catch (\Throwable $exception) {
            return error($exception->getMessage());
        }
        return success($arr, '成功', 200, $data['total']);
    }

    #[Apidoc\Title("修改地址")]
    #[Apidoc\Url("api/raffle/save_raffle.html")]
    #[Apidoc\Method("POST")]
    #[Apidoc\Header("token", type: "string", require: true, desc: "身份令牌Token", mock: "@token")]
    #[Apidoc\Param("id", type: "int", require: true, desc: "页面", mock: 1)]
    #[Apidoc\Param("name", type: "int", require: true, desc: "收货人", mock: 10)]
    #[Apidoc\Param("mobile", type: "int", require: true, desc: "手机号", mock: 10)]
    #[Apidoc\Param("address", type: "int", require: true, desc: "地址", mock: 10)]
    public function save_raffle(Request $request)
    {
        $param = $request->param_data;
        try {
            Validator::input($param, [
                'id'      => Validator::notEmpty()->setName('id'),
                'name'    => Validator::notEmpty()->setName('收货人'),
                'mobile'  => Validator::notEmpty()->setName('手机号'),
                'address' => Validator::notEmpty()->setName('收货地址'),
            ]);
            $rafflelog = Db::table('wa_raffle_log')->where('id', $param['id'])->first();
            Db::table('wa_raffle_log')->where('id', $param['id'])->update([
                'name'    => Arr::get($param, 'name', $rafflelog->name),
                'number'  => Arr::get($param, 'number', $rafflelog->number),
                'mobile'  => Arr::get($param, 'mobile', $rafflelog->mobile),
                'address' => Arr::get($param, 'address', $rafflelog->address),
            ]);
        } catch (\Throwable $exception) {
            return error($exception->getMessage());
        }
        return success();

    }
}
