<?php
namespace backendApi\modules\v1\models\lists\user;

use common\helpers\Cache;
use common\helpers\http\BackendToFrontendApi;
use common\helpers\LoggerTool;
use common\libs\dataList\DataListInterface;
use common\models\Countries;
use common\models\DecRole;
use common\models\EliteLevel;
use common\models\EmployLevel;
use common\models\Language;
use common\models\OpenBank;
use common\models\User;
use common\models\UserInfo;
use common\libs\dataList\column\DateTime;
use common\libs\dataList\column\YesNo;
use Yii;

class IndexList extends \common\libs\dataList\DataList implements DataListInterface
{
    /**
     * 列表名称
     * @return string
     */
    public function getListName(){
        return '会员列表';
    }

    /**
     * 列表筛选到的数据
     */
    public function dataHandle()
    {
        $this->condition .= '';
        $this->listData = User::lists($this->condition, $this->params, [
            'select' => 'U.*,
                UI.USER_ID, UI.ZC_PV, UI.CON_UID, UI.REC_UID_ACTUAL, UI.REC_UID, UI.CON_NUM, UI.REC_NUM, UI.NETWORK_DEEP, 
                UI.RELATION_DEEP, UI.SYSTEM_ID, UI.IS_GROUP_LEADER, UI.IS_SYSTEM_LEADER, UI.IS_TEAM, UI.IS_BIND, 
                UI.IS_TEAM_MAIN, UI.IS_BIND_MAIN, UI.IS_AUTO_WITHDRAW, UI.CLOSE_LOGIN, UI.REG_TYPE, UI.SHOULD_REG_TYPE, 
                UI.REG_NAME, UI.CREDIT_CODE, UI.PREMISES, UI.LEGAL_PERSON, UI.REG_EXPIRES, UI.STORE_TYPE, UI.INVOICE_BALANCE, 
                UI.HIGHEST_EMP_LV, UI.CLOSE_LOGIN_AT, UI.PULLED_AT, 
                UI.GROUP_LEADER_AT, UI.ALLOW_TRANSFER, UI.ALLOW_RECONSUME_SMS, UI.ALLOW_RECONSUME_SMS_TO, 
                UI.HIGHEST_EMP_LV_PERIOD, UI.TRANSFER_PROP, UI.LOGIN_NUMS, UI.FAIL_NUMS, UI.LAST_LOGIN_IP, 
                UI.LAST_LOGIN_AT, UI.SHOW_EMP_LV,
                CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME,
                RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,
                DU.USER_NAME DEC_USER_NAME,
                CS.NAME COUNTRY,
                LG.NAME LANGUAGE
                ',
            'orderBy' => 'UI.CREATED_AT DESC, UI.ID DESC',
            'from' => User::tableName() . ' AS U',
            'join' => [
                ['LEFT JOIN', UserInfo::tableName() . ' AS UI', 'UI.USER_ID=U.ID'],
                ['LEFT JOIN', User::tableName() . ' AS CU', 'UI.CON_UID=CU.ID'],
                ['LEFT JOIN', User::tableName() . ' AS RU', 'UI.REC_UID=RU.ID'],
                ['LEFT JOIN', User::tableName() . ' AS DU', 'U.DEC_ID=DU.ID'],
                ['LEFT JOIN', Countries::tableName() . ' AS CS', 'U.COUNTRY_ID=CS.ID'],
                ['LEFT JOIN', Language::tableName() . ' AS LG', 'U.LANGUAGE_ID=LG.ID'],
            ],
            'page' => $this->page,
            'pageSize' => $this->pageSize,
        ]);
        foreach ($this->listData['list'] as $key => $value) {
            // 后台访问前台的请求参数
            if (!$this->isExport && Yii::$app->user->validateAdminAction('user', 'login-to-frontend')) {
                $urlParams = BackendToFrontendApi::paramsFormat(['id' => $value['USER_ID']]);
                $urlParamStr = '';
                foreach ($urlParams as $pKey => $pValue) {
                    $urlParamStr .= $pKey . '=' . $pValue . '&';
                }
                $urlParamStr = substr($urlParamStr, 0, -1);
                $this->listData['list'][$key]['BTF_URL'] = $urlParamStr;
            } else {
                $this->listData['list'][$key]['BTF_URL'] = null;
            }

            $conActual = User::getBaseInfo($value['REC_UID_ACTUAL']);
            $this->listData['list'][$key]['REC_USER_NAME_ACTUAL'] = $conActual['USER_NAME'] ?? '';
            $this->listData['list'][$key]['REC_REAL_NAME_ACTUAL'] = $conActual['REAL_NAME'] ?? '';
        }
    }

