<?php

/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/02
 */

namespace app\models\auction;

use app\admin\model\user\User;
use app\admin\model\user\UserBill;
use crmeb\services\product\Product;
use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;

/**
 * 预约 Model
 * Class WechatNews
 * @package app\admin\model\wechat
 */
class AuctionOrder extends BaseModel
{

    use ModelTrait;

    protected $pk = 'id';

    protected $name = 'auction_order';
    protected $autoWriteTimestamp = true;


    /**
     * 用户订单
     * @param $data
     * @param $uid
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function userOrder($data,$uid)
    {
        if ($data['order_id']){
            $list = self::alias('a')
                ->field('a.*,u.nickname,u.avatar,u.uid as user_id')
                ->leftJoin('user u', 'a.collection_id = u.uid')
                ->where('a.order_id', $data['order_id'])->find(); //详细订单
            $pay = AuctionPay::where('uid', $list['collection_id'])->select();

            $list['wx'] = [];
            $list['zfb'] = [];
            $list['bank'] = [];
            $list['time'] = strtotime($list['create_time']);
            if ($pay){
                foreach ($pay as $k => $v){
                    if ($v['type'] == 1){
                        $list['wx'] = $v;
                    }elseif ($v['type'] == 2){
                        $list['zfb'] = $v;
                    }elseif ($v['type'] == 3){
                        $list['bank'] = $v;
                    }
                }
            }
        }else{
            if ($data['type'] == 1){
                $list = self::where([['uid', '=', $uid], ['status', '=', 1]])->page($data['page'], $data['limit'])->select(); //待上传订单

            }else if($data['type'] == 2){
                $list = self::where([['uid', '=', $uid], ['status', '=', 2]])->page($data['page'], $data['limit'])->select(); //待审核订单

            }else if($data['type'] == 3) {
                $list = self::where([['uid', '=', $uid], ['status', '=', 3]])->page($data['page'], $data['limit'])->select(); //完成订单
            }else{
                $list = self::where([['uid', '=', $uid], ['status', '<', 1]])->page($data['page'], $data['limit'])->select(); //过期订单
            }
        }

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

    /**
     * 卖家订单
     * @param $data
     * @param $uid
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function seller_list($data,$uid)
    {
        if ($data['order_id']){
            $list = self::alias('a')
                ->field('a.*,u.nickname,u.avatar,u.uid as user_id')
                ->leftJoin('user u', 'a.uid = u.uid')
                ->where('a.order_id', $data['order_id'])->find(); //详细订单
        }else{
            if ($data['type'] == 1){
                $list = self::alias('a')
                    ->field('a.*,u.nickname,u.avatar,u.uid as user_id')
                    ->leftJoin('user u', 'a.uid = u.uid')
                    ->where([['a.collection_id', '=', $uid], ['a.status', '=', 1]])
                    ->page($data['page'], $data['limit'])
                    ->select(); //待上传订单

            }else if($data['type'] == 2){
                $list = self::alias('a')
                    ->field('a.*,u.nickname,u.avatar,u.uid as user_id')
                    ->leftJoin('user u', 'a.uid = u.uid')
                    ->where([['a.collection_id', '=', $uid], ['a.status', '=', 2]])
                    ->page($data['page'], $data['limit'])
                    ->select(); //待审核订单

            }else if($data['type'] == 3) {
                $list = self::alias('a')
                    ->field('a.*,u.nickname,u.avatar,u.uid as user_id')
                    ->leftJoin('user u', 'a.uid = u.uid')
                    ->where([['a.collection_id', '=', $uid], ['a.status', '=', 3]])
                    ->page($data['page'], $data['limit'])
                    ->select(); //完成订单
            }else{
                $list = self::alias('a')
                    ->field('a.*,u.nickname,u.avatar,u.uid as user_id')
                    ->leftJoin('user u', 'a.uid = u.uid')
                    ->where([['a.collection_id', '=', $uid], ['a.status', '=', 0]])
                    ->page($data['page'], $data['limit'])
                    ->select(); //过期订单
            }
        }
        $list = !empty($list)? $list->toArray(): [];
        foreach ($list as $k => $v) {
            $pay = AuctionPay::where('uid', $v['uid'])->find();
            $list[$k]['phone'] = $pay['phone'];
        }

        return $list;
    }

    /**
     * 卖家操作
     * @param $id  //商品所属人
     * @param $price //卖出价格
     * @param $product //商品详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function earn($id, $price,$product)
    {
        $userModel = new \app\models\user\User();
        $productModel = new AuctionProduct();
        $user = $userModel->find($id);

        if ($user['spread_uid'] > 0){
            $s_price = number_format(($price - $product['price']) * 0.1, 2); // 卖出价格减去购买价格的百分之十 为上级直推奖励
            $spread = $userModel->find($user['spread_uid']);
            $spread['integral'] = $spread['integral'] + $s_price; //积分增加
            $spread->save();
            \app\models\user\UserBill::create([
                'uid' => $spread['uid'],
                'link_id' => $id,
                'pm' => 1,
                'title' => '积分增加',
                'category' => 'integral',
                'type' => 'gain',
                'mark' => '卖出商品直推'.$s_price.'积分',
                'add_time' => time(),
                'number' => $s_price,
                'balance' => $spread['integral']

            ]);
        }
//        $user['anticipate'] = $user['anticipate']-$price*($product['deduct']/100); // 扣除当前卖出价格百分比的预约卷
//        $user->save();
//        UserBill::expend('预约卷扣除', $user['uid'], 'anticipate','reduce_anticipate', $price*($product['deduct']/100), 0, $user['anticipate'] ,'卖出扣除预约卷');
        $productModel->where('id', $product['id'])->save(['is_show' => 0]); //下架等待挂售

    }

    /**
     * 购买成功退预约卷
     * @param $id
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function return($id)
    {
        $data = self::find($id);
        $userModel = new User();
        $productModel = new AuctionProduct();
        $auctionModel = new Auction();
        $bookingModel = new AuctionBooking();


        $user = $userModel->find($data['uid']);
        if ($user['is_new'] == 1){

            if ($user['spread_uid']) {
                $spread = $userModel->where('uid', $user['spread_uid'])->find();
                $spread['green_time'] = strtotime(date('Y-m-d', strtotime('+1 day'))); // 开启明天的绿色通道
            }
            $orderCount = AuctionOrder::where([['uid', '=',  $user['uid']], ['status','=', 3]])->count();
            if ($orderCount >= 5){
                $user['is_new'] = 0;
            }


        }
        $product = $productModel->where('id', $data['product_id'])->find();
        $auction = $auctionModel->where('id', $product['auction_id'])->find();
        $booking = $bookingModel->where('auction_id', $auction['id'])->where('uid', $user['uid'])->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 ($booking['status'] > 0){
            $booking['status'] = 0;
            $booking->save();
            $user['anticipate'] = $user['anticipate'] + $auction['anticipate'];// 退还预约卷
            $user->save();


            \app\models\user\UserBill::create([
                'uid' => $user['uid'],
                'pm' => 1,
                'title' => '预约卷退还',
                'category' => 'anticipate',
                'type' => 'add_anticipate',
                'mark' => '退还预约场馆'.number_format($auction['anticipate'],2).'预约卷',
                'add_time' => time(),
                'number' => number_format($auction['anticipate'],2),
                'balance' => $user['anticipate']
            ]);
        }
    }

    /**
     * 订单过期
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function deduction()
    {
        $hour = strtotime(date('Y-m-d H:i:s', strtotime('-1 hour'))); // 一小时以前

        $order = AuctionOrder::where('create_time', '<', $hour)->where('status', '=', 1)->select(); // 查询不在当前一个小时内的订单
        if ($order){
            foreach ($order as $K => $v){
                $product = AuctionProduct::where('id', $v['product_id'])->find();

                $auction = Auction::where('id', $product['auction_id'])->find();

                $booking = AuctionBooking::where([['uid', '=', $v['uid']], ['status', '=', 1], ['auction_id', '=', $auction['id']]])->where('status', '=', 1)->find(); // 找到预约订单
                if ($booking){
                    $user = \app\models\user\User::where('uid', $v['collection_id'])->find();
                    $user['anticipate'] = $user['anticipate'] + $auction['anticipate']; // 卖家增加预约卷
                    UserBill::income('增加预约卷', $v['collection_id'], 'anticipate', 'add_anticipate',  $auction['anticipate'], $v['uid'], $user['anticipate'], '卖出订单未上传支付凭证,增加'.$auction['anticipate'].'预约卷');

                    $user->save();
                    AuctionBooking::where('id', $booking['id'])->update(['status' => 2]); // 修改预约订单状态 为扣除
                }
                AuctionOrder::where('create_time', '<', $hour)->where('status', '=', 1)->update(['status' => 0]); // 修改为已过期订单
            }

        }
    }

    /**
     * 退回预约卷
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function th()
    {
        $auction = Auction::where('rend_time', '<', date('H:i:s', time()))->select();
        if ($auction){
            foreach ($auction as $k => $v){

                $booking = AuctionBooking::where([['auction_id', '=', $v['id']], ['status','=' , 1]])->select();
                if ($booking){
                    foreach ($booking as $key => $value){
                        $product = AuctionProduct::where('auction_id', $value['auction_id'])->column('id');
                        $order = AuctionOrder::where([['product_id', 'in', $product], ['frequency', '=', $value['frequency']], ['uid', '=', $value['uid']]])->where('status','>', 0)->find();
                        if (!$order){
                            $find = AuctionBooking::find($value['id']);
                            $find['status'] = 0;

                            $user = User::where('uid', $value['uid'])->find();
                            $user['anticipate'] = $user['anticipate'] + $value['anticipate'];

                            $user->save();
                            $find->save();
                            UserBill::income('预约卷增加',$user['uid'], 'anticipate', 'add_anticipate', $value['anticipate'], 0, $user['anticipate'], '预约卷退回');
                        }
                    }
                }
            }
        }
    }





}