<?php

namespace app\api\controller\auction;


use app\admin\model\system\SystemConfig;
use app\common\model\Config;
use app\models\auction\Auction;
use app\models\auction\AuctionBooking;
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 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();
        $product_ids = AuctionProduct::where('auction_id', $product['auction_id'])->column('id');
        $auction  = Auction::where('id', $product['auction_id'])->find();
        $count = AuctionOrder::where('frequency',$auction['frequency'])->where('product_id', 'in', $product_ids)->count();

        $config = SystemConfig::where('menu_name', 'auction_number')->find();
        if ($count >=  (int) preg_replace('~(,(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)|")~', '', $config['value'])) 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)->whereBetweenTime('create_time', date('Y-m-d H:i:s', strtotime(date('Y-m-d'))), date('Y-m-d H:i:s', strtotime('+1 day')))->find();
            if ($order){
                return app('json')->fail('商品已卖出');
            }
            $res = AuctionOrder::create([
                'uid' => $request->uid(),
                'collection_id' => $product['uid'],// 商品拥有有人
                'order_id' => getNewOrderId(),
                'name' => $product['name'],
                'product_id' => $product['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;

        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'];// 商品拥有人更新
            $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['auction_id'])->find()['nickname'];

        $auction = Auction::where('id', $details['auction_id'])->find();
        $details['time'] = $auction['radd_time'].'-'.$auction['rend_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();
       $auction = Auction::where('id', $product['auction_id'])->find();
       if (!$product) return app('json')->fail('商品不存在');

       $data['time'] = explode(',', $auction['site']);

       $date = date('w', time()); // 今天星期几
       $data['gs_time'] = '';
       if (in_array(1, $data['time'])){
          if ($date >= 1 and $date <= 2){
              $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Wednesday")); // 星期三
          }elseif ($date >= 3 and $date <= 4){

              $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Friday")); // 星期五
          }elseif ($date >= 5 or $date == 0){

              $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Monday")); // 下个星期一
          }

       }else if (in_array(2, $data['time'])){
           if ($date >= 2 and $date <= 3){
               $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Thursday")); // 星期四
           }elseif ($date >= 4 and $date <= 5){

               $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Saturday")); // 星期六
           }elseif ($date >= 6 or $date == 0 or $date == 1){

               $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Tuesday")); // 下个星期二
           }
       }

       $hanging_price = number_format($product['hanging_price'] * $product['rise']/100, 2); //  溢价
       $anticipate = number_format($product['hanging_price'] * $product['deduct']/100, 2); // 扣除

       $data['hanging_price'] = $product['hanging_price'] + $hanging_price;
       $data['anticipate'] = (float)$anticipate;


       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'],
            ['gs_time']
        ]);
        $product = AuctionProduct::where('id', $data['id'])->find();
        $user = User::where('uid', $request->uid())->find();
        if (!$product) return app('json')->fail('商品不存在');

        if ($product['is_show'] == 1) return app('json')->fail('商品已挂售');

        $hanging_price = number_format($product['hanging_price'] * $product['rise']/100, 2); //  溢价
        $anticipate = number_format($product['hanging_price'] * $product['deduct']/100, 2); // 扣除
        if ($user['anticipate'] < $anticipate) return app('json')->fail('预约券不足');

        $product['price'] = $product['hanging_price'];
        $product['hanging_price'] += $hanging_price;
        $product['is_show'] = 1;
        $product['is_admin'] = 2;
        $user['anticipate'] -= $anticipate;
        try {
            Db::startTrans();
            AuctionTime::create([
                'uid' => $request->uid(),
                'product_id' => $product['id'],
                'auction_id' => $product['auction_id'],
                'add_time' => strtotime($data['gs_time'])
            ]);

            $product->save();
            $user->save();
            UserBill::expend('挂售扣除预约券', $user['uid'], 'anticipate', 'reduce_anticipate', $anticipate, $user['spread_uid'], $user['anticipate'], '挂售商品扣除预约券');

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


    }


}