<?php

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

namespace app\admin\model\auction;

use app\admin\model\order\StoreOrderCartInfo;
use app\admin\model\user\User;
use app\admin\model\user\UserBill;
use app\admin\model\wechat\WechatUser;
use app\models\auction\AuctionProduct;
use crmeb\services\PHPExcelService;
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;


    public static function list($where)
    {
        $model = self::alias('a')
            ->order('a.id', 'desc')
            ->field('a.*, u.account, u.nickname,us.account as us_account,us.nickname as us_nickname,p.name, p.image, au.nickname as au_name, gu.name as gu_name')
            ->leftJoin('user u', 'a.uid = u.uid')
            ->leftJoin('user us', 'us.uid = a.collection_id')
            ->leftJoin('auction_product p', 'a.product_id = p.id')
            ->leftJoin('auction au', 'au.id = p.auction_id')
            ->leftJoin('auction_gu gu', 'gu.id = au.auction_gu_id');



        if (trim($where['store_name']) != '') $model->where('a.id|u.account|u.nickname|a.order_id', 'like', '%'.$where['store_name'].'%');
        if (trim($where['status']) != '') $model->where('a.status', $where['status']);
        if (trim($where['auction_id']) != '') $model->where('au.id', $where['auction_id']);
        if (trim($where['gu_id']) != '') $model->where('gu.id', $where['gu_id']);
        if (trim($where['product_name']) != '') $model->where('p.name', $where['product_name']);
        if (trim($where['data']) != '') $model = self::getModelTime($where, $model,  'a.create_time');
        if ($where['uid']){
            $auctionGu = AuctionGu::where('uid', $where['uid'])->column('id');
            $auction = Auction::where('auction_gu_id', 'in', $auctionGu)->column('id');
            $model->where('a.auction_id', 'in', $auction);
        }
        if ($where['is_gs'] == 2){
            $model->where('a.is_gs', 0);
        }else if($where['is_gs'] == 1){
            $model->where('a.is_gs', 1);
        }
        $data['count'] = $model->count();
        if (isset($where['excel']) && $where['excel'] == 1) {
            $list = ($list = $model->select()) && count($list) ? $list->toArray() : [];
        } else {
            $list = ($list = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($list) ? $list->toArray() : [];
        }
        if (isset($where['excel']) && $where['excel'] == 1) {
            self::SaveExcel($list);
        }
        if ($where['page'] && $where['limit']){
            $model->page($where['page'], $where['limit']);
        }else{
            $model->page(20, 1);
        }

        $list = $model->select();


        $data['data'] = $list;
        return $data;

    }

    /*
     * 保存并下载excel
     * $list array
     * return
     */
    public static function SaveExcel($list)
    {
        $export = [];
        foreach ($list as $index => $item) {
            if ($item['status']  == 0 ){
                $status = '过期订单';
            }elseif ($item['status'] == 1){
                $status ='待支付';
            }elseif ($item['status'] == 2){
                $status ='待审核';
            }elseif ($item['status'] == 3){
                $status ='完成';
            }
            if ($item['status'] == 0){
                $is_gs = '过期订单';
            }else{
                if ($item['is_gs'] == 0){
                    $is_gs ='未挂售';
                }elseif ($item['is_gs'] == 1){
                    $is_gs ='已挂售';
                }
            }
            $export[] = [
                $item['order_id'],
                $item['name'],
                $item['au_name'],
                $item['gu_name'],
                $item['account'],
                $item['nickname'],
                $item['us_account'],
                $item['us_nickname'],
                $item['price'],
                $status,
                $is_gs,
                $item['create_time'],
            ];
        }
        PHPExcelService::setExcelHeader(['订单号', '商品名', '场馆', '场次', '买家账号', '买家昵称', '卖家账号','卖家昵称','商品价格', '状态','挂售状态',
            '订单时间'])
            ->setExcelTile('订单导出' . date('YmdHis', time()), '订单信息' . time(), ' 生成时间：' . date('Y-m-d H:i:s', time()))
            ->setExcelContent($export)
            ->ExcelSave();
    }


    /**
     * 卖家操作
     * @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::income('直推奖励', $spread['uid'], 'anticipate', 'add_anticipate', $s_price, 0, $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'))); // 开启明天的绿色通道
                $spread->save();
            }
            $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();
        $time = strtotime(date('Y-m-d' ,strtotime($data['create_time']))); // 订单当天时间段
        $totime = strtotime(date('Y-m-d' ,strtotime($data['create_time']))) + 86400; // 订单凌晨时间段
        $booking = $bookingModel->where('auction_id', $auction['id'])->where('uid', $user['uid'])->whereBetweenTime('create_time', $time, $totime)->find();
        if ($booking['status'] > 0){
            $booking['status'] = 0;
            $booking->save();
            $anticipate = $booking['anticipate'] - $booking['deduction'];
            $user['anticipate'] = $user['anticipate'] + $anticipate;// 退还预约卷
            $user->save();
            UserBill::create([
                'uid' => $user['uid'],
                'pm' => 1,
                'title' => '预约卷退还',
                'category' => 'anticipate',
                'type' => 'th_anticipate',
                'mark' => '退还'.$anticipate.'预约卷扣除'.$booking['deduction'],
                'add_time' => time(),
                'number' => $anticipate,
                'balance' => $user['anticipate']
            ]);
        }
    }





}