<?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\models\forms\ReceiveAddressForm;
use common\models\forms\UserConfigForm;
use common\models\ReceiveAddress;
use common\models\Region;
use common\models\UserInfo;
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('开启关闭自动提现成功');
            } 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('开启关闭复销短信提醒成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
    }

    /**
     * 收货地址列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressList() {
        $condition = ' AND USER_ID=:USER_ID';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $data = ReceiveAddress::lists($condition, $params, [
            'SELECT' => 'ID,CONSIGNEE,MOBILE,PROVINCE,CITY,COUNTY,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 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() {
        if(\Yii::$app->request->isPost) {
            return parent::edit(ReceiveAddressForm::class, '添加收货地址成功', 'userAdd', ['edit']);
        }
        return static::notice('非法访问', 400);
    }

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

    /**
     * 设置取消默认收货地址
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionReceiveAddressDefault() {
        if(\Yii::$app->request->isPost) {
            return parent::edit(ReceiveAddressForm::class, '添加收货地址成功', 'userIsDefault', ['edit']);
        }
        return static::notice('非法访问', 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('更新默认地址失败');
                    }
                }
            } , true);
        }
        return static::notice('非法访问', 400);
    }

}