<?php

namespace App\Services\Share;

use App\Exceptions\AlertException;
use App\Models\Fpdx\PairModel;
use App\Models\Share\RedpackCheckModel;
use App\Models\Share\RedpackListModel;
use App\Models\User\UserModel;
use App\Services\Pay\OrderService;
use App\Services\Service;
use Illuminate\Support\Collection;

class RedpackService extends Service
{
    private $fee = 2;

    /**
     * 滚动气泡
     */
    public function bannerlist()
    {
        $listModel = new RedpackListModel();
        $datas = $listModel->where('is_withdraw', 1)->take(10)->orderBy('updated_at', 'desc')->get(['uid', 'fee']);
        foreach ($datas as &$data) {
            $user = UserModel::findOrFail($data->uid);
            $data->nickname = $user->nickname;
            $data->headimgurl = $user->headimgurl;
            $data->sex = $user->sex;
            $data->address = $user->address;
        }

        return $datas;
    }

    /**
     * 创建现金红包
     * @param  int  $uid
     * @return bool
     * @throws AlertException
     */
    public function store(int $uid)
    {
        throw new AlertException("第一波红包活动已结束，敬请期待下一波。");
        $listModel = new RedpackListModel();
        if (
            $listModel->where([
            ['uid', $uid],
            ['expired_at', '>', time()],
            ['is_withdraw', 0],
            ])->OrWhere([
            ['uid', $uid],
            ['completeness', '>=', 100],
            ['is_withdraw', 0],
            ])->exists()
        ) {
            return false;
        } else {
            if (!PairModel::where('uid', $uid)->exists()) {
                throw new AlertException("(￣▽￣)无权限生成新的红包，去首页玩玩吧", 404);
            }
            $total = \DB::table('kdgx_charge_redpack_list')->where([
                ['uid', $uid],
                ['is_withdraw', 1],
            ])->sum('fee');
            if ($total >= 6) {
                throw new AlertException('红包已达上限', 402);
            }
            $completeness = 60;
            $list = $listModel->fill([
                'expired_at' => time() + 86400,
                'completeness' => $completeness,
                'uid' => $uid,
                'fee' => $this->fee,
            ]);
            if ($list->save()) {
                \DB::table('kdgx_charge_redpack_check')->insert([
                    'created_at' => time(),
                    'updated_at' => time(),
                    'list_id' => $list->id,
                    'check_uid' => $uid,
                    'fee' => sprintf('%.2f', $this->fee * $completeness / 100),
                ]);

                return $list->toArray();
            } else {
                return false;
            }
        }
    }

    /**
     * 最后一个红包
     * @param  int  $uid
     * @return Collection
     */
    public function ingredpack(int $uid)
    {
        $redpackModel = new RedpackListModel();
        $data = $redpackModel->where('uid', $uid)->orderBy('id', 'desc')->first();
        if (collect($data)->isEmpty()) {
            return array();
        } else {
            return $this->get($data->id);
        }
    }

    /**
     * 获取正在进行的现金红包信息
     * @param  int  $id
     * @return array
     */
    public function get(int $id)
    {
        $redpackModel = new RedpackListModel();
        $redpack = $redpackModel->findOrFail($id);
        $redpack->get_fee = (string)sprintf('%.2f', $redpack->fee * $redpack->completeness / 100);
        $self = UserModel::findOrFail($redpack->uid);
        $redpack->self = array(
            'headimgurl' => $self->headimgurl,
            'nickname' => $self->nickname,
        );
        $checkModel = new RedpackCheckModel();
        $checks = $checkModel->where('list_id', $redpack->id)->get();
        $list = array();
        foreach ($checks as $tmp) {
            $user = UserModel::findOrFail($tmp->check_uid);
            $list[] = array(
                'uid' => $tmp->check_uid,
                'headimgurl' => $user->headimgurl,
                'nickname' => $user->nickname,
                'fee' => $tmp->fee,
            );
        }
        $redpack->list = $list;

        return $redpack->toArray();
    }

    /**
     * 新用户现金红包检验
     * @param  int  $uid
     * @param  int  $share_uid
     * @return bool
     * @throws AlertException
     * @throws \Throwable
     */
    public function check(int $uid, int $share_uid)
    {
        $listModel = new RedpackListModel();
        $data = $listModel->where([
            ['uid', $share_uid],
            ['completeness', '<', 100],
            ['expired_at', '>', time()],
        ])->first();
        if (collect($data)->isEmpty()) {
            return false;
        } else {
            $data = $this->pcheck($uid, $data->id);

            return $data['get_fee'];
        }
    }

