<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */

namespace frontendApi\modules\v1\controllers;

use common\helpers\Cache;
use common\helpers\Form;
use common\helpers\user\Info;
use common\models\DeclarationPackage;
use common\models\forms\DeclarationForm;
use common\models\forms\DeclarationLoopForm;
use common\models\forms\UploadForm;
use common\models\forms\UserBindForm;
use common\models\forms\UserForm;
use common\models\OpenBank;
use common\models\ShopGoods;
use common\models\User;
use common\models\UserBind;
use common\models\UserInfo;
use common\models\UserNetwork;
use yii\web\UploadedFile;

class UserController extends BaseController {
    public $modelClass = UserInfo::class;

    /**
     * 会员资料
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionIndex() {
        $allNation = \Yii::$app->params['nation'];
        $allOpenBank = OpenBank::findAllAsArray('STATUS=1');
        $data['allNation'] = $allNation;
        $data['allOpenBank'] = $allOpenBank;
        $data['userInfo'] = User::getEnCodeInfo(\Yii::$app->user->id);
        return static::notice($data);
    }

    /**
     * 编辑会员资料
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionEdit() {
        if(\Yii::$app->request->isPost){
            $form = new UserForm();
            $post = \Yii::$app->request->post();
            $form->scenario = 'modifyProfile';
            if($form->load($post, '') && $result = $form->modifyProfile()){
                return static::notice('个人资料修改成功');
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
            }
        }
        return static::notice('非法访问', 400);
    }

    /**
     * 修改登录密码
     */
    public function actionPassword(){
        if(\Yii::$app->request->isPost){
            $form = new UserForm();
            $form->scenario = 'modifyPassword';
            $post = \Yii::$app->request->post();
            if($form->load($post, '') && $result = $form->modifyPassword()){
                return static::notice('密码修改成功');
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
            }
        }
        return static::notice('非法访问', 400);
    }

