<?php

namespace app\api\controller\auction;


use app\models\auction\Auction;
use app\models\auction\AuctionApply;
use app\models\auction\AuctionBooking;
use app\models\auction\AuctionGu;
use app\models\auction\AuctionOrder;
use app\models\auction\AuctionPay;
use app\models\user\User;
use app\models\user\UserBill;
use app\Request;
use Monolog\Handler\Curl\Util;
use think\facade\Cache;
use crmeb\services\{
    CacheService,
    ExpressService,
    SystemConfigService
};
use crmeb\services\UtilService;
use crmeb\repositories\OrderRepository;
use think\facade\Db;
use think\facade\Validate;


class AuctionController
{
    /**
     * 场馆列表
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        $data = UtilService::getMore([
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
            ['advance'],
            ['auction_gu_id']
        ], $request);
        if (!$data['auction_gu_id']) return app('json')->fail('数据传入错误');
        $auctionModel = new \app\models\auction\Auction();

        return app('json')->successful($auctionModel->list($data, $request->uid()));

    }

    /**
     * 预约场馆
     * @param Request $request
     * @return void
     */
    public function subscribe(Request $request)
    {
        $data = UtilService::postMore([
            ['id']
        ]);
        if (!$data['id']) return app('json')->fail('数据传入错误');
        $auctionModel = new Auction();
        $auction = $auctionModel->find($data['id']);
        if (!$auction)return app('json')->fail('没有此数据');

        if (time() < strtotime($auction['add_time'])){
            return app('json')->fail('预约未开始');
        }
        if (time() > strtotime($auction['end_time'])){
            return app('json')->fail('预约时间已过');
        }
        if (AuctionBooking::where([['uid', '=', $request->uid()], ['auction_id' , '=', $auction['id']], ['frequency', '=', $auction['frequency']]])->find()){
            return app('json')->fail('当前场馆已预约');
        }

        $userModel = new User();
        $user = $userModel->find($request->uid());

        if ($user['anticipate'] < $auction['anticipate']) return app('json')->fail('预约卷不够');
        $user['anticipate'] = $user['anticipate'] - $auction['anticipate'];// 扣除预约卷

        User::rollbackTrans();
        $res = $user->save();

        if ($res){
            AuctionBooking::booking($user['uid'], $auction);
            UserBill::expend('预约场馆', $user['uid'], 'anticipate','reduce_anticipate', $auction['anticipate'], 0, $user['anticipate'], '预约扣除预约卷'); // 写入记录

            User::commitTrans();
            return app('json')->successful('预约成功');
        }else{

            User::rollbackTrans();
            return app('json')->fail('预约失败');
        }

    }

    /**
     * 进入场馆
     * @param Request $request
     * @return void
     */
    public function advance(Request $request)
    {
        $data = UtilService::getMore([
            ['id']
        ]);
        if (!$data['id']) return app('json')->fail('数据传入错误');
        $auction = Auction::find($data['id']);
        $booking = AuctionBooking::where([['auction_id', '=',$auction['id']], ['frequency', '=', $auction['frequency']]])->find();
        $user = $request->user();
        $time = strtotime(date('Y-m-d', time()));// 今天
        $today = strtotime(date('Y-m-d', strtotime('+1day')));// 明天

        if (!$booking){
            return app('json')->fail('未预约');
        }
        if ($user['is_new'] == 1 or ($user['green_time'] >= $time and $user['green_time'] <= $today)){
            // 新人或者绿色通道提前三分钟入场
            if (strtotime($auction['radd_time']) -180 > time()){
                return app('json')->fail('未到进入时间');
            }
            if (strtotime($auction['rend_time']) < time()){
                return app('json')->fail('进场时间已过');
            }

        }else{
            if (strtotime($auction['radd_time']) > time()){
                return app('json')->fail('未到进入时间');
            }
            if (strtotime($auction['rend_time']) < time()){
                return app('json')->fail('进场时间已过');
            }
        }
        return app('json')->successful('可进入');

    }


