<?php

namespace common\models\forms;

use backendApi\modules\v1\models\Admin;
use common\components\Model;
use common\helpers\Date;
use common\helpers\Form;
use common\libs\logging\operate\AdminOperate;
use common\models\EmployLevel;
use yii\helpers\Json;

/**
 * Login form
 */
class EmployLevelForm extends Model {
    public $id;
    public $levelName;          // 级别名称
    public $locationNum;        // 区域数量
    public $locationPerf;       // 单区业绩
    public $newPerf;            // 当区新增业绩
    public $minEmployLevel;     // locationNum个区域内存在什么级别的会员
    public $sort;               // 等级排序
    public $iconType;               // 等级排序
    public $iconNum;               // 等级排序
    public $otherDepartPerf;       // 其它部门的累计推荐业绩

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'levelName', 'locationNum', 'locationPerf', 'newPerf', 'minEmployLevel', 'sort', 'iconType', 'iconNum', 'otherDepartPerf'], 'trim', 'on' => ['add', 'edit']],
            [['id'], 'required', 'on' => 'edit'],
            [['id'], 'exist', 'targetClass' => EmployLevel::class, 'targetAttribute' => 'ID'],
            [['levelName', 'locationNum', 'locationPerf', 'newPerf', 'sort'], 'required'],
            [['minEmployLevel'], 'exist', 'targetClass' => EmployLevel::class, 'targetAttribute' => 'ID'],
            [['locationNum', 'sort'], 'integer'],
            [['locationPerf', 'newPerf', 'otherDepartPerf'], 'price'],
            [['iconType', 'iconNum'], 'number', 'max' => 10, 'min' => 0, 'on' => 'edit'],
            ['iconType', 'isIconType', 'on' => 'edit'],
            ['iconNum', 'isIconNum', 'on' => 'edit'],
        ];
    }

    /**
     * 图标类型判断
     * @param $attributes
     */
    public function isIconType($attributes) {
        if (!in_array($this->iconType, [0, 1, 2, 3])) {
            $this->addError($attributes, '请选择正确的图标');
        }
    }

    public function isIconNum($attributes) {
        if (!in_array($this->iconType, [0, 1, 2, 3])) {
            $this->addError($attributes, '请选择正确的图标');
        }
    }

    /**
     * 编辑
     * @return EmployLevel|null|static
     */
    public function edit() {
        if (!$this->validate()) {
            return null;
        }
        if ($this->scenario == 'add') {
            $this->addError('id', '提交场景不存在');
            return null;
            $model = new EmployLevel();
            $model->CREATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->CREATED_AT = Date::nowTime();
        } elseif ($this->scenario == 'edit') {
            $model = EmployLevel::findOne(['ID' => $this->id]);
            $model->UPDATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->UPDATED_AT = Date::nowTime();
        } else {
            $this->addError('id', '提交场景不存在');
            return null;
        }
        //$model->LEVEL_NAME = $this->levelName;
        //$model->LOCATION_NUM = $this->locationNum;
        //$model->LOCATION_PERF = $this->locationPerf;
        //$model->NEW_PERF = $this->newPerf;
        //$model->MIN_EMPLOY_LEVEL = $this->minEmployLevel;
        //$model->SORT = $this->sort;
        $model->ICON_TYPE = $this->iconType;
        $model->ICON_NUM = $this->iconNum;
        $model->OTHER_DEPART_PERF = $this->otherDepartPerf;
        if ($model->save()) {
            return $model;
        } else {
            $this->addErrors($model->getErrors());
            return null;
        }
    }

    /**
     * 聘级奖金配置
     * @return bool|null
     * @throws \yii\db\Exception
     */
    public function updateBonus(){
        $beforeData = EmployLevel::getBonusConfig();
        $this->adminOperateLogger->saveBeforeContent=$beforeData;

        $postData = \Yii::$app->request->post('data');
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            foreach ($postData as $value) {
                $empLevelModel = EmployLevel::findOne(['ID' => $value['ID']]);
                if ($empLevelModel) {
                    $empLevelModel->YC_PERCENT_ARR = Json::encode($value['YC_PERCENT_ARR']);
//                    $empLevelModel->CF_BASE_NUM = $value['CF_BASE_NUM'];
//                    $empLevelModel->CF_PERCENT = $value['CF_PERCENT'];
//                    $empLevelModel->LX_BASE_NUM = $value['LX_BASE_NUM'];
//                    $empLevelModel->LX_PERCENT = $value['LX_PERCENT'];
                    $empLevelModel->RX_PERCENT = $value['RX_PERCENT'];
                    $empLevelModel->LEVEL_SCORE = $value['LEVEL_SCORE'];
                    $empLevelModel->UPGRADE_SCORE = $value['UPGRADE_SCORE'];
                    if (!$empLevelModel->save()) {
                        throw new \Exception(Form::formatErrorsForApi($empLevelModel->getErrors()));
                    }
                }
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->addError('updateBonus', $e->getMessage());
            return null;
        }

        $afterData = EmployLevel::getBonusConfig();
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新聘级奖金配置',
        ]);
        return true;
    }
}
