<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "pay_order_user_t".
 *
 * type: 1:新保, 2:跟踪, 3:续保, 4:送单
 * @property integer $id
 * @property integer $user_id
 * @property integer $order_id
 * @property string $pay_date
 * @property integer $type
 * @property integer $is_own
 * @property string $should_pay
 * @property string $real_pay
 * @property string $created_at
 * @property string $updated_at
 */
class PayOrderUserT extends \common\models\Base
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'pay_order_user_t';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'order_id', 'type'], 'required'],
            [['user_id', 'order_id', 'type','is_own'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['should_pay','real_pay'], 'number'],
            [['pay_date'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'order_id' => 'Order ID',
            'pay_date' => 'Pay Date',
            'type' => 'Type',
            'is_own' => 'Is Own',
            'should_pay' => 'Should Pay',
            'real_pay' => 'Real Pay',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getUser()
    {
        return $this->hasOne(UserT::className(),['id'=>'user_id']);
    }

    public function getOrder()
    {
        return $this->hasOne(OrderT::className(),['id'=>'order_id']);
    }

    public function calPay()
    {
        $should_pay = 0;

        $order_info = $this->order;
        if(!$order_info) return;
        $caiwu_info = $order_info->caiwu;
        if(!$caiwu_info) return;
        if($this->type == 1) {
            $should_pay = $caiwu_info->money1;
        }
        if($this->type == 2) {
            $should_pay = $caiwu_info->money2;
        }
        if($this->type == 3) {
            $should_pay = $caiwu_info->money3;
        }
        if($this->type == 4) {
            $should_pay = $caiwu_info->send_money;
        }
        if($this->type == 5) {
            $should_pay = $caiwu_info->money4;
        }
        if($this->type == 6) {
            $should_pay = $caiwu_info->money5;
        }
        $this->should_pay = round($should_pay,2);

        $real_pay = $should_pay;
        if($this->is_own == 1) {
            $real_pay -= $order_info->total1_dis;
            $order_gifts = $order_info->orderGifts;
            foreach($order_gifts as $order_gift) {
                $real_pay -= $order_gift->price;
            }
        }
        $this->real_pay = round($real_pay,2);

        $this->save();
    }
}