    /**
     * 用户下级
     * @param Request $request
     * @return mixed
     */
    public function lower(Request $request){
        $data = UtilService::getMore([
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
        ], $request);
        $user = User::where('spread_uid', $request->uid())->page($data['page'], $data['limit'])->field('uid,nickname,avatar')->order('uid DESC')->select();
        $user = empty($user) ? [] : $user->toArray();
        if ($user) {
            foreach ($user as $k => $v){
                $user[$k]['count'] = User::where('spread_uid',$v['uid'])->count(); // 粉丝人数
                $user[$k]['money'] = AuctionOrder::where('uid', $v['uid'])
                    ->whereBetweenTime('create_time', date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime('+1 day')))
                    ->where('status', 3)
                    ->sum('price');
            }
        }
        $count =  User::where('spread_uid', $request->uid())->count(); // 粉丝人数
        $active =  User::where('spread_uid', $request->uid())->whereBetweenTime('last_time', date('Y-m-d H:i:s', strtotime('-1 week')), date('Y-m-d H:i:s'))->count(); // 活跃人数
        $money = AuctionOrder::where('uid', 'in', User::where('spread_uid', $request->uid())->column('uid'))
            ->where('status', 3)
            ->sum('price');
        $data = [
            'user' => $user, // 下级用户
            'count' => $count, // 下级用户人数
            'active' => $active,// 活跃人数
            'money' => $money // 总金额
        ];


