<?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\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;


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']
        ]);
        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');

        $count = AuctionOrder::whereBetweenTime('create_time', day(),today())->where('product_id', 'in', $product_ids)->count();

        $config = SystemConfig::where('menu_name', 'auction_number')->find();
        halt((int)$config['value']);
        if ($count >= $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'],
            ]);
            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],
        ]);

        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]
        ]);

        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('失败');
        }

    }

}