<?php

namespace App\Services\Share;

use App\Exceptions\AlertException;
use App\Models\Share\FlowerCheckModel;
use App\Models\Share\FlowerListModel;
use App\Models\User\UserModel;
use App\Services\Service;

class FlowerService extends Service
{
    private $fee = 2;

    public function latest(int $uid)
    {
        $listmodel = new FlowerListModel();
        $data = $listmodel->where('uid', $uid)->orderBy('id', 'desc')->first();
        if (collect($data)->isEmpty()) {
            return array();
        } else {
            return $this->get($data->id);
        }
    }

    /**
     * 获取小花分享信息
     * @param  int  $list_id
     * @return array
     */
    public function get(int $list_id): array
    {
        $listmodel = new FlowerListModel();
        $data = $listmodel->findOrFail($list_id);
        $data->get_fee = (string)sprintf('%.2f', $data->fee * $data->completeness / 100);
        $self = UserModel::findOrFail($data->uid);
        $data->self = array(
            'headimgurl' => $self->headimgurl,
            'nickname' => $self->nickname,
        );
        $checkModel = new FlowerCheckModel();
        $checks = $checkModel->where('list_id', $data->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,
                'type' => 3,
            );
        }
        $data->list = $list;

        return $data->toArray();
    }

    /**
     * 滚动气泡
     */
    public function bannerlist()
    {
        $listModel = new FlowerListModel();
        $datas = $listModel->where('completeness', 100)->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;
    }

    /**
     * 创建小fa红包
     * @param  int  $uid
     * @return bool|array
     */
    public function store(int $uid): bool
    {
        $listModel = new FlowerListModel();
        if (
            $listModel->where([
            ['uid', $uid],
            ['completeness', '<', 100],
            ['expired_at', '>', time()],
            ])->exists()
        ) {
            return false;
        } else {
            $completeness = 40;
            $list = $listModel->fill([
                'expired_at' => time() + 86400,
                'completeness' => $completeness,
                'uid' => $uid,
                'fee' => $this->fee,
            ]);
            if ($list->save()) {
                \DB::table('kdgx_charge_flower_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 array
     */
    public function ing(int $uid): array
    {
        $listmodel = new FlowerListModel();
        $data = $listmodel->where([
            ['uid', $uid],
            ['completeness', '<', 100],
            ['expired_at', '>', time()],
        ])->first();
        if (collect($data)->isEmpty()) {
            return array();
        } else {
            $res[] = array(
                'id' => $data->id,
                'expired_at' => $data->expired_at,
                'completeness' => $data->completeness,
                'photo' => 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c5d8090c.png',
                'title' => '小fa分享',
                'desc' => "分享成功后可到账{$data->fee}多小fa",
                'type' => 3,
            );

            return $res;
        }
    }

    /**
     * 已完成的小花红包
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function susslist(int $uid, array $pages): array
    {
        $listmodel = new FlowerListModel();
        $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();
        foreach ($datas as &$data) {
            $data->photo = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c5d8090c.png';
            $data->type = 3;
            $data->title = '小fa分享';
            $data->desc = "分享成功后可到账{$data->fee}多小fa";
        }

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

    /**
     * 失效列表
     * @param  int  $uid
     * @param  array  $pages
     * @return array
     */
    public function faillist(int $uid, array $pages): array
    {
        $listmodel = new FlowerListModel();
        $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();
        foreach ($datas as &$data) {
            $data->photo = 'https://oss.pocketuniversity.cn/media/2018-10-10/5bbd7c5d8090c.png';
            $data->type = 3;
            $data->title = '小fa分享';
            $data->desc = "分享成功后可到账{$data->fee}多小fa";
        }

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

    /**
     * 分享助力核销
     * @param  int  $uid
     * @param  int  $list_id
     * @return string
     * @throws \Throwable
     */
    public function check(int $uid, int $list_id)
    {
        $listModel = new FlowerListModel();
        $list = $listModel->findOrFail($list_id);
        $rs = new RedpackService();
        try {
            $rs->check($uid, $list->uid);
        } catch (\Exception $e) {
        }
        if ($list->expired_at < time() || $list->completeness >= 100) {
            throw new AlertException("分享已经失效", 204);
        }
        $checkModel = new FlowerCheckModel();
        if (
            $checkModel->where([
            ['check_uid', $uid],
            ['list_id', $list_id],
            ])->exists()
        ) {
            throw new AlertException("你已经帮Ta助力过了哦", 202);
        }
        $ls = $listModel->where('uid', $uid)->get();
        if (
            $checkModel->where([
                ['check_uid', $uid],
                ['created_at', '>', mktime(0, 0, 0)],
            ])->whereNotIn('list_id', $ls->pluck('id'))->count() >= 2
        ) {
            throw new AlertException("今日助力次数已用完", 203);
        }
        $cnt = $checkModel->where('list_id', $list->id)->count();
        \DB::beginTransaction();
        try {
            switch ($cnt) {
                case 0:
                    $completeness = 40;
                    break;
                case 1:
                    $completeness = 25;
                    break;
                case 2:
                    $completeness = 15;
                    break;
                case 4:
                case 3:
                    $completeness = 10;
                    break;
                default:
                    $completeness = 0;
                    break;
            }
            if (($list->completeness + $completeness) > 100) {
                $completeness = 100 - $list->completeness;
            }
            $get = sprintf('%.2f', $list->fee * $completeness / 100);
            \DB::table('kdgx_charge_flower_check')->insert([
                'created_at' => time(),
                'updated_at' => time(),
                'list_id' => $list->id,
                'check_uid' => $uid,
                'fee' => $get,
            ]);
            \DB::table('kdgx_charge_flower_list')->where([
                ['id', $list->id],
                ['completeness', $list->completeness],
            ])->increment('completeness', $completeness);
            $self = UserModel::findOrFail($list->uid);
            if (($list->completeness + $completeness) == 100) {
                \DB::table('kdgx_partner_charge_user')->where('uid', $list->uid)->increment('red_flower', $list->fee);
                \DB::table('kdgx_partner_charge_pay_logs')->insert([
                    'uid' => $list->uid,
                    'create_at' => time(),
                    'type' => 12,
                    'red_flower' => $list->fee,
                    'remark' => "助力红包",
                ]);
            }
            \DB::commit();

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

            return false;
        }
    }

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

        return false;
    }
}
