<?php

namespace common\models;

use backendApi\modules\v1\models\Admin;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\user\Info;
use common\helpers\user\Status;
use common\models\forms\UserBindForm;
use Yii;
use yii\base\Exception;
use common\libs\logging\operate\valueType\Config as ValueTypeConfig;

/**
 * This is the model class for table "{{%USER_BIND}}".
 *
 * @property string $ID
 * @property string $USER_ID 会员ID
 * @property string $MAIN_UID 主会员ID
 * @property int $PERIOD_NUM 加入时期数
 * @property int $IS_DEL 是否删除
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 修改时间
 * @property string $CREATE_ADMIN 创建管理员
 * @property string $CREATE_USER 创建会员
 * @property string $UPDATE_ADMIN 修改管理员
 * @property string $UPDATE_USER 修改会员
 * @property int $DELETED_AT 已删除
 */
class UserBind extends \common\components\ActiveRecord {
    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%USER_BIND}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['USER_ID', 'MAIN_UID', 'PERIOD_NUM', 'CREATED_AT'], 'required'],
            [['PERIOD_NUM', 'IS_DEL', 'CREATED_AT', 'UPDATED_AT', 'DELETED_AT'], 'integer'],
            [['ID', 'USER_ID', 'MAIN_UID', 'CREATE_ADMIN', 'CREATE_USER', 'UPDATE_ADMIN', 'UPDATE_USER'], 'string', 'max' => 32],
            [['ID'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'ID' => 'ID',
            'USER_ID' => '会员ID',
            'MAIN_UID' => '主会员ID',
            'PERIOD_NUM' => '加入时期数',
            'IS_DEL' => '是否删除',
            'CREATE_ADMIN' => '创建管理员',
            'CREATE_USER' => '创建会员',
            'UPDATE_ADMIN' => '修改管理员',
            'UPDATE_USER' => '修改会员',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '修改时间',
            'DELETED_AT' => '已删除',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser() {
        return $this->hasOne(User::className(), ['ID' => 'USER_ID']);
    }

    /**
     * 为删除的会员点位体系设置新的主会员
     * @param $userId
     */
    public static function setNewBindWhenUserDel($userId) {
        //如果是主点位
        if (self::find()->where('USER_ID=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userId])->orderBy('CREATED_AT ASC')->asArray()->one()) {
            self::setNewMainBind($userId);
        }
        self::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
    }

    /**
     * 向下找新的会员成为新的主会员，优先找不以hz开头的会员
     * @param $userId
     * @param null $idCard
     * @return bool
     * @throws \Exception
     */
    public static function setNewMainBind($userId,$idCard=null) {
        //是否是主会员
        if (!self::find()->where('USER_ID=:USER_ID AND MAIN_UID=:USER_ID AND IS_DEL=0', [':USER_ID' => $userId])->exists()) {
            return false;
        }
        //取同一身份证的最近会员
        if(!$idCard) $idCard = Info::getIdCardByUserId($userId);
        //把所有实名身份证的会员绑到一起
        $hasUsers = User::findAllAsArray('ID_CARD=:ID_CARD AND VERIFIED=1 AND STATUS=1 AND DELETED=0',[':ID_CARD'=>$idCard],'ID');
        if($hasUsers){
            $period = Period::instance();
            $periodNum = $period->getNowPeriodNum();
            foreach ($hasUsers as $u){
                if(!self::find()->where('USER_ID=:USER_ID AND IS_DEL=0',[':USER_ID'=>$u['ID']])->exists()){
                    UserInfo::updateAll(['IS_BIND' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $u['ID']]);
                    // 添加会员合作点位
                    $model = new UserBind();
                    $model->USER_ID = $u['ID'];
                    $model->MAIN_UID = $userId;
                    $model->PERIOD_NUM = $periodNum;
                    $model->IS_DEL = 0;
                    $model->CREATE_ADMIN = \Yii::$app->user->id??'';
                    $model->CREATED_AT = Date::nowTime();
                    if (!$model->save()) {
                        throw new \Exception($model->getErrors());
                    }
                }
            }
        }
        $newMainUid = 0;
        if ($newMain = User::find()->select('ID')->where("ID!=:ID AND ID_CARD=:ID_CARD AND IS_UNION=0 AND VERIFIED=1 AND STATUS=1 AND DELETED=0", [':ID'=>$userId, ':ID_CARD' => $idCard])->orderBy('CREATED_AT ASC')->asArray()->one()) {
            $newMainUid = $newMain['ID'];
        } else {
            if ($newMain = User::find()->select('ID')->where("ID!=:ID AND ID_CARD=:ID_CARD AND STATUS=1 AND VERIFIED=1 AND DELETED=0", [':ID'=>$userId, ':ID_CARD' => $idCard])->orderBy('CREATED_AT ASC')->asArray()->one()) {
                $newMainUid = $newMain['ID'];
            }
        }
        if ($newMainUid) {
            //设置主会员
            UserInfo::updateAll(['IS_BIND_MAIN' => 1], 'USER_ID=:USER_ID', [':USER_ID' => $newMainUid]);
            //更新绑定表的主会员
            self::updateAll(['MAIN_UID' => $newMainUid,'UPDATED_AT'=>Date::nowTime()], 'MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userId]);
            //取消原来主会员
            UserInfo::updateAll(['IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
        }
    }

    /**
     * 商城报首购单，rpc中绑定
     * @param $userIds
     * @param $idCard
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public static function zcBind($userIds, $idCard){
        if(!empty($userIds)){
            // 从一批的首购会员中拿出第一个去数据库里面查找
            // 拿身份证编号去数据库中查找看看有没有同身份证并实名认证的会员
            $sameUsers = User::find()->select('ID')->where('ID!=:ID AND VERIFIED=1 AND ID_CARD=:ID_CARD', [':ID' => $userIds[0], ':ID_CARD' => $idCard])->orderBy('CREATED_AT ASC')->asArray()->all();
            // 如果有
            if($sameUsers){
                // 把这些相同身份证号的会员追加到$userIds的数组中
                $mainUid = $sameUsers[0]['ID'];
                foreach ($sameUsers as $u) {
                    //是否有绑定，有则绑定到绑定位置，无则新建绑定
                    $hasBind = self::find()->select('MAIN_UID')->where('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => $u['ID']])->asArray()->one();
                    if ($hasBind) {
                        $mainUid = $hasBind['MAIN_UID'];
                        break;
                    }
                }
                foreach($userIds as $uid){
                    // 是否有绑定关系没有就新增
                    if(!self::find()->select('MAIN_UID')->where('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => $uid])->asArray()->exists()){
                        $userBindForm = new UserBindForm();
                        $userBindForm->scenario = 'autoBind';
                        $userBindForm->userId = $uid;
                        $userBindForm->mainUid = $mainUid;
                        if (!$userBindForm->autoBind()) {
                            throw new Exception('与其他同身份证会员点位绑定失败'.Form::formatErrorsForApi($userBindForm->getErrors()));
                        }
                    }
                }
            }
            // 如果没有
            else {
                // 只有当新注册的会员数量大于一个才需要绑定
                if(count($userIds) > 1){
                    $mainUid = $userIds[0];
                    unset($userIds[0]);
                    // 把这些人都循环绑定到一起
                    foreach($userIds as $uid){
                        $userBindForm = new UserBindForm();
                        $userBindForm->scenario = 'autoBind';
                        $userBindForm->userId = $uid;
                        $userBindForm->mainUid = $mainUid;
                        if (!$userBindForm->autoBind()) {
                            throw new Exception('点位绑定失败'.Form::formatErrorsForApi($userBindForm->getErrors()));
                        }
                    }
                }
            }
        }
    }

    /**
     * 自动绑定
     * @param $userId
     * @param null $idCard
     * @param int $verified
     * @return bool|string
     * @throws \yii\db\Exception
     */
    public static function autoBind($userId,$idCard=null,$verified=1) {
        if($verified==0){
            if (self::find()->where('USER_ID=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0',[':MAIN_UID'=>$userId])->exists()) {
                self::setNewMainBind($userId);
            }
            UserInfo::updateAll(['IS_BIND' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
            self::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
            return '取消绑定关系成功';
        }else {
            if (self::find()->where('USER_ID=:MAIN_UID AND MAIN_UID=:MAIN_UID AND IS_DEL=0',[':MAIN_UID'=>$userId])->exists()) {
                return '此会员是主会员，绑定关系未改变';
            }
            //清除原有绑定关系
            self::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
            UserInfo::updateAll(['IS_BIND' => 0, 'IS_BIND_MAIN' => 0], 'USER_ID=:USER_ID', [':USER_ID' => $userId]);
            //获取新的绑定关系
            if (!$idCard) {
                $idCard = Info::getIdCardByUserId($userId);
            }
            $hasUsers = User::find()->select('ID')->where('ID!=:ID AND VERIFIED=1 AND ID_CARD=:ID_CARD', [':ID' => $userId, ':ID_CARD' => $idCard])->orderBy('CREATED_AT ASC')->asArray()->all();
            //如果有同一身份证的其他点位
            if ($hasUsers) {
                $mainUid = $hasUsers[0]['ID'];
                foreach ($hasUsers as $u) {
                    //是否有绑定，有则绑定到绑定位置，无则新建绑定
                    $hasBind = self::find()->select('MAIN_UID')->where('USER_ID=:USER_ID AND IS_DEL=0 AND MAIN_UID!=:MAIN_UID', [':USER_ID' => $u['ID'], ':MAIN_UID' => $userId])->asArray()->one();
                    if ($hasBind) {
                        $mainUid = $hasBind['MAIN_UID'];
                        break;
                    }
                }
                $userBindForm = new UserBindForm();
                $userBindForm->scenario = 'autoBind';
                $userBindForm->userId = $userId;
                $userBindForm->mainUid = $mainUid;
                if ($result = $userBindForm->autoBind()) {
                    return '实名验证成功，此会员编号为非主会员编号，不可提现，可以转账';
                } else {
                    return false;
                }
            } else {
                /*$userBindForm = new UserBindForm();
                $userBindForm->scenario = 'autoBind';
                $userBindForm->userId = $userId;
                $userBindForm->mainUid = $userId;
                if ($result = $userBindForm->autoBind()) {
                    return '实名验证成功';
                } else {
                    return false;
                }*/
                return '实名验证成功';
            }
        }
    }

    /**
     * 是否绑定在一起
     * @param $oneId
     * @param $twoId
     * @return bool
     */
    public static function sameBind($oneId, $twoId) {
        $oneBind = self::findOneAsArray('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => $oneId], 'MAIN_UID');
        $twoBind = self::findOneAsArray('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => $twoId], 'MAIN_UID');
        if ($oneBind && $twoBind && $oneBind['MAIN_UID'] == $twoBind['MAIN_UID']) {
            return true;
        }
        return false;
    }

    /**
     * 操作日志记录条件
     * @return array
     */
    public function attrLabelsWithLogType(){
        return [
            'USER_ID' => '会员ID',
            'MAIN_UID' => [
                'label' => '主会员编号',
                'type' => function($data){
                    $value = $data['value'];
                    return Info::getUserNameByUserId($value);
                },
            ],
            'CREATE_ADMIN' => [
                'label' => '创建管理员',
                'type' => function($data){
                    $value = is_array($data) && isset($data['value']) ? $data['value'] : '';
                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
                    return !empty($result) ? $result['ADMIN_NAME'] : '';
                },
            ],
            'UPDATE_ADMIN' => [
                'label' => '修改管理员',
                'type' => function($data){
                    $value = is_array($data) && isset($data['value']) ? $data['value'] : '';
                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
                    return !empty($result) ? $result['ADMIN_NAME'] : '';
                },
            ],
            'CREATED_AT' => [
                'label' => '创建时间',
                'type' => ValueTypeConfig::DATE_TIME_TYPE,
            ],
            'UPDATED_AT' => [
                'label' => '修改时间',
                'type' => ValueTypeConfig::DATE_TIME_TYPE,
            ],
        ];
    }
}
