<?php

namespace app\api\controller\auction;


use app\admin\model\system\SystemConfig;
use app\models\auction\Auction;
use app\models\auction\AuctionBooking;
use app\models\auction\AuctionFrozen;
use app\models\auction\AuctionGu;
use app\models\auction\AuctionOrder;
use app\models\auction\AuctionProduct;
use app\models\auction\AuctionTime;
use app\models\user\User;
use app\models\user\UserBill;
use app\Request;
use crmeb\utils\Redis;
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;


class AuctionProductController
{
    /**
     * 获取商品列表
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function auction_product(Request $request)
    {
        $data = UtilService::getMore([
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
            ['id'],
            ['name']
        ]);
        if (!$data['id']) return app('json')->fail('数据传入错误');
        return app('json')->successful(AuctionProduct::list($data, $request->uid()));
    }

    /**
     * 用户商品
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function user_product(Request  $request)
    {

        $data = UtilService::getMore([
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
        ]);
        return app('json')->successful(AuctionProduct::user_product( $data,$request->uid()));
    }


    /**
     * 购买商品
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function purchase(Request $request)
    {
        $data = UtilService::getMore([
            ['product_id'],
        ]);
        if (!$data['product_id']) return app('json')->fail('数据传入错误');

        $product = AuctionProduct::where('id', $data['product_id'])->find();
        if ($product['is_show'] == 0) return app('json')->fail('商品未挂售');
        $auction  = Auction::where('id', $product['auction_id'])->find();
        $user = $request->user();
        $time = strtotime(date('Y-m-d', time()));// 今天
        $today = strtotime(date('Y-m-d', strtotime('+1day')));// 明天
        $radd_time = strtotime($auction['radd_time']); // 抢购时间
        if ($user['is_new'] == 1 or ($user['green_time'] >= $time and $user['green_time'] <= $today)){
            // 新人或者绿色通道提前三分钟入场
            if ($radd_time - 180 > time()){
                return app('json')->fail('未到抢购时间');
            }
        }else if($radd_time > time()){
            return app('json')->fail('当前未到抢购时间');
        }

        $count = AuctionOrder::where('frequency',$auction['frequency'])->where('uid', $request->uid())->where('auction_id', '=', $auction['id'])->count();// 查找今天订单数量
        $orderCount = AuctionOrder::where([['uid', '=', $request->uid()]])->whereBetweenTime('create_time', $time, $today)->count(); // 查找今天抢购的订单数量;
        $config = SystemConfigService::get('auction_number');
        $max = SystemConfigService::get('maximum');

        if ($orderCount >= (int)$max) return app('json')->fail('今日抢购数量已达到最大'); // 查看当前是否已到最大
        if ($count >=  (int)$config) return app('json')->fail('单场购买数量已到达最大'); // 查看当前是否已到最大

        if ($product['uid'] == $request->uid()) return app('json')->fail('无法购买自己商品');
        if ($product){
            AuctionOrder::beginTrans();
            //查询商品是否以卖出
            $order = AuctionOrder::where('product_id', $data['product_id'])->where('status', '>', 0)->where('frequency', $auction['frequency'])->find();
            if ($order){
                return app('json')->fail('商品已卖出');
            }
            $order_id = getNewOrderId();
            if ($count >= 1){
                if ($user['anticipate'] < 200) return app('json')->fail('艺金券不足');
                $user['anticipate'] -= 200;
                User::where('uid', $user['uid'])->update(['anticipate' => $user['anticipate']]);
                UserBill::expend('冻结艺金券',$user['uid'], 'anticipate', 'fz_anticipate', 200, $user['spread_uid'], $user['anticipate'], '购买订单'.$order_id.'冻结艺金券');

                AuctionFrozen::create([
                    'order_id' => $order_id,
                    'uid' => $request->uid(),
                    'anticipate' => 200
                ]);
            }
            $redis = new \Redis();
            $redis->connect('127.0.0.1','6379'); // redis 缓存
            if (!$redis->lPop($data['product_id'])){
                return app('json')->fail('商品已卖出');
            }
            $res = AuctionOrder::create([
                'uid' => $request->uid(),
                'collection_id' => $product['uid'],// 商品拥有有人
                'order_id' => $order_id,
                'name' => $product['name'],
                'product_id' => $product['id'],
                'auction_id' => $auction['id'],
                'image'=> $product['image'],
                'price' => $product['hanging_price'],
                'frequency' => $auction['frequency']
            ]);
            if ($res){
                AuctionOrder::commitTrans();
                return app('json')->successful('购买成功');
            }else{
                AuctionOrder::rollbackTrans();
                return app('json')->fail('购买失败');
            }
        }else{
            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 user_auction_order(Request $request)
    {

        $data = UtilService::getMore([
            [['type', 'd'], 0],
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
            ['order_id']
        ]);

        return app('json')->successful(AuctionOrder::userOrder($data,$request->uid()));
    }

    /**
     * 上传打款凭证
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function up_image(Request  $request)
    {
        $data = UtilService::getMore([
            ['image'],
            ['id']
        ]);
        if (!$data['image'] || !$data['id'])  return app('json')->fail('请上传打款凭证');

        $order = AuctionOrder::where('id', $data['id'])->find();
        if (!$order) return app('json')->fail('订单不存在');
        if ($order['status'] != 1)  return app('json')->fail('当前订单状态无法上传凭证');
        $order['upload_image'] = $data['image'];
        $order['status'] = 2;
        $order['voucher_time'] = time();

        if ($order->save()){
            return app('json')->successful('上传成功');
        }else{
            return app('json')->fail('上传失败');
        }
    }

    /**
     * 卖家显示订单
     * @param Request $request
     * @return void
     */
    public function seller(Request $request)
    {
        $data = UtilService::getMore([
            ['type', 0],
            [['page', 'd'], 0],
            [['limit', 'd'], 0],
            ['order_id']
        ]);

        return app('json')->successful(AuctionOrder::seller_list($data,$request->uid()));
    }

