<?php

namespace common\models;

use backendApi\modules\v1\models\Admin;
use common\helpers\Cache;
use common\helpers\user\Info;
use Yii;
use common\libs\logging\operate\valueType\Config as ValueTypeConfig;

/**
 * This is the model class for table "{{%USER_SYSTEM}}".
 *
 * @property string $ID
 * @property string $SYSTEM_NAME 体系名称
 * @property string $LEADER_UID 领导人ID
 * @property int $PERIOD_NUM 加入时的期数
 * @property int $UPDATE_PERIOD_NUM 修改期数
 * @property string $CREATE_ADMIN 创建人
 * @property string $UPDATE_ADMIN 修改人
 * @property string $CREATE_REMARK 备注
 * @property string $UPDATE_REMARK 备注
 * @property int $IS_DEL 是否删除
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 */
class UserSystem extends \common\components\ActiveRecord {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%USER_SYSTEM}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['SYSTEM_NAME', 'LEADER_UID', 'PERIOD_NUM', 'CREATE_ADMIN', 'CREATED_AT'], 'required'],
            [['PERIOD_NUM', 'UPDATE_PERIOD_NUM', 'IS_DEL', 'CREATED_AT', 'UPDATED_AT'], 'integer'],
            [['ID', 'SYSTEM_NAME', 'LEADER_UID', 'CREATE_ADMIN', 'UPDATE_ADMIN'], 'string', 'max' => 32],
            [['CREATE_REMARK', 'UPDATE_REMARK'], 'string', 'max' => 4000],
            [['LEADER_UID'], 'unique'],
            [['SYSTEM_NAME'], 'unique'],
            [['ID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'ID' => 'ID',
            'SYSTEM_NAME' => '体系名称',
            'LEADER_UID' => '领导人ID',
            'PERIOD_NUM' => '加入时的期数',
            'UPDATE_PERIOD_NUM' => '修改期数',
            'CREATE_ADMIN' => '创建人',
            'UPDATE_ADMIN' => '修改人',
            'CREATE_REMARK' => '备注',
            'UPDATE_REMARK' => '备注',
            'IS_DEL' => '是否删除',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
        ];
    }

    /**
     * 获取一个体系
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getSystem($id) {
        return static::findUseSlaves()->where('ID=:ID', [':ID' => $id])->asArray()->one();
    }

    /**
     * 通过会员ID查找体系
     * @param $userId
     * @return array|null
     */
    public static function getSystemByUserId($userId) {
        $userInfo = UserInfo::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $userId]);
        return static::findOneAsArray('ID=:ID', [':ID' => $userInfo['SYSTEM_ID']]);
    }

    /**
     * 体系下的所有会员
     * @param $id
     * @return array|null
     */
    public static function getAllChildren($id) {
        return UserInfo::findAllAsArray('SYSTEM_ID=:SYSTEM_ID', [':SYSTEM_ID' => $id]);
    }

    /**
     * 通过一个体系查找到上级体系领导人
     * @param $id
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getParentSystemFromSystem($id) {
        $oneSystem = static::find()->select('LEADER_UID')->where('ID=:ID', [':ID' => $id])->asArray()->one();
        return $oneSystem ? self::getPatentSystemLeader($oneSystem['LEADER_UID']) : null;
    }


    /**
     * 通过一个体系的领导会员获取上级体系
     * @param $userId
     * @return array|null
     */
    public static function getParentSystem($userId){
        // 联表查询安置网络的上级UID，并且是领导的会员
        $isSystemLeaderUser = UserRelation::find()->select('UN.*,PUI.NETWORK_DEEP,PUI.IS_SYSTEM_LEADER,PUI.SYSTEM_ID')->where('UN.USER_ID=:USER_ID AND PUI.IS_SYSTEM_LEADER=1', [':USER_ID'=>$userId])->from(UserRelation::tableName().' AS UN')->join('LEFT JOIN', UserInfo::tableName().' AS PUI', 'UN.PARENT_UID=PUI.USER_ID')->orderBy('PUI.NETWORK_DEEP DESC')->limit(1)->asArray()->one();
        // 拿到体系的ID以后，再查询体系
        return UserSystem::findOneAsArray('ID=:ID', [':ID'=>$isSystemLeaderUser['SYSTEM_ID']]);
    }

    /**
     * 通过一个体系的领导会员获取上级体系领导UID
     * @param $userId
     * @return mixed|null
     */
    public static function getPatentSystemLeader($userId) {
        $system = self::getParentSystem($userId);
        return $system ? $system['LEADER_UID'] : null;
    }

    /**
     * 全部体系
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getSystemData(){
        return self::find()->select('ID,SYSTEM_NAME,LEADER_UID')->where('IS_DEL=0')->indexBy('ID')->orderBy('CREATED_AT ASC')->asArray()->all();
    }

    /**
     * 获取全部体系
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllSystems(){
        return self::find()->select('ID,SYSTEM_NAME')->where('IS_DEL=0')->indexBy('ID')->orderBy('CREATED_AT ASC')->asArray()->all();
    }

    /**
     * 操作日志记录条件
     * @return array
     */
    public function attrLabelsWithLogType(){
        return [
            'SYSTEM_NAME' => '体系名称',
            'LEADER_UID' => '领导人ID',
            'CREATE_ADMIN' => [
                'label' => '创建人',
                'type' => function($data){
                    $value = $data['value'];
                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
                    return $result['ADMIN_NAME'];
                },
            ],
            'UPDATE_ADMIN' => [
                'label' => '修改人',
                'type' => function($data){
                    $value = $data['value'];
                    $result = Admin::findOneAsArray('ID=:ID', [':ID'=>$value], 'ADMIN_NAME');
                    return $result['ADMIN_NAME'];
                },
            ],
            'CREATE_REMARK' => '备注',
            'IS_DEL' => [
                'label' => '是否撤销',
                'type' => ValueTypeConfig::YES_NO_TYPE,
            ],
            'CREATED_AT' => [
                'label' => '创建时间',
                'type' => ValueTypeConfig::DATE_TIME_TYPE,
            ],
            'UPDATED_AT' => [
                'label' => '修改时间',
                'type' => ValueTypeConfig::DATE_TIME_TYPE,
            ],
        ];
    }
}