        return app('json')->successful($data);
    }


    /**
     * 转预约卷给下级
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function transfer_accounts(Request $request){
        $data = UtilService::getMore([
            ['uid'],
            ['anticipate']
        ], $request);
        if (!$data['uid'] or !$data['anticipate'])  return app('json')->fail('数据传入错误');
        $user = User::find($request->uid());
        if ($user['anticipate'] < $data['anticipate']) return app('json')->fail('预约卷不够');
        $me = User::find($data['uid']);
        $user['anticipate'] = $user['anticipate'] - $data['anticipate'];// 扣除预约卷
        $me['anticipate'] = $me['anticipate'] + $data['anticipate'];// 增加预约卷

        try {
            Db::startTrans();
            UserBill::expend('预约卷减少',$user['uid'], 'anticipate', 'reduce_anticipate', $data['anticipate'], 0, $user['anticipate'], '转账给用户'.$me['nickname'].$data['anticipate'].'预约卷');
            UserBill::income('预约卷增加',$me['uid'], 'anticipate', 'add_anticipate', $data['anticipate'], 0, $me['anticipate'], $me['nickname'].'转账'.$data['anticipate'].'预约卷');
            $user->save();
            $me->save();

            Db::commit();
            return app('json')->successful('成功');
        } catch (\Exception $e) {
            Db::rollback();
            return app('json')->fail('失败');
        }


    }

    /**
     * 会馆
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function auction_gu(Request  $request)
    {
        $data = UtilService::getMore([
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
        ], $request);
        $uid = getParent($request->uid());
        $uid[] = $request->uid();
        $list = [];
        if ($uid){
            $list = AuctionGu::where('a.uid', 'in', $uid)
                ->where('a.status', 1)
                ->alias('a')
                ->field('a.*,u.nickname,u.avatar')
                ->leftJoin('user u', 'a.uid = u.uid')
                ->page($data['page'], $data['limit'])
                ->select();

        }
        $list = !empty($list) ? $list->toArray() : [];
        return app('json')->successful($list);

    }

    /**
     * 用户管理会馆
     * @param Request $request
     * @return mixed
     */
    public function user_gu(Request $request)
    {
        $data = UtilService::getMore([
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
        ], $request);

        $list = AuctionGu::where('uid', $request->uid())->page($data['page'], $data['limit'])->select();
        $list = count($list) ? $list->toArray() : [];

        return app('json')->successful($list);
    }


    /**
     * 添加收款方式
     * @param Request $request
     * @return void
     */
    public function pay(Request $request)
    {
        $data = UtilService::postMore([
            ['payment'],
            ['image'],
            ['bank'],
            ['name'],
            ['type'],
            ['phone']
        ], $request);
        if (!$data['type'])  return app('json')->fail('数据传入错误');
        $data['uid'] =$request->uid();
        $model = new AuctionPay();
        $pay = $model->where([['uid', '=', $request->uid()], ['type', '=', $data['type']]])->find();
        $res = Validate::rule([
            'phone' => 'mobile'
        ]);
        $res->message([
            'phone.mobile' => '请填写正确手机格式'
        ]);
        if (!$res->check($data)){
            return app('json')->fail($res->getError());
        }
        if (!empty($pay)){
            if ($data['type'] == 1 ){
                // 微信收款方式
                if (!$data['payment'])  return app('json')->fail('微信账号不能为空');
                if (!$data['image'])  return app('json')->fail('二维码不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');
                $pay['payment'] = $data['payment'];
                $pay['image'] = $data['image'];
                $pay['name'] = $data['name'];
                $pay['name'] = $data['name'];
            }elseif ($data['type'] == 2){
                // 支付宝收款方式
                if (!$data['payment'])  return app('json')->fail('支付宝账号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');
                $pay['payment'] = $data['payment'];
                $pay['name'] = $data['name'];
                $pay['name'] = $data['name'];
            }elseif ($data['type'] == 3){
                // 银行卡收款方式
                if (!$data['payment'])  return app('json')->fail('银行卡号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['bank'])  return app('json')->fail('开户行');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');
                $pay['payment'] = $data['payment'];
                $pay['image'] = $data['image'];
                $pay['bank'] = $data['name'];
                $pay['phone'] = $data['phone'];

            }
            $res = $pay->save();
            if ($res) return app('json')->successful('修改成功');
            return app('json')->fail('修改失败');
        }else{
            if ($data['type'] == 1 ){
                // 微信收款方式
                if (!$data['payment'])  return app('json')->fail('微信账号不能为空');
                if (!$data['image'])  return app('json')->fail('二维码不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');

            }elseif ($data['type'] == 2){
                // 支付宝收款方式
                if (!$data['payment'])  return app('json')->fail('支付宝账号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');

            }elseif ($data['type'] == 3){
                // 银行卡收款方式
                if (!$data['payment'])  return app('json')->fail('银行卡号不能为空');
                if (!$data['name'])  return app('json')->fail('姓名不能为空');
                if (!$data['bank'])  return app('json')->fail('开户行不能为空');
                if (!$data['phone'])  return app('json')->fail('请填写手机号');
            }
            $res = $model->save($data);
            if ($res) return app('json')->successful('添加成功');
            return app('json')->fail('添加失败');
        }
    }

    /**
     * 收款方式详情
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pay_list(Request $request)
    {
        $model = new AuctionPay();
        $list = $model->where('uid', $request->uid())->select();

        $list = empty($list)? []: $list->toArray();
        $data['wx'] = [];
        $data['zfb'] = [];
        $data['bank'] = [];
        foreach ($list as $k => $v){
            if ($v['type'] == 1){
                $data['wx'] = $v;
            }elseif ($v['type'] == 2){
                $data['zfb'] = $v;
            }elseif ($v['type'] == 3){
                $data['bank'] = $v;
            }
        }
        return app('json')->successful($data);
    }

    /**
     * 馆长申请
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function apply(Request $request)
    {
        $data = AuctionApply::where('status', '>', 0)->where('uid', $request->uid())->find();
        if (!$data){
            $res = AuctionApply::create([
                'uid' => $request->uid()
            ]);
            if ($res)return app('json')->successful('申请成功');
            return app('json')->fail('申请失败');
        }
        return app('json')->fail('已申请,请等待管理员操作');

    }

    public function apply_status(Request $request)
    {
        $data = AuctionApply::where('uid', $request->uid())->find();
        if (!$data){
            return app('json')->successful(['status' => 0, 'str' => '未提交申请']); // 未提交申请
        }
        $data = AuctionApply::where([['status', '=', 1], ['uid', '=', $request->uid()]])->find();
        if ($data){
            return app('json')->successful(['status' => 1, 'str' => '待审核']);// 待审核
        }
        $data = AuctionApply::where([['status', '=', 2], ['uid', '=', $request->uid()]])->find();
        if ($data){
            return app('json')->successful(['status' => 2 ,'str' => '已完成']);// 已完成
        }
        $data = AuctionApply::where([['status', '=', 0], ['uid', '=', $request->uid()]])->find();
        if ($data){
            return app('json')->successful(['status' => 3, 'str' => '失败']);// 失败
        }



    }







}