<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\helpers\Form;
use common\libs\logging\operate\AdminOperate;
use common\models\ShopGoods;
use yii\base\Exception;

/**
 * Login form
 */
class ShopGoodsForm extends Model
{
    public $selectedIds;
    public $id;
    public $goodsName;
    public $type;
    public $sellDiscount;
    public $giftType;
    public $sellType;
    public $goodsNo;
    public $unit;
    public $cover;
    public $sellPrice;
    public $marketPrice;
    public $pricePv;
    //public $point;
    public $storeNums;
    public $content;
    public $sort;
    public $status;
    public $statusdate;
    public $goodsstatusdate;
    public $goodsdate;

    private $_model;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id','sellDiscount','giftType','sellType','goodsNo', 'goodsName', 'unit', 'sellPrice', 'marketPrice', 'pricePv', 'storeNums', 'content', 'sort','status','cover'], 'trim'],
            [['goodsName','sellDiscount','giftType','goodsNo', 'storeNums','sellPrice','marketPrice','pricePv', 'sort','status', 'type'], 'required'],
            [['id'], 'required', 'on'=>'edit'],
            [['id'], 'exist', 'targetClass'=>ShopGoods::class, 'targetAttribute'=>'ID'],
            [['sellPrice','marketPrice','pricePv'], 'price'],
            [['id'], 'initModel'],
            [['selectedIds'], 'isSelected'],
            [['sort'], 'isSort'],
            [['sellDiscount'], 'isDiscount'],
            [['statusdate','goodsstatusdate'],'match','pattern'=>'/^[0-1]{1,1}$/'],
            [['type'], 'isType'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'selectedIds' => '商品ID',
            'id' => '产品ID',
            'goodsName' => '商品名称',
            'sellDiscount' => '会员折扣',
            'giftType' => '商品类型',
            'sellType' => '出售方式',
            'goodsNo' => '产品编号',
            'unit' => '单位',
            'cover' => '封面',
            'sellPrice' => '销售价格',
            'marketPrice' => '市场价格',
            'pricePv' => '销售PV',
            //'point' => '兑换积分',
            'storeNums' => '库存',
            'content' => '产品详情',
            'listOrder' => '排序',
            'type' => '商品来源',
        ];
    }

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','sellPrice','marketPrice','pricePv','storeNums', 'content','sort','cover', 'type'],
            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','sellPrice','marketPrice','pricePv', 'storeNums', 'content','sort','cover','statusdate','goodsstatusdate','goodsdate', 'type'],
            'changeStatus' => ['selectedIds', 'status'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 初始化model
     * @param $attributes
     */
    public function initModel($attributes) {
        $this->_model = ShopGoods::findOne(['ID' => $this->id]);
        if (!$this->_model) {
            $this->addError($attributes, '数据不存在');
        }
    }
    /**
     * 批量数据
     * @param $attributes
     */
    public function isSelected($attributes) {
        if (!$this->selectedIds) {
            $this->addError($attributes, '必须选择一条数据');
        }
        if (!is_array($this->selectedIds)) {
            $this->selectedIds = [$this->selectedIds];
        }
    }
    /**
     * 排序需大于等于1
     * @param $attributes
     */
    public function isSort($attributes) {
        if ($this->sort < 1) {
            $this->addError($attributes, '排序请填写大于等于1的数字');
        }
    }

    // 折扣为0-1
    public function isDiscount($attributes) {
        if ($this->sellDiscount < 0 || $this->sellDiscount > 1 || !is_numeric($this->sellDiscount)) {
            $this->addError($attributes, '折扣请填写0-1之间的数');
        }
    }

    /**
     * 根据商品类型处理支付类型
     * @param $attributes
     */
    public function isType() {
//        $this->sellType = $this->type == '1' ? implode(',', array_keys(ShopGoods::LOCAL_PAY)) : implode(',', array_keys(ShopGoods::ONLINE_PAY));
        $this->sellType = $this->type == '1' ? implode(',', array_keys(ShopGoods::LOCAL_PAY)) : '5';
    }

    /**
     * 添加
     * @return ShopGoods|null
     * @throws \yii\db\Exception
     */
    public function add() {
        if (!$this->validate()) {
            return null;
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 添加商品
            $shopGoods = new ShopGoods();
            $shopGoods->GOODS_NAME = $this->goodsName;
            //$shopGoods->TYPE = $this->type;
            $shopGoods->SELL_DISCOUNT = $this->sellDiscount;
            $shopGoods->GIFT_TYPE = implode(',',$this->giftType);
            // $shopGoods->SELL_TYPE = implode(',',$this->sellType);
            $shopGoods->SELL_TYPE = $this->sellType;
            $shopGoods->GOODS_NO = $this->goodsNo;
            $shopGoods->UNIT = $this->unit ?: '个';
            $shopGoods->COVER = $this->cover ?: '';
            $shopGoods->SELL_PRICE = $this->sellPrice;
            $shopGoods->MARKET_PRICE = $this->marketPrice;
            $shopGoods->PRICE_PV = $this->pricePv;
            //$shopGoods->POINT = $this->point;
            $shopGoods->CONTENT = $this->content;
            $shopGoods->STORE_NUMS = $this->storeNums;
            $shopGoods->SORT = $this->sort;
            $shopGoods->CATE_ID = $this->type;
            $shopGoods->CREATED_AT = Date::nowTime();
            if (!$shopGoods->save()) {
                throw new Exception(Form::formatErrorsForApi($shopGoods->getErrors()));
            }

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

    /**
     * 编辑商品
     * @return null
     * @throws \yii\db\Exception
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = $this->_model;
            $model->GOODS_NAME = $this->goodsName;
            $model->TYPE = 0;
            $model->CATE_ID = $this->type ?? $this->_model->CATE_ID;
            $model->SELL_DISCOUNT = $this->sellDiscount;
            $model->GIFT_TYPE = implode(',',$this->giftType);
            // $model->SELL_TYPE = implode(',',$this->sellType);
            $model->SELL_TYPE = $this->sellType;
            $model->GOODS_NO = $this->goodsNo;
            $model->UNIT = $this->unit ? $this->unit : '个';
            $model->COVER = $this->cover ? $this->cover : '';
            $model->SELL_PRICE = $this->sellPrice;
            $model->MARKET_PRICE = $this->marketPrice;
            $model->PRICE_PV = $this->pricePv;
            //$model->POINT = $this->point;
            $model->CONTENT = $this->content;
            $model->STORE_NUMS = $this->storeNums;
            $model->SORT = $this->sort;
            $model->UPDATED_AT = Date::nowTime();
            $model->STATUS_DATE = $this->statusdate;
            $model->GOODS_STATUS_DATE = $this->goodsstatusdate;
            $model->GOODS_DATE = $this->goodsdate / 1000;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        return $model;
    }

    /**
     * 上下架
     * @return null|static
     * @throws \yii\db\Exception
     */
    public function changeStatus() {
        if (!$this->validate()) {
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            foreach ($this->selectedIds as $select) {
                $oneGoods = ShopGoods::findOne(['ID' => $select]);
                //判断状态
                if (($msg = ShopGoods::chkAuditStatus($oneGoods->STATUS, $this->status)) != '') {
                    throw new Exception($msg);
                }
                $oneGoods->STATUS = $this->status;
                $oneGoods->UPDATED_AT = Date::nowTime();
                if (!$oneGoods->save()) {
                    throw new Exception(Form::formatErrorsForApi($oneGoods->getErrors()));
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('changeStatus', $e->getMessage());
            return null;
        }
        return ['status' => $this->status];
    }

}