    /**
     * 确定订单
     * @param Request $request
     * @return void
     */
    public function adopt(Request $request){
        $data = UtilService::postMore([
            ['order_id']
        ]);
        if (!$data['order_id'])  return app('json')->fail('数据传入错误');

        $order = AuctionOrder::where('order_id', $data['order_id'])->find();
        if ($order['status'] < 1) return app('json')->fail('该订单已失效');
        if ($order['status'] == 1) return app('json')->fail('未上传打款凭证');
        if ($order['status'] == 3) return app('json')->fail('该订单已完成');

        $order['status'] = 3;
        AuctionOrder::beginTrans();
        $res = $order->save();
        if ($res){

            $product = AuctionProduct::find($order['product_id']);
            if (!$product) return app('json')->fail('数据不存在');
            $uid = $product['uid']; // 所属人id

            $product['uid'] = $order['uid'];// 商品拥有人更新
            $product['add_time'] = time();
            $product['order'] = $data['order_id'];
            $res = $product->save();
            if ($res){
                if ($uid > 0){
                    AuctionOrder::earn($uid,$order['price'] ,$product); // 卖家
                }
            }
            AuctionOrder::return($order['id']); // 买家
            AuctionOrder::commitTrans();
            return app('json')->successful('完成');
        }else{

            AuctionOrder::rollbackTrans();
            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 details(Request $request)
    {
        $data = UtilService::getMore([
            ['product_id']
        ]);
        if (!$data['product_id']) return app('json')->fail('数据传入错误');
        $details = AuctionProduct::where('id', $data['product_id'])->find();

        if (empty($details)) return app('json')->fail('商品不存在');
        $details['slider_image'] = is_string($details['slider_image']) ? json_decode($details['slider_image'], true) : [];
        $details['description'] = !empty($details['description']) ? html_entity_decode($details['description'], ENT_COMPAT) : '';
        $details['user_nickname'] = User::where('uid', $details['uid'])->find()['nickname'];

        $auction = Auction::where('id', $details['auction_id'])->find();
        $details['time'] = $auction['radd_time'].'-'.$auction['rend_time'];
        $details['times'] = strtotime($auction['radd_time']);
        $details = $details->toArray();
        return app('json')->successful($details);
    }

    /**商品以前属于人
     * @param Request $request
     * @return mixed
     */
    public function belong(Request $request)
    {
        $data = UtilService::getMore([
            ['product_id']
        ]);
        if (!$data['product_id']) return app('json')->fail('数据传入错误');
        $order = AuctionOrder::alias('a')
            ->field('u.nickname,u.avatar,a.create_time')
            ->leftJoin('user u', 'a.collection_id = u.uid')
            ->where('a.product_id', $data['product_id'])->where('a.status', 3)->select();

        if (empty($order->toArray())) $order = AuctionProduct::alias('a')
            ->field('u.nickname,u.avatar,a.create_time')
            ->leftJoin('user u', 'a.uid = u.uid')
            ->where('a.id', $data['product_id'])->select();
        $order = empty($order)? [] : $order->toArray();
        return app('json')->successful($order);
    }

    /**
     * 挂售详情
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function gsxq(Request $request)
    {
        $data = UtilService::getMore([
            ['id']
        ]);
        $product = AuctionProduct::where('id', $data['id'])->find();
        if (!$product) return app('json')->fail('商品不存在');

        $data = AuctionProduct::bs($data['id']);
        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 hanging_sale(Request $request)
    {
        $data = UtilService::postMore([
            ['id'],
        ]);
        $product = AuctionProduct::where('id', $data['id'])->where('uid', $request->uid())->find();
        $user = User::where('uid', $request->uid())->find();
        if (!$product) return app('json')->fail('商品不存在');
        if ($product['frozen'] == 1) return app('json')->fail('商品已冻结，无法挂售');
        if ($product['is_show'] == 1) return app('json')->fail('商品已挂售');

        $guId = Auction::where('id', $product['auction_id'])->value('auction_gu_id');
        $auction_id = Auction::where('auction_gu_id', $guId)->column('id');
        $max = AuctionGu::where('id', $guId)->value('max_hanging');
        $money = AuctionProduct::where('is_show', 1)
            ->where('is_admin', 2)
            ->where('uid', $request->uid())
            ->where('auction_id', 'in', $auction_id)
            ->whereBetweenTime('update_time',strtotime('today'), strtotime('tomorrow'))
            ->sum('hanging_price');
        if (($money+$product['hanging_price']) > (float)$max) return app('json')->fail('今天挂售金额已超出上限');

        $datas = AuctionProduct::bs($data['id']);// 获取挂售详情
        if ($user['anticipate'] < $datas['anticipate']) return app('json')->fail('预约券不足');
        $product['price'] = $product['hanging_price'];
        $product['hanging_price'] = $datas['hanging_price']; // 商品变为挂售价格
        $product['is_show'] = 1; // 上架
        $product['is_admin'] = 2;
        $user['anticipate'] -= $datas['anticipate']; // 扣除预约券
        $user['integral'] += $datas['give'];
        try {
            Db::startTrans();
            // 新增挂售时间段
            AuctionTime::create([
                'uid' => $request->uid(),
                'product_id' => $product['id'],
                'auction_id' => $product['auction_id'],
                'add_time' => strtotime($datas['gs_time'])
            ]);

            $product->save();
            $user->save();
            AuctionOrder::where([['uid', '=', $request->uid()], ['product_id', '=', $product['id']], ['is_gs', '=', 0]])->update(['is_gs' => 1]);// 修改订单挂售
            UserBill::expend('挂售扣除预约券', $user['uid'], 'anticipate', 'gs_anticipate', $datas['anticipate'], $user['spread_uid'], $user['anticipate'], '挂售扣除艺金券');
            UserBill::income('赠送趣豆', $user['uid'], 'integral', 'gs_integral', $datas['give'], $user['spread_uid'], $user['integral'], '挂售赠送趣豆');

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


    }

    /**
     * 取消挂售
     * @param Request $request
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancel(Request $request)
    {
        $data = UtilService::postMore([
            ['id']
        ]);
        $productModel = new AuctionProduct();

        $details = $productModel->find($data['id']);
        if (!$details)  return app('json')->fail('商品不存在');
        $order = AuctionOrder::where([['product_id', '=', $details['id']], ['status', '<', 3], ['status', '>', 0]])->find();
        if ($order) return app('json')->fail('商品已出售，无法取消');


        $auction = Auction::where('id', $details['auction_id'])->find();
        $data['time'] = explode(',', $auction['site']);

        $date = date('w', time()); // 今天星期几
        $bs = 0;
        if (in_array(1, $data['time'])){
            if ($date >= 1 and $date <= 2){
                $bs = 3 - $date;
            }elseif ($date >= 3 and $date <= 4){
                $bs = 5 - $date;
            }elseif ($date >= 5 or $date == 0){
                if ($date == 5) $bs = 3;
                if ($date == 6) $bs = 2;
                if ($date == 0) $bs = 1;
            }

        }else if (in_array(2, $data['time'])){
            if ($date >= 2 and $date <= 3){
                $bs = 4 - $date;
            }elseif ($date >= 4 and $date <= 5){
                $bs = 6 - $date;
            }elseif ($date >= 6 or $date == 0 or $date == 1){
                if ($date == 6) $bs = 3;
                if ($date == 0) $bs = 2;
                if ($date == 1) $bs = 1;
            }
        }
        $user = User::where('uid', $request->uid())->find();
        $anticipate = round($details['price'] * $details['deduct']/100, 2);
        $details['hanging_price'] = $details['price']; // 价格变=回未挂售前;
        $details['is_show'] = 0; // 价格变回未挂售前;
        $user['anticipate'] += $anticipate*$bs;// 退回挂售扣除的预约预约券
        $user['integral'] -=  round(($details['price'] * $details['give']/100)*$bs, 2);// 挂售赠送趣豆


        try {
            Db::startTrans();
            $details->save();
            $user->save();
            AuctionOrder::where('order_id', $details['order'])->save(['is_gs' => 0]);
            UserBill::income('取消挂售退回预约券', $request->uid(), 'anticipate', 'gsth_anticipate', $anticipate*$bs, 0, $user['anticipate'], '取消挂售退回预约券');
            UserBill::expend('取消挂售扣除趣豆', $request->uid(), 'integral', 'gsth_integral',  round(($details['price'] * $details['give']/100)*$bs, 2), 0, $user['integral'], '取消挂售扣除赠送趣豆');
            AuctionTime::where([['uid', '=', $request->uid()], ['product_id', '=', $data['id']]])->delete(); // 删除上架时间
            Db::commit();

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


    }

    /**
     * 订单数量
     * @param Request $request
     * @return mixed
     */
    public function untreated(Request $request){
        $data = [
            'user' => [
                'paid' => AuctionOrder::where([['uid', '=', $request->uid()], ['status', '=', 1]])->count(), //待支付
                'reviewed' => AuctionOrder::where([['uid', '=', $request->uid()], ['status', '=', 2]])->count(), // 待审核
                'hanging' => AuctionOrder::where([['uid', '=', $request->uid()], ['status', '=', 3], ['is_gs', '=', 0]])->count(), // 待挂售
            ],
            'seller' => [
                'paid' => AuctionOrder::where([['collection_id', '=', $request->uid()], ['status', '=', 1]])->count(), //待支付
                'reviewed' => AuctionOrder::where([['collection_id', '=', $request->uid()], ['status', '=', 2]])->count(),  // 待审核
                'hanging' => AuctionOrder::where([['uid', '=', $request->uid()], ['status', '=', 3], ['is_gs', '=', 1]])->count(), //挂售中
            ]
        ];
        return app('json')->successful($data);
    }





}