    /**
     * 新用户现金红包检验
     * @param  int  $uid
     * @param  int  $redpack_id
     * @return bool
     * @throws AlertException
     * @throws \Throwable
     */
    public function pcheck(int $uid, int $redpack_id)
    {

        $user = UserModel::findOrFail($uid);
        if ((int)$user->toArray()['created_at'] < time() - 300) {
            throw new AlertException("老朋友，欢迎回来", 201);
        }
        $listModel = new RedpackListModel();
        $ls = $listModel->where('uid', $uid)->get();
        $checkModel = new RedpackCheckModel();
        if (
            $checkModel->where([
            ['check_uid', $user->uid],
            ])->whereNotIn('list_id', $ls->pluck('id'))->exists()
        ) {
            throw new AlertException("老朋友，欢迎回来!", 202);
        }
        $list = $listModel->findOrFail($redpack_id);
        if ($list->expired_at < time() || $list->completeness >= 100) {
            throw new AlertException("分享已经失效", 203);
        }
        $cnt = $checkModel->where('list_id', $list->id)->count();
        \DB::beginTransaction();
        try {
            switch ($cnt) {
                case 0:
                    $completeness = 60;
                    break;
                case 1:
                    $completeness = 15;
                    break;
                case 3:
                case 2:
                    $completeness = 10;
                    break;
                case 4:
                    $completeness = 5;
                    break;
                default:
                    $completeness = 0;
                    break;
            }
            if (($list->completeness + $completeness) > 100) {
                $completeness = 100 - $list->completeness;
            }
            $get_fee = sprintf('%.2f', $list->fee * $completeness / 100);
            \DB::table('kdgx_charge_redpack_check')->insert([
                'created_at' => time(),
                'updated_at' => time(),
                'list_id' => $redpack_id,
                'check_uid' => $uid,
                'fee' => $get_fee,
            ]);
            \DB::table('kdgx_charge_redpack_list')->where([
                ['id', $list->id],
                ['completeness', $list->completeness],
            ])->increment('completeness', $completeness);
            if (($list->completeness + $completeness) == 100 && $completeness != 0) {
                $self = UserModel::findOrFail($list->uid);
                if (!empty($self->phone)) {
                    $total = \DB::table('kdgx_charge_redpack_list')->where([
                        ['uid', $list->uid],
                        ['is_withdraw', 1],
                    ])->sum('fee');
                    if ($total > 6) {
                        throw new AlertException('提现申请已提交。超过提现额度，暂无法自主提现。系统会在2个工作日内陆续下发红包', 402);
                    }
                    \DB::table('kdgx_charge_redpack_list')->where([
                        ['id', $list->id],
                        ['is_withdraw', 0],
                    ])->update(['is_withdraw' => 1]);
                    $os = new OrderService();
                    $os->payments($list->uid, $list->fee * 100, "分配对象现金红包提现");
                }
            }
            \DB::commit();

            return [
                'get_fee' => $get_fee,
                'user' => [
                    'nickname' => $self->nickname,
                ],
            ];
        } catch (\Exception $e) {
            \DB::rollBack();

            return false;
        }
    }

    /**
     * 切换通知状态
     * @param  int  $uid
     * @param  int  $list_id
     * @return bool
     * @throws AlertException
     */
    public function notice(int $uid, int $list_id)
    {
        $listModel = new RedpackListModel();
        $list = $listModel->findOrFail($list_id);
        if ($list->uid != $uid) {
            throw new AlertException("无权限", 403);
        }
        $list->notice = abs($list->notice - 1);
        if ($list->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 已完成的现金红包
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function susslist(int $uid, array $pages): array
    {
        $listmodel = new RedpackListModel();
        $total = $listmodel->where([
            ['uid', $uid],
            ['completeness', 100],
        ])->count();
        $datas = $listmodel->where([
            ['uid', $uid],
            ['completeness', 100],
        ])->orderBy('id', 'desc')->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $res = array();
        foreach ($datas as &$data) {
            $data->type = 4;
            $data->photo = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c7ac8c90.png';
            $data->title = '现金红包分享';
            $data->desc = "分享成功后可到账{$data->fee}元";
        }

        return [
            'page' => $pages['page'],
            'total' => $total,
            'limit' => $pages['limit'],
            'list' => $res,
        ];
    }

    /**
     * 已完成的现金红包
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function faillist(int $uid, array $pages): array
    {
        $listmodel = new RedpackListModel();
        $total = $listmodel->where([
            ['uid', $uid],
            ['completeness', '<', 100],
            ['expired_at', '>', time()],
        ])->count();
        $datas = $listmodel->where([
            ['uid', $uid],
            ['completeness', '<', 100],
            ['expired_at', '>', time()],
        ])->orderBy('id', 'desc')->skip(($pages['page'] - 1) * $pages['limit'])->take($pages['limit'])->get();
        $res = array();
        foreach ($datas as &$data) {
            $data->type = 4;
            $data->photo = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c7ac8c90.png';
            $data->title = '现金红包分享';
            $data->desc = "分享成功后可到账{$data->fee}元";
        }

        return [
            'page' => $pages['page'],
            'total' => $total,
            'limit' => $pages['limit'],
            'list' => $res,
        ];
    }

    /**
     * 现金红包提现
     * @param  int  $uid
     * @param  int  $list_id
     * @return bool
     * @throws AlertException
     */
    public function withdraw(int $uid, int $list_id)
    {
        $listmodel = new RedpackListModel();
        $list = $listmodel->findOrFail($list_id);
        if ($list->uid != $uid) {
            throw new AlertException('无权限', 403);
        }
        $user = UserModel::findOrFail($list->uid);
        if (empty($user->phone)) {
            throw new AlertException('请补全手机号', 201);
        }
        if ($list->completeness < 100) {
            throw new AlertException('分享任务未完成', 401);
        }
        if ($list->is_withdraw != 0) {
            throw new AlertException('红包已提现', 401);
        }
        $total = \DB::table('kdgx_charge_redpack_list')->where([
            ['uid', $list->uid],
            ['is_withdraw', 1],
        ])->sum('fee');
        if ($total > 6) {
            throw new AlertException('提现申请已提交。超过提现额度，暂无法自主提现。系统会在2个工作日内陆续下发红包', 402);
        }
        try {
            $os = new OrderService();
            $os->payments($list->uid, $list->fee * 100, "分配对象现金红包提现");
            \DB::table('kdgx_charge_redpack_list')->where([
                ['id', $list->id],
                ['is_withdraw', 0],
            ])->update(['is_withdraw' => 1]);

            return true;
        } catch (\Exception $e) {
            \DB::table('kdgx_charge_redpack_list')->where([
                ['id', $list->id],
                ['is_withdraw', 1],
            ])->update(['is_withdraw' => 0]);
            throw new AlertException($e->getMessage(), 500);
        }
    }
}
