<?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\snowflake\SnowFake;
use common\helpers\user\Info;
use common\models\BaReceiveAddress;
use common\models\forms\BaReceiveAddressForm;
use common\models\forms\ReceiveAddressForm;
use common\models\forms\UserConfigForm;
use common\models\ReceiveAddress;
use common\models\Region;
use common\models\User;
use common\models\UserInfo;
use Yii;
use yii\base\Exception;

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

    /**
     * 会员的相关配置
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBase(){
        /**/
        $data = UserInfo::find()->select('IS_AUTO_WITHDRAW,ALLOW_RECONSUME_SMS')->where('USER_ID=:USER_ID', [':USER_ID'=>\Yii::$app->user->id])->asArray()->one();
        foreach($data as $key=>$value){
            if($key == 'IS_AUTO_WITHDRAW'){
                $data[$key] = boolval($value);
            }
            if($key == 'ALLOW_RECONSUME_SMS'){
                $data[$key] = boolval($value);
            }
        }
        $data['smsFee'] = Cache::getSystemConfig()['smsFee']['VALUE'];
        return static::notice($data);
    }

    /**
     * 修改自动提现设置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAutoWithdraw(){
        if(\Yii::$app->request->isPost){
            $formModel = new UserConfigForm();
            $formModel->scenario = 'autoWithdraw';
            if($formModel->load(\Yii::$app->request->post(), '') && $formModel->autoWithdraw()){
                return static::notice(Yii::t('app', 'autoWithdrawHasBeenClosed'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 修改复销短信通知设置
     * @return mixed
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionAllowReconsumeSms(){
        if(\Yii::$app->request->isPost){
            $formModel = new UserConfigForm();
            $formModel->scenario = 'allowReconsumeSms';
            if($formModel->load(\Yii::$app->request->post(), '') && $formModel->allowReconsumeSms()){
                return static::notice(Yii::t('app', 'closeMessageSendSuccessfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 收货地址列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressList() {
        // 会员信息
        $user = User::getEnCodeInfo(\Yii::$app->user->id);

        $condition = ' AND USER_ID=:USER_ID AND COUNTRY_ID=:COUNTRY_ID';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $params[':COUNTRY_ID'] = $user['COUNTRY_ID'];
        $data = ReceiveAddress::lists($condition, $params, [
            'SELECT' => 'ID,CONSIGNEE,MOBILE,PROVINCE,LGA_NAME,CITY_NAME,ADDRESS,IS_DEFAULT',
            'orderBy' => 'IS_DEFAULT DESC,CREATED_AT DESC',
            'useSlaves' => true,
        ]);

        if($data['list']){
            foreach($data['list'] as $key=>$row){
                $data['list'][$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
//                $data['list'][$key]['CITY_NAME'] = Region::getCnName($row['CITY']);
//                $data['list'][$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
            }
        }
        return static::notice($data);
    }

    /**
     * 行政区划列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRegionList() {
        $countryId = \Yii::$app->request->get('countryId');
        if (!$countryId) {
            $countryId = Info::getUserCountryByUserId(\Yii::$app->user->id);
        }

        $data = Region::getByCountryId($countryId);

        return static::notice($data);
    }

    /**
     * 获取一条收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressOne() {
        $data = ReceiveAddress::findOneAsArray('USER_ID=:USER_ID AND ID=:ID', [':USER_ID'=>\Yii::$app->user->id, ':ID'=>\Yii::$app->request->get('id')]);
        return static::notice($data);
    }

    /**
     * 添加收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressAdd() {
        Region::updateToCache();
        if(\Yii::$app->request->isPost) {
            return parent::edit(ReceiveAddressForm::class, Yii::t('app', 'successfully'), 'userAdd', ['edit']);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 编辑收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressEdit() {
        if(\Yii::$app->request->isPost) {
            return parent::edit(ReceiveAddressForm::class, Yii::t('app', 'successfully'), 'userEdit', ['edit']);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 设置取消默认收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressDefault() {
        if(\Yii::$app->request->isPost) {
            return parent::edit(ReceiveAddressForm::class, Yii::t('app', 'successfully'), 'userIsDefault', ['edit']);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 删除
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressDelete() {
        if(\Yii::$app->request->isPost) {
            return parent::delete(ReceiveAddress::class, null, function(){
                // 如果没有默认地址的话，就在设置一个默认地址
                if(!ReceiveAddress::find()->where('USER_ID=:USER_ID AND IS_DEFAULT=1', [':USER_ID'=>\Yii::$app->user->id])->exists()){
                    $model = ReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID'=>\Yii::$app->user->id])->one();
                    $model->IS_DEFAULT = 1;
                    if (!$model->save()){
                        throw new Exception(Yii::t('app', 'changeDefaultAddressFailed'));
                    }
                }
            } , true);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 收货地址列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBaReceiveAddressList() {
        $condition = ' AND USER_ID=:USER_ID';
        $params[':USER_ID'] = \Yii::$app->getUser()->getId();
        $data = BaReceiveAddress::lists($condition, $params, [
            'SELECT' => 'ID,CONSIGNEE,MOBILE,PROVINCE,LGA_NAME,CITY_NAME,ADDRESS,IS_DEFAULT',
            'orderBy' => 'IS_DEFAULT DESC,CREATED_AT DESC',
            'useSlaves' => true,
        ]);
        if($data['list']){
            foreach($data['list'] as $key=>$row){
                $data['list'][$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
            }
        }
        return static::notice($data);
    }

    /**
     * 获取一条收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBaReceiveAddressOne() {
        $data = BaReceiveAddress::findOneAsArray(
            'USER_ID=:USER_ID AND ID=:ID',
            [':USER_ID'=>\Yii::$app->getUser()->getId(), ':ID' => \Yii::$app->request->get('id')]
        );
        return static::notice($data);
    }

    /**
     * 添加收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBaReceiveAddressAdd() {
        Region::updateToCache();
        if (\Yii::$app->request->isPost) {
            return parent::edit(BaReceiveAddressForm::class, Yii::t('app', 'successfully'), 'userAdd', ['edit']);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 编辑收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBaReceiveAddressEdit() {
        if(\Yii::$app->request->isPost) {
            return parent::edit(BaReceiveAddressForm::class, Yii::t('app', 'successfully'), 'userEdit', ['edit']);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 设置取消默认收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionBaReceiveAddressDefault() {
        if(\Yii::$app->request->isPost) {
            return parent::edit(BaReceiveAddressForm::class, Yii::t('app', Yii::t('app', 'successfully')), 'userIsDefault', ['edit']);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }

    /**
     * 删除
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBaReceiveAddressDelete() {
        if(\Yii::$app->request->isPost) {
            return parent::delete(BaReceiveAddress::class, null, function() {
                // 如果没有默认地址的话，就在设置一个默认地址
                if (!BaReceiveAddress::find()->where('USER_ID=:USER_ID AND IS_DEFAULT=1', [':USER_ID' => \Yii::$app->getUser()->getId()])->exists()) {
                    $addressNumber = BaReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->getUser()->getId()])->count();
                    if ($addressNumber >= 1) {
                        $model = BaReceiveAddress::find()->where('USER_ID=:USER_ID', [':USER_ID' => \Yii::$app->getUser()->getId()])->one();
                        $model->IS_DEFAULT = 1;
                        if (!$model->save()) {
                            throw new Exception(Yii::t('app', 'changeDefaultAddressFailed'));
                        }
                    }
                }
            } , true);
        }
        return static::notice(Yii::t('app', 'illegalRequest'), 400);
    }
}