    /**
     * 修改支付密码
     */
    public function actionPayPassword(){
        if(\Yii::$app->request->isPost){
            $form = new UserForm();
            $form->scenario = 'modifyPasswordPay';
            $post = \Yii::$app->request->post();
            $form->userId = \Yii::$app->user->id;
            if($form->load($post, '') && $result = $form->modifyPasswordPay()){
                return static::notice('支付密码修改成功');
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 400);
            }
        }
        return static::notice('非法访问', 400);
    }

    /**
     * 直推会员列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRecUser() {
        $allData = UserInfo::lists('AND REC_UID=:REC_UID', [':REC_UID' => \Yii::$app->user->id], ['useSlaves' => true, 'select'=>'USER_ID,CREATED_AT']);
        foreach ($allData['list'] as $key => $data) {
            $userBaseInfo = User::getEnCodeInfo($data['USER_ID']);
            $userBaseInfo['NATION'] = \Yii::$app->params['nation'][$userBaseInfo['NATION']]['name'] ?? '';
            $allData['list'][$key]['BASE_INFO'] = $userBaseInfo;
        }
        return static::notice($allData);
    }

    /**
     * 上传身份证
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionIdCard() {
        if (\Yii::$app->request->isPost) {
            $formModel = new UploadForm();
            $formModel->scenario = 'idCardFront';
            $formModel->file = UploadedFile::getInstanceByName('file');
            //$formModel->token = \Yii::$app->request->post('uploadToken');
            $formModel->token = \Yii::$app->request->request('uploadToken');;
            if ($formModel->file && $formModel->upload()) {
                return static::notice('上传成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        // 查看该用户是否已经上传过身份证
        $oneData = User::find()->select('ID_IMAGE')->where('ID=:ID', [':ID' => \Yii::$app->user->id])->asArray()->one();
        if ($oneData['ID_IMAGE']) {
            return static::notice($oneData);
        } else {
            $token = Cache::setUploadToken();
            return static::notice($token);
        }
    }

    /**
     * 点位绑定
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBind() {
        $userBind = UserBind::findOneAsArray('USER_ID=:USER_ID AND IS_DEL=0', [':USER_ID' => \Yii::$app->user->id]);
        $allData['list']=UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0', [':MAIN_UID' => $userBind['MAIN_UID']], 'ID,USER_ID,MAIN_UID,CREATED_AT,UPDATED_AT');
        foreach ($allData['list'] as $key => $value) {
            $baseInfo = Info::baseInfoZh($value['USER_ID']);
            if ($baseInfo['STATUS'] != 1) {
                unset($allData['list'][$key]);
                continue;
            }
            $allData['list'][$key]['USER_NAME'] = $baseInfo['USER_NAME'];
            $allData['list'][$key]['REAL_NAME'] = $baseInfo['REAL_NAME'];
            $allData['list'][$key]['BANK_PROVINCE_NAME'] = $baseInfo['BANK_PROVINCE_NAME'];
            $allData['list'][$key]['BANK_CITY_NAME'] = $baseInfo['BANK_CITY_NAME'];
            $allData['list'][$key]['BANK_COUNTY_NAME'] = $baseInfo['BANK_COUNTY_NAME'];
            $allData['list'][$key]['OPEN_BANK_NAME'] = $baseInfo['OPEN_BANK_NAME'];
            $allData['list'][$key]['BANK_NO'] = $baseInfo['BANK_NO'];
            $allData['list'][$key]['MAIN_USER_NAME'] =Info::getUserNameByUserId($value['MAIN_UID']);
        }
        $allData['list'] = array_values($allData['list']);
        return static::notice($allData);
    }

    /**
     * 编辑点位绑定
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBindEdit(){
        $id = \Yii::$app->request->get('id');
        if(\Yii::$app->request->isPost) {
            return parent::edit(UserBindForm::class, '修改主点位成功', 'frontEdit', ['frontEdit'], null, function($form, $result){
                //log
            });
        }
        // 获得当前会员的用户名等信息
        $userBind = UserBind::findOneAsArray('ID=:ID AND IS_DEL=0', [':ID' => $id]);
        $userBinds = UserBind::findAllAsArray('MAIN_UID=:MAIN_UID AND IS_DEL=0',[':MAIN_UID'=>$userBind['MAIN_UID']], 'ID,USER_ID,MAIN_UID,CREATED_AT,UPDATED_AT');
        foreach($userBinds as $key=>$value){
            $status = Info::getStatusByUserId($value['USER_ID']);
            if ($status != 1) {
                unset($userBinds[$key]);
                continue;
            }
            $userBinds[$key]['USER_NAME'] = Info::getUserNameByUserId($value['USER_ID']);

        }
        $userBinds = array_values($userBinds);
        return static::notice(['userBinds' => $userBinds,'mainUid'=>$userBind['MAIN_UID']]);
    }

    /**
     * 报单管理
     */
    public function actionDec() {
        if (\Yii::$app->request->isPost) {
            $formModel = new DeclarationLoopForm();
            $formModel->scenario = 'userDec';
            $post = \Yii::$app->request->post();
            $post['insertUserName'] = strtoupper($post['insertUserName']);
            $post['type'] = DeclarationForm::TYPE_ZC;
            $allData['data'][] = $post;
            if ($formModel->load($allData, '') && $formModel->add()) {
                return static::notice('报单成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
            }
        }
        //所有报单套餐
        $allDecPackage = DeclarationPackage::getAllData();
        $decLevels = Cache::getDecLevelConfig();
        foreach ($allDecPackage as $k=>$v){
            $levelName = $decLevels[$v['LEVEL_ID']]['LEVEL_NAME'] ?? '';
            $allDecPackage[$k]['LEVEL_NAME'] = $levelName;
        }
        //所有自选商品
        $allGoods = ShopGoods::find()->where('STATUS=1')->orderBy('SORT ASC')->asArray()->all();
        //$allGoods = ShopGoods::findAllAsArray('STATUS=1');
        // 所有开户行
        $allOpenBank = OpenBank::find()->where('STATUS=1')->orderBy('LIST_ORDER ASC')->asArray()->all();
        if (!$userName = Info::generateUserName('LA',9)) {
            return static::notice('会员编号生成失败', 400);
        }
        return static::notice(['allDecPackage' => $allDecPackage,'allGoods' => $allGoods,'allOpenBank' => $allOpenBank, 'userName' => $userName]);
    }

    /**
     * 报单级别套餐
     */
    public function actionDecPackage() {
        $decLv = \Yii::$app->request->get('id');
        //所有报单级别套餐
        $allDecPackage = DeclarationPackage::getPackageFromLevelId($decLv);
        return static::notice(['allDecPackage' => $allDecPackage]);

    }

    /**
     * 会员信息查询
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionFullInfo()
    {
        $userName = \Yii::$app->request->get('userName');
        $userId = Info::getUserIdByUserName($userName);
        $userInfo['REAL_NAME'] = '';
        $user = User::findOneAsArray('ID=:ID', [':ID' => $userId], 'REAL_NAME');
        if($user){
            $userInfo['REAL_NAME'] = $user['REAL_NAME'];
            $allChildUser = UserNetwork::getFirstFloorChildren($userId);
            $isLocation = [1 => '左-', 2 => '中-', 3 => '右-'];
            if($allChildUser) {
                foreach ($allChildUser as $child) {
                    $isLocation[$child['RELATIVE_LOCATION']].= '满';
                }
            }
            $userInfo['isLocation'] = '('.implode(',',$isLocation).')';
            return static::notice($userInfo);
        }else{
            return static::notice('会员编号不存在', 400);
        }
    }

}