<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\LoggerTool;
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 $taxRate;
    public $cover;
    public $sellPrice;
    public $sellPriceStandard;
    public $marketPrice;
    public $pricePv;
    //public $point;
    public $storeNums;
    public $content;
    public $sort;
    public $status;
    public $categoryType;

    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', 'categoryType', 'sellPriceStandard'], 'required'],
            [['id'], 'required', 'on'=>'edit'],
            [['id'], 'exist', 'targetClass'=>ShopGoods::class, 'targetAttribute'=>'ID'],
            [['sellPrice','marketPrice','pricePv', 'sellPriceStandard'], 'price'],
            [['id'], 'initModel'],
            [['selectedIds'], 'isSelected'],
            [['sort'], 'isSort'],
            [['sellDiscount'], 'isDiscount'],
        ];
    }

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

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'add' => ['goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','sellPrice','marketPrice','pricePv','storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate', 'taxAmount'],
            'edit' => ['id','goodsName','sellDiscount','giftType', 'sellType','goodsNo','unit','sellPrice','marketPrice','pricePv', 'storeNums', 'content','sort','cover', 'categoryType', 'sellPriceStandard', 'taxRate'],
            '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, '数据不存在');
        }
    }

    /**
     * 前置数据填充和校验.
     * @return bool
     */
    public function beforeValidate()
    {
        if($this->categoryType){
            // 处理sellType
            $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
            $sellType = $categoryType[$this->categoryType]['sell_type'] ?? [];
//            print_r($formModel);
//            print_r($this);
//            exit;
            if (!$sellType) {
                $this->addError('add', '商品购买方式错误');
            } else {
                foreach ($sellType as $item) {
                    if (!in_array($item['id'], array_keys(ShopGoods::SALE_TYPE))) {
                        $this->addError('add', '商品购买方式错误');
                        break;
                    }
                }
                // 购买方式格式化为','分割的方式
                $this->sellType = implode(',', array_column($sellType, 'id'));
                // 如果是普通商品,有PV，旅游、名车、豪宅商品没有PV
                if ($this->categoryType != 1) {
                    $this->pricePv = 0;
                }
            }
        }

        return parent::beforeValidate();
    }

    /**
     * 批量数据
     * @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之间的数');
        }
    }

    /**
     * 添加
     * @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 ? $this->unit : '个';
            $shopGoods->COVER = $this->cover ? $this->cover : '';
            $shopGoods->SELL_PRICE_STANDARD = $this->sellPriceStandard;
            $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->TAX_RATE = $this->taxRate;
            $shopGoods->SORT = $this->sort;
            $shopGoods->CATE_ID = '1';
            $shopGoods->CREATED_AT = Date::nowTime();
            $shopGoods->CATEGORY_TYPE = $this->categoryType;
            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->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_STANDARD = $this->sellPriceStandard;
            $model->SELL_PRICE = $this->sellPrice;
            $model->MARKET_PRICE = $this->marketPrice;
            $model->PRICE_PV = $this->pricePv;
            $model->TAX_RATE = $this->taxRate;
            //$model->POINT = $this->point;
            $model->CONTENT = $this->content;
            $model->STORE_NUMS = $this->storeNums;
            $model->SORT = $this->sort;
            $model->UPDATED_AT = Date::nowTime();
            $model->CATEGORY_TYPE = $this->categoryType;
            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];
    }

    /**
     * 异步更新商品属性表
     * @return bool
     */
    public function updateAsync(){
        // 汇率
        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
        // 商品列表
        $goods = ShopGoods::findAll(['STATUS' => 1]);

        $transaction = \Yii::$app->db->beginTransaction();
        try{
            foreach ($goods as $good) {
                $model = clone $good;
                $model->SELL_PRICE = $good->SELL_PRICE_STANDARD * $exchangeRate;
                $model->MARKET_PRICE = $good->SELL_PRICE_STANDARD * $exchangeRate;
                $model->UPDATED_AT = Date::nowTime();
                if (!$model->save()) {
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }
            }

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