<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\user\Info;
use common\libs\logging\operate\UserOperate;
use common\models\Ad;
use common\models\ReceiveAddress;
use common\models\Region;
use common\models\User;
use common\models\UserInfo;
use yii\base\Exception;

/**
 * Login form
 */
class ReceiveAddressForm extends Model
{
    public $id;
    public $consignee;
    public $mobile;
    public $province;
    public $city;
    public $county;
    public $address;
    public $isDefault;

    /**
     * @var ReceiveAddress
     */
    private $_model;


    public function init() {
        parent::init();
        $this->adminOperateLogger = new UserOperate([
            'fetchClass' => ReceiveAddress::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'consignee', 'mobile', 'province', 'city', 'county', 'address', 'isDefault'], 'trim'],
            [['id', 'consignee', 'mobile', 'province', 'city', 'county', 'address'], 'required'],
            [['mobile'], 'mobile'],
            [['province', 'city', 'county'], 'exist', 'targetClass' => Region::class, 'targetAttribute' => 'REGION_CODE'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'consignee' => '收货人',
            'mobile' => '手机号',
            'province' => '省/市',
            'city' => '市/区',
            'county' => '区/县',
            'address' => '详细地址',
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'userAdd' => ['consignee', 'mobile', 'province', 'city', 'county', 'address', 'isDefault'],
            'userEdit' => ['id', 'consignee', 'mobile', 'province', 'city', 'county', 'address', 'isDefault'],
            'userIsDefault' => ['id', 'isDefault'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 校验之前
     * @return bool
     */
    public function beforeValidate()
    {
        $parentResult = parent::beforeValidate();
        if ($this->scenario == 'userAdd' || $this->scenario == 'userEdit' || $this->scenario == 'userIsDefault') {
            if ($this->scenario == 'userAdd') {
                $count = ReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID'=>\Yii::$app->user->id])->count();
                if ($count > 10) {
                    $this->addError('id', '最多只能添加10个收货地址');
                    return $parentResult;
                }
            }
            if ($this->id) {
                $this->_model = ReceiveAddress::findOne(["ID"=>$this->id]);
                if (!$this->_model){
                    $this->addError('id', '地址不存在');
                    return $parentResult;
                }
                if ($this->_model['USER_ID'] != \Yii::$app->user->id){
                    $this->addError('id', '无权修改此地址');
                    return $parentResult;
                }
            } else {
                $this->_model = new ReceiveAddress();
            }
        }

        return $parentResult;
    }

    /**
     * 添加编辑
     * @return ReceiveAddress|null
     * @throws \yii\db\Exception
     */
    public function edit(){
        //var_dump(\Yii::$app->user->id);exit;
        if(!$this->validate()){
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            // 如果设置了此项为默认则清空所有默认
            if ($this->isDefault) {
                ReceiveAddress::updateAll(['IS_DEFAULT' => 0], 'USER_ID=:USER_ID', [':USER_ID'=>\Yii::$app->user->id]);
            }
            if($this->scenario == 'userAdd'){
                $this->_model->USER_ID = \Yii::$app->user->id;
                $this->_model->USER_NAME = Info::getUserNameByUserId(\Yii::$app->user->id);
                $this->_model->CONSIGNEE = $this->consignee;
                $this->_model->MOBILE = $this->mobile;
                $this->_model->PROVINCE = $this->province;
                $this->_model->CITY = $this->city;
                $this->_model->COUNTY = $this->county;
                $this->_model->ADDRESS = $this->address;
                $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
                $this->_model->CREATED_AT = Date::nowTime();
            } elseif($this->scenario == 'userEdit') {
                $this->_model->CONSIGNEE = $this->consignee;
                $this->_model->MOBILE = $this->mobile;
                $this->_model->PROVINCE = $this->province;
                $this->_model->CITY = $this->city;
                $this->_model->COUNTY = $this->county;
                $this->_model->ADDRESS = $this->address;
                $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
                $this->_model->UPDATED_AT = Date::nowTime();
            } elseif($this->scenario == 'userIsDefault') {
                $this->_model->IS_DEFAULT = $this->isDefault ? 1 : 0;
            } else {
                throw new Exception('提交场景不存在');
            }
            if(!$this->_model->save()){
                throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        if($this->scenario == 'adminAdd'){
            $this->adminOperateLogger->afterInsert($this->_model)->clean()->save([
                'optType' => '添加收货地址',
            ]);
        } elseif($this->scenario == 'adminEdit') {
            $this->adminOperateLogger->afterUpdate($this->_model)->clean()->save([
                'optType' => '编辑收货地址',
            ]);
        }
        return $this->_model;
    }

    /**
     * 删除前
     * @param $selected
     */
    public function beforeDelete($selected) {
        $this->adminOperateLogger->fetchClass = Ad::class;
        $this->adminOperateLogger->setIsBatch(true)->beforeDelete($selected, 'ID');
    }
    /**
     * 删除
     * @param $selected
     * @throws Exception
     */
    public function delete($selected) {
        $this->adminOperateLogger->clean()->save([
            'optType' => '删除收货地址',
        ]);
    }
}
