<?php

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

namespace app\models\auction;

use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;

/**
 * 竞拍上坪 Model
 * Class WechatNews
 * @package app\admin\model\wechat
 */
class AuctionProduct extends BaseModel
{

    use ModelTrait;

    protected $pk = 'id';

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

    /**
     * 竞拍商品列表
     * @param $data
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function list($data, $uid){
        $model = self::where('is_show', 1)->where('auction_id', $data['id'])->order('id DESC');
        if ($data['name']) $model->where('name', 'like', '%'.$data['name'].'%');
        $list = $model->select();
        $list = empty($list)? [] : $list->toArray();
        $lists = [];
        $auction = Auction::where('id', $data['id'])->find();
        if ($list){
            foreach ($list as $k => $v) {
                $order = AuctionOrder::where('product_id', $v['id'])->where('status', '>', 0)->where('frequency', $auction['frequency'])->find();
                if ($order){
                    $list[$k]['status'] = 2;// 已被购买
                    $list[$k]['str'] = '已卖完';
                }else{
                    $list[$k]['status'] = 1;// 能购买
                    $list[$k]['str'] = '购买';
                }
                if ($v['is_admin'] == 2){
                    $time = AuctionTime::where([['auction_id', '=', $auction['id']], ['product_id', '=', $v['id']], ['add_time', '=', strtotime(date('Y-m-d', time()))]])->find();
                    if (!$time){
                        unset($list[$k]);
                    } else{
                        $lists[] = $list[$k];
                    }
                }else{
                    $lists[] = $list[$k];
                }
            }
            $productId = AuctionProduct::where('auction_id', $data['id'])->column('id');
            $orderList = AuctionOrder::alias('a')
                ->field('p.*')
                ->leftJoin('auction_product p', 'a.product_id = p.id')
                ->where([['a.product_id', 'in', $productId], ['a.frequency', '=', $auction['frequency']], ['a.status', '=', 3]])
                ->select();
        }else{
            $productId = AuctionProduct::where('auction_id', $data['id'])->column('id');
            $orderList = AuctionOrder::alias('a')
                ->field('p.*')
                ->leftJoin('auction_product p', 'a.product_id = p.id')
                ->where([['a.product_id', 'in', $productId], ['a.frequency', '=', $auction['frequency']], ['a.status', '=', 3]])
                ->select();
        }

        $a = [];
        $b = [];
        foreach ($lists as $k => $v){
            if ($v['status']  == 1){
                $a[] = $v; // 未卖出的商品
            }
            if ($v['status']  == 2) $b[] = $v; // 卖出的商品
        }
        foreach ($b as $k => $v){
            array_push($a, $v); // 卖出商品到最后
        }
        if (isset($orderList) and !empty($orderList)){
            $orderList = count($orderList) == 0? [] : $orderList->toArray();
            foreach ($orderList as $v){
                $v['status'] = 2;// 已被购买
                $v['str'] = '已卖完';
                array_push($a, $v);
            }
        }
        $data['page'] = ($data['page'] - 1)*$data['limit'];
        $List = array_slice($a, $data['page'], $data['limit']);
        return $List;
    }

    /**
     * 用户商品
     * @param $data
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function user_product($data, $uid){
        $model = self::alias('a')
            ->field('a.*,b.nickname')
            ->leftJoin('auction b', 'a.auction_id = b.id')
            ->where('a.uid', $uid)->order('a.id DESC');
        $model->page($data['page'], $data['limit']);

        $list = $model->select();
        $list = empty($list)? [] : $list->toArray();

        return $list;
    }


    /**
     * 场次时间到期用户未出售商品下架
     * @return void
     */
    public static function off_the_shelf(){
        $auction = Auction::where('rend_time', '<', date('H:i:s'))->select();
        if ($auction){
            foreach ($auction as $k => $v) {
                $productId = AuctionTime::where('auction_id', '=', $v['id'])->where('add_time', '=', strtotime(date('Y-m-d', time())))->column('product_id');

                if ($productId){
                    $orderId = AuctionOrder::where('product_id', 'in', $productId)->where('frequency', '=', $v['frequency'])->where('status','>', 0)->column('product_id');
                    if ($orderId){
                        foreach ($orderId as $value){
                            if (in_array($value, $productId))unset($productId[$value]);
                        }
                    }
                    if ($productId){
                        foreach ($productId as $item){
                            $product = AuctionProduct::where([['id', '=', $item], ['is_admin', '=', 2]])->find();// 查找今天场次没买出去的商品下架
                            if ($product){
                                $product['is_show'] = 0;
                                $product['hanging_price'] = $product['price'];
                                $product->save();
                            }
                        }
                    }
                    $order = AuctionProduct::where([['id', 'in', $productId], ['auction_id', '=', $v['id']], ['is_admin', '=', 2]])->column('order');// 查找今天场次没买出去的商品订单
                    AuctionOrder::where('order_id', 'in', $order)->save(['is_gs' => 0]);//订单为未挂售状态
                    AuctionTime::where('auction_id', '=', $v['id'])->where('add_time', '<=', strtotime(date('Y-m-d', time())))->delete(); // 清除今天挂售时间
                }
            }

        }

    }

    public static function bs($id)
    {
        $product = AuctionProduct::where('id',$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'] = '';
        $bs = 0;
        if (in_array(1, $data['time'])){
            if ($date >= 1 and $date <= 2){
                $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Wednesday")); // 星期三
                $bs = 3 - $date;
            }elseif ($date >= 3 and $date <= 4){
                $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Friday")); // 星期五
                $bs = 5 - $date;
            }elseif ($date >= 5 or $date == 0){
                if ($date == 5) $bs = 3;
                if ($date == 6) $bs = 2;
                if ($date == 0) $bs = 1;
                $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")); // 星期四
                $bs = 4 - $date;
            }elseif ($date >= 4 and $date <= 5){
                $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Saturday")); // 星期六
                $bs = 6 - $date;
            }elseif ($date >= 6 or $date == 0 or $date == 1){
                $data['gs_time'] = date('Y-m-d H:i:s', strtotime("Tuesday")); // 下个星期二
                if ($date == 6) $bs = 3;
                if ($date == 0) $bs = 2;
                if ($date == 1) $bs = 1;
            }
        }
        $hanging_price = round($product['hanging_price'] * $product['rise']/100, 2); //  溢价
        $anticipate = round($product['hanging_price'] * $product['deduct']/100, 2); // 扣除
        $give = round($product['hanging_price'] * $product['give']/100, 2);// 赠送趣豆

        $data['price'] = $product['hanging_price'];
        $data['hanging_price'] = ($product['hanging_price'] + ($hanging_price * $bs));
        $data['anticipate'] = round($anticipate*$bs,2);
        $data['give'] = round($give*$bs,2);


        return $data;
    }

}