    /**
     * 要展示和导出的所有字段
     * @return array
     */
    public function getColumn(){
        $decLevelConfig = Cache::getDecLevelConfig();
        $empLevelConfig = Cache::getEmpLevelConfig();
        $eliteLevelConfig = Cache::getEliteLevelConfig();
        $decRoleConfig = DecRole::getAllData();
        $openBankConfig = OpenBank::getAllOpenBank();
        $regionConfig = Cache::getRegionConfig();
        if(!$this->columns){
            $this->columns = [
                'USER_ID' => null, // 这种传输方式主要是用于索引，因为过滤后的字段可能没有这种ID，但是一些功能的操作还需要用这种ID去关联，例如前台会员列表中的勾选批量状态管理，这里需要的就是USER_ID
                'BTF_URL' => null,
                'USER_NAME' => [
                    'header' => Yii::t('ctx', 'memberCode'),
                    'headerOther' => ['width' => '150'],
                ],
                'REAL_NAME' => [
                    'header' => Yii::t('ctx', 'memberName'),
                    'headerOther' => [
                        'width' => '120',
                    ],
                    'valueOther' => [
                        'tag'=>['type'=>'success', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'LOGIN_STATUS_NAME' => [
                    'header' => Yii::t('ctx', 'loginStatus'),
                    'value' => function($row) {
                        return $row['ALLOW_LOGIN'] == 1 ? Yii::t('ctx', 'allowLogin') : Yii::t('ctx', 'prohibitLogin');
                    },
                    'headerOther' => ['width' => '110'],
                ],
                'STATUS' => [
                    'header' => Yii::t('ctx', 'status'),
                    'value' => function($row) {
                        return $row['STATUS'] == 1 ? Yii::t('ctx', 'activate') : Yii::t('ctx', 'lock');
                    },
                    'headerOther' => ['width' => '110'],
                ],
                'COUNTRY' => [
                    'header' => Yii::t('ctx', 'country'),
                    'headerOther' => ['width' => '110'],
                ],
                'CREATED_AT' => [
                    'header' => Yii::t('ctx', 'joiningDate'),
                    'value' => function($row) {
                        return (new DateTime([
                            'value' => $row['CREATED_AT'],
                        ]))->result();
                    },
                    'headerOther' => ['width' => '170'],
                ],
                'PERIOD_AT' => [
                    'header' => Yii::t('ctx', 'joiningPeriod'),
                    'headerOther' => ['width' => '180'],
                ],
                'DEC_LV_NAME' => [
                    'header' => Yii::t('ctx', 'currentMemberLevel'),
                    'headerOther' => ['width' => '160'],
                    'value' => function($row) use($decLevelConfig) {
                        return $decLevelConfig[$row['DEC_LV']]['LEVEL_NAME'];
                    },
                    'valueOther' => [
                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'DEC_LV_UPDATED_AT' => [
                    'header' => Yii::t('ctx', 'currentAdjustmentDate'),
                    'value' => function($row) {
                        return (new DateTime([
                            'value' => $row['DEC_LV_UPDATED_AT'],
                        ]))->result();
                    },
                    'headerOther' => ['width' => '180'],
                ],
                'LAST_DEC_LV_NAME' => [
                    'header' => Yii::t('ctx', 'PCMemberLevel'),
                    'headerOther' => [
                        'width' => '140',
                    ],
                    'value' => function($row) use($decLevelConfig) {
                        if (!$row['LAST_DEC_LV']) {
                            return $decLevelConfig[$row['DEC_LV']]['LEVEL_NAME'];
                        } else {
                            return $decLevelConfig[$row['LAST_DEC_LV']]['LEVEL_NAME'];
                        }
                    },
                    'valueOther' => [
                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'EMP_LV_NAME' => [
                    'header' => Yii::t('ctx', 'highestDirector'),
                    'headerOther' => [
                        'width' => '190',
                    ],
                    'value' => function($row) use($empLevelConfig) {
                        return isset($empLevelConfig[$row['EMP_LV']]) ? $empLevelConfig[$row['EMP_LV']]['LEVEL_NAME'] : $empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'];
                    },
                    'valueOther' => [
                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'LAST_EMP_LV_NAME' => [
                    'header' => Yii::t('ctx', 'latestDirector'),
                    'headerOther' => [
                        'width' => '190',
                    ],
                    'value' => function($row) use($empLevelConfig) {
                        return isset($empLevelConfig[$row['LAST_EMP_LV']]) ? $empLevelConfig[$row['LAST_EMP_LV']]['LEVEL_NAME'] : $empLevelConfig[EmployLevel::getDefaultLevelId()]['LEVEL_NAME'];
                    },
                    'valueOther' => [
                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'ELITE_LV_NAME' => [
                    'header' => Yii::t('ctx', 'highestElite'),
                    'headerOther' => [
                        'width' => '190',
                    ],
                    'value' => function($row) use($eliteLevelConfig) {
                        return $eliteLevelConfig[$row['ELITE_LV']]['LEVEL_NAME'] ?? $eliteLevelConfig[EliteLevel::getDefaultLevelId()]['LEVEL_NAME'];
                    },
                    'valueOther' => [
                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'LAST_ELite_LV_NAME' => [
                    'header' => Yii::t('ctx', 'latestElite'),
                    'headerOther' => [
                        'width' => '190',
                    ],
                    'value' => function($row) use($eliteLevelConfig) {
                        return $eliteLevelConfig[$row['LAST_ELITE_LV']]['LEVEL_NAME'] ?? $eliteLevelConfig[EliteLevel::getDefaultLevelId()]['LEVEL_NAME'];
                    },
                    'valueOther' => [
                        'tag'=>['type'=>'warning', 'size' => 'small', 'class'=>'no-border']
                    ],
                ],
                'REC_USER_NAME' => [
                    'header' => Yii::t('ctx', 'recommendationNo'),
                    'headerOther' => ['width' => '180'],
                ],
                'REC_REAL_NAME' => [
                    'header' => Yii::t('ctx', 'recommendedName'),
                    'headerOther' => ['width' => '190'],
                ],
                'REC_USER_NAME_ACTUAL' => [
                    'header' => Yii::t('ctx', 'placementNo'),
                    'headerOther' => ['width' => '140'],
                ],
                'REC_REAL_NAME_ACTUAL' => [
                    'header' => Yii::t('ctx', 'placementName'),
                    'headerOther' => ['width' => '140'],
                ],
                'MOBILE' => [
                    'header' => Yii::t('ctx', 'phoneNumber'),
                    'value' => function($row) {
                        return "\t".$row['MOBILE'];
                    },
                    'headerOther' => ['width' => '120'],
                ],
                'DEC_USER_NAME' => [
                    'header' => Yii::t('ctx', 'stockistCode'),
                    'headerOther' => ['width' => '150'],
                ],
                'IS_DEC' => [
                    'header' => Yii::t('ctx', 'whetherStockist'),
                    'value' => function($row) {
                        return (new YesNo([
                            'value' => $row['IS_DEC'],
                        ]))->result();
                    },
                    'headerOther' => function($row) {
                        return ['width' => '200'];
                    },
                    'valueOther' => function($row) {
                        return [
                            'tag'=>['type'=>(isset($row['IS_DEC']) && $row['IS_DEC'] )? 'success' : 'info', 'size' => 'small']
                        ];
                    },
                ],
                'IS_ATLAS' => [
                    'header' => Yii::t('ctx', 'whetherChartDisplay'),
                    'value' => function($row) {
                        return (new YesNo([
                            'value' => $row['IS_ATLAS'],
                        ]))->result();
                    },
                    'headerOther' => function($row) {
                        return [
                            'width' => '200',
                        ];
                    },
                    'valueOther' => function($row) {
                        return [
                            'tag'=>['type'=>(isset($row['IS_ATLAS']) && $row['IS_ATLAS'] )? 'success' : 'info', 'size' => 'small']
                        ];
                    },
                ],
                'IS_RECHARGE' => [
                    'header' => Yii::t('ctx', 'whetherRechargeDisplay'),
                    'value' => function($row) {
                        return (new YesNo([
                            'value' => $row['IS_RECHARGE'],
                        ]))->result();
                    },
                    'headerOther' => function($row) {
                        return [
                            'width' => '200',
                        ];
                    },
                    'valueOther' => function($row) {
                        return [
                            'tag'=>['type'=>(isset($row['IS_RECHARGE']) && $row['IS_RECHARGE'] )? 'success' : 'info', 'size' => 'small']
                        ];
                    },
                ],
                'DEC_ROLE_NAME' => [
                    'header' => Yii::t('ctx', 'stockistLevel'),
                    'headerOther' => ['width' => '110'],
                    'value' => function($row) use($decRoleConfig) {
                        return $decRoleConfig[$row['DEC_ROLE_ID']]['ROLE_NAME'] ?? '';
                    },
                ],
                'OPEN_BANK_NAME' => [
                    'header' => Yii::t('ctx', 'bankName'),
                    'headerOther' => ['width' => '110'],
                    'value' => function($row) use($openBankConfig) {
                        return $openBankConfig[$row['OPEN_BANK']]['BANK_NAME'] ?? '';
                    },
                ],
                'BANK_NO' => [
                    'header' => Yii::t('ctx', 'bankAccountNumber'),
                    'headerOther' => ['width' => '220'],
                    'value' => function($row) {
                        return "\t".$row['BANK_NO'];
                    },
                ],
                'AREA' => [
                    'header' => Yii::t('ctx', 'commonAddress'),
                    'value' => function($row) use($regionConfig) {
                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
                        return $province.$city.$county;
                    },
                    'showValue' => function($row) {
                        $province = $regionConfig[$row['PROVINCE']]['REGION_NAME'] ?? '';
                        $city = $regionConfig[$row['CITY']]['REGION_NAME'] ?? '';
                        $county = $regionConfig[$row['COUNTY']]['REGION_NAME'] ?? '';
                        return '<div class="addr" title='.$province.$city.$county.'>'.$province.$city.$county.'</div>';
                    },
                    'headerOther' => [
                        'width' => '200'
                    ],
                ],
                'ALLOW_TRANSFER' => [
                    'header' => Yii::t('ctx', 'enableTransfer'),
                    'value' => function($row) {
                        return $row['ALLOW_TRANSFER'] == 1 ? Yii::t('ctx', 'on') : Yii::t('ctx', 'off');
                    },
                    'headerOther' => function($row) {
                        return [
                            'width' => '130',
                        ];
                    },
                    'valueOther' => function($row) {
                        return [
                            'tag'=>['type'=>(isset($row['ALLOW_TRANSFER']) && $row['ALLOW_TRANSFER']) ? 'Success' : 'Info', 'size' => 'small']
                        ];
                    },
                ],
            ];
        }
        return $this->columns;
    }

    /**
     * 前台用于筛选的类型集合
     * @return mixed
     */
    public function getFilterTypes()
    {
        if(!$this->filterTypes){
            $this->filterTypes = [
                'USER_NAME'=> ['name'=> Yii::t('ctx', 'memberCode')],
                'REAL_NAME'=> ['name'=> Yii::t('ctx', 'memberName')],
                'CREATED_AT'=> ['name'=> Yii::t('ctx', 'joiningDate'), 'other'=> 'date'],
                'PERIOD_AT'=> ['name'=> Yii::t('ctx', 'joiningPeriod')],
                'DEC_LV_NAME'=> ['name'=> Yii::t('ctx', 'currentMemberLevel'), 'other'=> 'decLevel'],
                'EMP_LV_NAME'=> ['name'=> Yii::t('ctx', 'highestDirector'), 'other'=> 'empLevel'],
                'LAST_EMP_LV_NAME'=> ['name'=> Yii::t('ctx', 'latestDirector'), 'other'=> 'empLevel'],
                'ELITE_LV_NAME'=> ['name'=> Yii::t('ctx', 'highestElite'), 'other'=> 'eliteLevel'],
                'LAST_ELITE_LV_NAME'=> ['name'=> Yii::t('ctx', 'latestElite'), 'other'=> 'eliteLevel'],
                'MOBILE'=> ['name'=> Yii::t('ctx', 'phoneNumber')],
                'DEC_USER_NAME'=> ['name'=> Yii::t('ctx', 'stockistCode')],
                'IS_DEC'=> ['name'=> Yii::t('ctx', 'stockistOrNot'), 'other'=> 'yesOrNo'],
                'DEC_ROLE_NAME'=> ['name'=> Yii::t('ctx', 'stockistLevel'), 'other'=> 'decRole'],
                'COUNTRY'=> [
                    'name'=> \Yii::t('ctx', 'country'),
                    'other'=> 'select',
                    'selectData'=> self::getCountry()
                ],
                'AREA'=> ['name'=> Yii::t('ctx', 'commonAddress'), 'other'=> 'area'],
                'STATUS'=> ['name'=> Yii::t('ctx', 'activeStatus'), 'other'=> 'select', 'selectData'=> [['id'=> 0, 'name'=> Yii::t('ctx', 'locking')],['id'=> 1, 'name'=> Yii::t('ctx', 'activation')]]],
            ];
        }
        return $this->filterTypes;
    }

    public function getCountry()
    {
        $countries = Countries::getFromCache();

        $data = [];
        foreach ($countries as $country) {
            $data[] = [
                'id' => $country['ID'],
                'name' => $country['NAME'],
            ];
        }

        return $data;
    }
}