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

namespace frontendApi\modules\v1\controllers;

use common\helpers\Date;
use common\helpers\Form;
use common\helpers\user\Info;
use common\models\DecOrder;
use common\models\forms\DeclarationForm;
use common\models\forms\OrderForm;
use common\models\Order;
use common\models\ReceiveAddress;
use common\models\Region;
use common\models\ShopGoods;
use common\models\User;
use common\models\UserBonus;
use common\models\UserWallet;

class ShopController extends BaseController {
    public $modelClass = DecOrder::class;

    /**
     * 商品列表
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionIndex() {
        $condition = ' AND STATUS=1';
        $data = ShopGoods::lists($condition, [], [
            'orderBy' => 'SORT ASC,CREATED_AT DESC',
            'from' => ShopGoods::tableName(),
        ]);
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['DISCOUNT'] = ShopGoods::GOODS_TYPE[$value['TYPE']]['discount'];
        }
        return static::notice($data);
    }

    /**
     * 获取商品详情
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionGoodsDetail(){
        $id = \Yii::$app->request->get('id');
        $data = null;
        if($id){
            $data = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=>$id]);
        }
        return static::notice($data);
    }

    /**
     * 购物车订单展示
     * @throws \yii\web\HttpException
     */
    public function actionShowCart(){
        $userId = \Yii::$app->user->id;
        $payList = ShopGoods::payTypes();
        $allAddress = ReceiveAddress::findAllAsArray('USER_ID=:USER_ID', [':USER_ID'=>$userId]);
        if($allAddress) {
            foreach ($allAddress as $key => $row) {
                $allAddress[$key]['PROVINCE_NAME'] = Region::getCnName($row['PROVINCE']);
                $allAddress[$key]['CITY_NAME'] = Region::getCnName($row['CITY']);
                $allAddress[$key]['COUNTY_NAME'] = Region::getCnName($row['COUNTY']);
            }
        }
        $userBalance = [
            'points' => 0,
            'cash' => 0
        ];
        if ($userBonusResult = UserBonus::findOneAsArray(['USER_ID' => $userId])) {
            $userBalance['points'] = $userBonusResult['RECONSUME_POINTS'];
        }
        if ($userCashResult = UserWallet::findOneAsArray(['USER_ID' => $userId])) {
            $userBalance['cash'] = $userCashResult['CASH'];
        }
        return static::notice(['payList'=>$payList,'allAddress'=>$allAddress,'userBalance'=>$userBalance]);
    }

    /**
     * 确认订单
     */
    public function actionSureOrder(){
        if (\Yii::$app->request->isPost) {
            $formModel = new OrderForm();
            $formModel->scenario = 'userOrder';
            $formModel->remark = '复销备注';
            $post = \Yii::$app->request->post();
            $post['type'] = DeclarationForm::TYPE_FX;
            if ($formModel->load($post, '') && $formModel->add()) {
                return static::notice('购物成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()),400);
            }
        }
    }

    /**
     * 订单支付成功
     * @throws \yii\web\HttpException
     */
    public function actionPaySuccess(){
        $orderSn = \Yii::$app->request->get('orderSn');
        $data = null;
        if($orderSn){
            $data = Order::findOneAsArray('SN=:SN', [':SN'=>$orderSn]);
        }
        return static::notice($data);
    }

    /**
     * 我的报单
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecOrderList() {
        $condition = ' AND USER_ID=:USER_ID AND IS_DEL=0';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $data = DecOrder::lists($condition, $params, [
            'select' => 'DO.*,U.USER_NAME USER_NAME,U.REAL_NAME REAL_NAME,RU.USER_NAME REC_USER_NAME,RU.REAL_NAME REC_REAL_NAME,CU.USER_NAME CON_USER_NAME,CU.REAL_NAME CON_REAL_NAME',
            'orderBy' => 'DO.CREATED_AT DESC',
            'from' => DecOrder::tableName() . ' AS DO',
            'join' => [
                ['LEFT JOIN', User::tableName() . ' AS U', 'DO.TO_USER_ID=U.ID'],
                ['LEFT JOIN', User::tableName() . ' AS RU', 'DO.REC_USER_ID=RU.ID'],
                ['LEFT JOIN', User::tableName() . ' AS CU', 'DO.CON_USER_ID=CU.ID'],
            ],
        ]);
        return static::notice($data);
    }

    /**
     * 我的订单
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionOrderList() {
        $condition = ' AND USER_ID=:USER_ID';
        $params[':USER_ID'] = \Yii::$app->user->id;
        $data = Order::lists($condition, $params, [
            'select' => 'SN,USER_ID,USER_NAME,ORDER_TYPE,ORDER_AMOUNT,PV,STATUS,CONSIGNEE,MOBILE,PROVINCE,CITY,COUNTY,ADDRESS,PAY_AT,CREATED_AT',
            'orderBy' => 'CREATED_AT DESC',
        ]);
        foreach ($data['list'] as $key => $value) {
            //$data['list'][$key]['PROVINCE_NAME'] = $value['PROVINCE'] ? Region::getCnName($value['PROVINCE']) : '';
           //$data['list'][$key]['CITY_NAME'] = $value['CITY'] ? Region::getCnName($value['CITY']) : '';
            //$data['list'][$key]['COUNTY_NAME'] = $value['COUNTY'] ? Region::getCnName($value['COUNTY']) : '';
            $data['list'][$key]['PAY_AT'] = Date::convert($value['PAY_AT'],'Y-m-d H:i:s');
        }
        return static::notice($data);
    }

}