<?php

namespace backend\models;

use backend\helpers\DateTimeHelper;
use Yii;

/**
 * This is the model class for table "crm_commission".
 *
 * @property integer $id
 * @property integer $login
 * @property integer $member_id
 * @property double $forex
 * @property double $metal
 * @property double $cfd
 * @property double $gold
 * @property double $silver
 * @property double $wy
 * @property double $stock
 * @property double $btc
 * @property integer $in_time
 */
class Commission extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'crm_commission';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('dbXcrm');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['login', 'member_id', 'in_time'], 'required'],
            [['login', 'member_id', 'in_time'], 'integer'],
            [['forex', 'metal', 'cfd', 'gold', 'silver', 'wy', 'stock', 'btc'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '主键ID',
            'login' => 'MT4登录ID',
            'member_id' => '上级代理商ID',
            'forex' => 'forex每手佣金',
            'metal' => 'metal每手佣金',
            'cfd' => 'cfd',
            'gold' => '黄金',
            'silver' => '白银',
            'wy' => '外佣',
            'stock' => '股指',
            'btc' => '比特币',
            'in_time' => '创建时间',
        ];
    }
    
    /**
     * 根据member_id和logins获取佣金率，返回二位数组，键为login
     * @param int $member_id
     * @param array $logins
     * @return array
     */
    public function getCommissionByMemberIdAndLogins($member_id, $logins)
    {
        $commissionWhere = [
            'and',
            ['=', 'member_id', $member_id],
            ['in', 'login', $logins],
        ];
        $commissionList = Commission::find()->where($commissionWhere)->asArray()->all();
        $commissionList2 = [];
        foreach ($commissionList as $k => $v) {
            $commissionList2[$v['login']] = $v;
        }
        return $commissionList2;
    }
    
    /**
     * 批量设置返佣规则
     * @param array $post
     * @return array
     */
    public function batchSet($post)
    {
        $result = ['code' => 0, 'data' => [], 'message' => ''];

        $userId = isset($post['userId']) ? intval($post['userId']) : 0;
        $ibMemberId = isset($post['ibMemberId']) ? intval($post['ibMemberId']) : 0;
        $setType = isset($post['setType']) ? $post['setType'] : '';
        $subIbLogins = isset($post['subordinateIbLogins']) ? intval($post['subordinateIbLogins']) : 0;
        $forex = isset($post['forex']) ? floatval($post['forex']) : 0;
        $metal = isset($post['metal']) ? floatval($post['metal']) : 0;
        $cfd = isset($post['cfd']) ? floatval($post['cfd']) : 0;
        $gold = isset($post['gold']) ? floatval($post['gold']) : 0;
        $silver = isset($post['silver']) ? floatval($post['silver']) : 0;
        $wy = isset($post['wy']) ? floatval($post['wy']) : 0;
        $stock = isset($post['stock']) ? floatval($post['stock']) : 0;
        $btc = isset($post['btc']) ? floatval($post['btc']) : 0;

        if (!$ibMemberId || !in_array($setType, ['direct', 'indirect'])) {
            $result['message'] = '参数错误';
            return $result;
        }

        $member = Member::findById($ibMemberId);
        if (!$member) {
            $result['message'] = '该代理商不存在';
            return $result;
        }

        $customerList = [];
        if ($setType === 'direct') {
            // 直属返佣
            $customerList = Mt4Users::findChildLogins($ibMemberId);
        } else {
            // 差佣
            $subIbMemberList = Member::find()->andWhere("FIND_IN_SET({$subIbLogins}, logins)")
                ->andWhere(['type' => Member::MEMBER_TYPE_IB])
                ->asArray()
                ->all();
            if (!$subIbMemberList) {
                $result['message'] = '未找到该账户';
                return $result;
            }
            $subIbMemberIds = array_column($subIbMemberList, 'id');
            
            $memberModel = new Member();
            $members = $memberModel->findChildren($ibMemberId);
            if ($members) {
                $memberIds = array_column($members, 'id');
                foreach ($subIbMemberIds as $k => $v) {
                    if (in_array($v, $memberIds)) {
                        $customerList = array_merge($customerList, Mt4Users::findChildLogins($v));
                    }
                }
            }
        }
        
        $customerList2 = [];
        foreach ($customerList as $k => $v) {
            $customerList2[$v['id']] = $v;
        }
        $customerList = $customerList2;

        foreach ($customerList as $k => $v) {
            $oldCommission = static::find()->where(['member_id' => $ibMemberId, 'login' => $v['login']])->limit(1)->one();
            if ($oldCommission) {
                $oldCommission->delete();
            }
            
            $commission = new static();
            
            $commission->login = $v['login'];
            $commission->member_id = $ibMemberId;
            $commission->forex = $forex;
            $commission->metal = $metal;
            $commission->cfd = $cfd;
            $commission->gold = $gold;
            $commission->silver = $silver;
            $commission->wy = $wy;
            $commission->stock = $stock;
            $commission->btc = $btc;
            $commission->in_time = round(microtime(true) * 1000);
            
            if ($commission->save()) {
                $commissionLog = new CommissionLog();
                $commissionLog->login = $v['login'];
                $commissionLog->member_id = $ibMemberId;
                $commissionLog->type = $setType;
                $commissionLog->forex = $forex;
                $commissionLog->metal = $metal;
                $commissionLog->cfd = $cfd;
                $commissionLog->gold = $gold;
                $commissionLog->silver = $silver;
                $commissionLog->wy = $wy;
                $commissionLog->stock = $stock;
                $commissionLog->btc = $btc;
                $commissionLog->modify_user = $userId;
                $commissionLog->in_time = DateTimeHelper::microtime_float();
                $commissionLog->save();
            }
        }
        
        $result['code'] = 1;

        return $result;
    }
    
    /**
     * 删除指定MT4账号的返佣规则
     * @param int $login
     * @return bool|int
     */
    public static function deleteCommissionsByLogin($login)
    {
        if ($login == null) {
            return false;
        }
        return static::deleteAll(['login' => $login]);
    }

    /**
     * 查询指定login和代理商id的返佣规则
     * @param int $login
     * @param int $memberId
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function findByCommission($login, $memberId)
    {
        return static::find()->where(['login' => $login, 'member_id' => $memberId])->limit(1)->asArray()->one();
    }
    
}
