<?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\models\Article;
use common\models\ArticleCategory;
use common\models\DealType;
use common\models\Period;
use common\models\Transfer;
use common\models\User;
use common\models\UserBind;
use common\models\UserBonus;
use common\models\UserInfo;
use yii\base\Exception;

/**
 * Login form
 */
class TransferBonusForm extends Model
{
    public $toUserId;
    public $amount;
    public $fromUserId;

    private $_fromUserInfo;
    private $_toUserInfo;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['toUserId', 'amount', 'fromUserId'], 'trim'],
            [['toUserName', 'amount', 'fromUserId'], 'required'],
            [['amount'], 'price'],
            [['amount'], 'isAmount'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'toUserId' => '转入会员编号',
            'amount' => '金额',
            'fromUserId' => '转出会员编号',
        ];
    }

    /**
     * 归集批量转账
     * @param $main_uid
     * @return Transfer|null
     * @throws \yii\db\Exception
     */
    public function collectBind($main_uid){
        $result = [];
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $userBinds = UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0',[':MAIN_UID'=>$main_uid]);
            if(!$userBinds){
                throw new Exception('不存在点位绑定关系');
            }
            $period = Period::instance();
            $totals=0;
            foreach ($userBinds as $value){
                if($value['USER_ID']==$main_uid) continue;
                $bonus=Balance::getAvailableBalance($value['USER_ID']);
                if($bonus<=0) continue;
                $totals+=$bonus;
                Balance::changeUserBonus($value['USER_ID'], 'bonus', -abs($bonus), ['DEAL_TYPE_ID' => DealType::BIND_TRANSFER_OUT, 'REMARK' => 'To:'.$main_uid]);
                Balance::changeUserBonus($main_uid, 'bonus', abs($bonus), ['DEAL_TYPE_ID' => DealType::BIND_TRANSFER_IN, 'REMARK' => 'From:'.$value['USER_ID']]);
                $array = [
                    'FROM_UID'=>$value['USER_ID'],
                    'TO_UID'=>$main_uid,
                    'FROM_WALLET'=>'bonus',
                    'IN_WALLET'=>'bonus',
                    'AMOUNT'=>$bonus,
                    'PERIOD_NUM'=>$period->getNowPeriodNum(),
                    'CALC_MONTH'=>$period->getNowYearMonth(),
                    'CREATED_AT'=>Date::nowTime(),
                ];
                $result[] = $array;
            }
            if($result) Transfer::batchInsert($result);
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }
        unset($parents ,$res ,$model);
        return $totals;
    }


}
