<?php

namespace app\model;
use think\facade\Db;
use think\Model;

/**
 * 商品订单模型
 * Class Order
 * @package app\model
 */
class OrderGoods extends Model {

    protected $autoWriteTimestamp = true;

    public static function getTypes(){
        return ['alipay'=>'支付宝','wxpay'=>'微信'] ;
    }

    public function getTypeTextAttr($value,$data){
        //$types = ['alipay'=>'支付宝','wechat'=>'微信'];
        return self::getTypes()[$data['type']];
    }

    public static function getTradeNoOrder($trade_no = ''){

        if( empty( $trade_no ) ){
            return null ;
        }

        return self::where('trade_no',$trade_no)->find() ;
    }

    // 已付款
    public function getStatusTextAttr($value,$data){

        $status = [
            '0'=>['text'=>'未付款','style'=>'light'],
            '1'=>['text'=>'已付款','style'=>'success'],
            '2'=>['text'=>'完成','style'=>'dark'],
            '3'=>['text'=>'过期','style'=>'warning']];

        return $status[$data['status']] ;
    }

    public static function rebackCard(){
        //getCurrentTime()
        $list = self::hasWhere('card',function($query) {
            $query->where('status', '=', '1');
        })->with('card')->where([
            ['far_order_goods.status','=',0],
            ['goods_type','=',2],
            ['card_id','>',0],
            ['out_time','<',getCurrentTime()]
        ])->select();
        //print_r($list->count());
        $data = [] ;
        $data2 = [] ;
        $ids = [] ;
        foreach($list as $value){
            if( in_array($value->card_id,$ids ) ){
                continue ;
            }
            array_unshift($data,['id'=>$value->card_id,'status'=>0]) ;
            array_unshift($data2,['id'=>$value->id,'status'=>3]) ;
            array_unshift($ids,$value->card_id);
        }
        //print_r($ids);
        if( !empty( $ids ) ){

            $card = new Card;
            $card->saveAll($data);

            $orderGoods = new OrderGoods;
            $orderGoods->saveAll($data2);

        }
        //Card::update($ids);
    }

    public function goods(){
        return $this->hasOne('goods','id','goods_id') ;
    }

    public function card(){
        return $this->hasOne('card','id','card_id') ;
    }
}
