<?php
namespace common\models\forms;

use common\components\Model;
use common\models\Order;
use yii\base\Exception;

class OrderInvoiceRemarkForm extends Model
{
    public $orderSn;
    public $invoiceRemark;
    public $orderMethod;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['orderSn'], 'trim'],
            [['orderSn'], 'required'],
            ['invoiceRemark', 'string', 'max' => 50000],
            ['orderMethod', 'string'],
            ['orderMethod', 'in', 'range' => ['Cash', 'Credit Card', 'Direct Banking', 'Cheque']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'orderSn' => '订单号',
            'invoiceRemark' => '发票备注',
            'orderMethod' => '支付方式',
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [];

        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * @throws Exception
     */
    public function remarkOrderInvoice()
    {
        if (!$this->validate()) {
            return null;
        }

        $sn = $this->orderSn;
        // 订单详情
        $orderInfo = Order::findOneAsArray(['SN' => $sn]);

        if (!$orderInfo) {
            throw new Exception('订单不存在');
        }

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            Order::updateAll(
                ['INVOICE_REMARK' => $this->invoiceRemark,'METHOD'=>$this->orderMethod],
                'SN=:SN',
                ['SN' => $sn]
            );

            $transaction->commit();
        } catch(Exception $e) {
            $transaction->rollBack();
            $this->addError('add', $e->getMessage());
            return null;
        }

        return true;
    }
}
