<?php

namespace common\models\forms;

use common\helpers\Cache;
use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\user\Balance;
use common\helpers\user\Info;
use common\helpers\user\Status;
use common\libs\logging\operate\AdminOperate;
use common\models\PerfPeriod;
use common\models\Period;
use common\models\UserWallet;
use common\models\User;
use common\models\UserClose;
use common\models\UserInfo;
use common\models\UserPerf;
use common\models\UserStatusAudit;
use common\models\Withdraw;
use yii\base\Exception;

/**
 * Login form
 */
class UserTransferPropForm extends Model {
    public $userIds;
    public $allowTransfer;
    public $transferProp;
    public $remark;

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

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['userIds', 'transferProp', 'allowTransfer', 'remark'], 'trim'],
            [['transferProp', 'userIds'], 'required']
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios() {
        $parentScenarios = parent::scenarios();
        $customScenarios = [
            'change' => ['userIds', 'transferProp', 'allowTransfer', 'remark'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    public function attributeLabels() {
        return [
            'userIds' => '会员ID',
            'transferProp' => '转账比例',
        ];
    }

    /**
     * 调整比例
     * @return null
     * @throws \yii\db\Exception
     */
    public function change() {
        if (!$this->validate()) {
            return null;
        }
        $this->adminOperateLogger->setIsBatch(true)->beforeUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,ALLOW_TRANSFER,TRANSFER_PROP']);
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $allUidIn = implode("','", $this->userIds);
            if(!UserInfo::updateAll(['ALLOW_TRANSFER'=>$this->allowTransfer?$this->allowTransfer:0,'TRANSFER_PROP' => $this->transferProp], "USER_ID IN ('" . $allUidIn . "')")){
                throw new Exception('调整会员转账/提现比例失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return null;
        }
        $this->adminOperateLogger->setIsBatch(true)->afterUpdate($this->userIds, 'USER_ID',['select'=>'USER_ID,ALLOW_TRANSFER,TRANSFER_PROP']);
        $this->adminOperateLogger->setBatchField('USER_ID')->clean()->save([
            'optType' => '调整会员转账/提现比例',
            'remark' => $this->remark,
        ]);
        return $this->userIds;
    }

}
