<?php

namespace backend\modules\shop\controllers;

use backend\modules\shop\logic\ShopManager;
use backend\modules\shop\models\searchs\ExpressAreaSearch;
use Yii;
use backend\modules\shop\models\ars\ExpressTemplate;
use backend\modules\shop\models\searchs\ExpressTemplateSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use backend\modules\shop\models\ars\ExpressArea;
use backend\modules\goods\models\ars\Goods;
use backend\modules\shop\logic\CommonManager;


/**
 * ExpressTemplateController implements the CRUD actions for ExpressTemplate model.
 */
class ExpressTemplateController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ExpressTemplate models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ExpressTemplateSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'columns' => $searchModel->columns()
    ]);
    }

    /**
     * Displays a single ExpressTemplate model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ExpressTemplate model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ExpressTemplate();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect('index');
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing ExpressTemplate model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect('index');
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing ExpressTemplate model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        if (Goods::find()->where(['express_template' => $id])->count() == 0) {
            $expressTemplateModel = $this->findModel($id);
            ExpressArea::deleteAll(['express_template' => $expressTemplateModel->id]);
            $expressTemplateModel->delete();
        } else {
            Yii::$app->session->setFlash('error', '该模板已被使用');
        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the ExpressTemplate model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ExpressTemplate the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ExpressTemplate::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    /**
    * @author iron
    * 文件导出
    */
    public function actionExport()
    {
        $searchModel = new ExpressTemplateSearch();
        $params = Yii::$app->request->queryParams;
        if ($params['page-type'] == 'all') {
             $dataProvider = $searchModel->allData($params);
        } else {
            $dataProvider = $searchModel->search($params);
        }
    \iron\widget\Excel::export([
            'models' => $dataProvider->getModels(),
            'format' => 'Xlsx',
            'asAttachment' => true,
            'fileName' =>'Express Templates'. "-" .date('Y-m-d H/i/s', time()),
            'columns' => $searchModel->columns()
        ]);
    }

    /**
     * @return string
     * 运费区域列表
     */
    public function actionExpressAreaList($id)
    {
        $expressTemplate = ExpressTemplate::findOne($id);
        $searchModel = new ExpressAreaSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $id);

        return $this->render('express_area_list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'columns' => $searchModel->columns(),
            'expressTemplate' => $expressTemplate
        ]);
    }

    /**
     * @return array|mixed|string|Response
     * 运费区域模板区域创建方法
     */
    public function actionExpressAreaCreate()
    {
        $expressTemplateId = Yii::$app->request->get('expressTemplateId');
        $expressTemplateModel = ExpressTemplate::findOne($expressTemplateId);
        $model = new ExpressArea();
        $model->basic_count = 1;
        $model->basic_price = '0.00';
        $model->express_template = $expressTemplateModel->id;

        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post('ExpressArea');
            if (Yii::$app->request->isAjax) {
                $model->load($data, '');
                Yii::$app->response->format = Response::FORMAT_JSON;
                $data = ActiveForm::validate($model);
                $data['status'] = 2;
                return $data;
            }
            if (Yii::$app->request->post('area') == null) {
                return $this->redirect(Yii::$app->request->referrer . '?status=1');
            }
            $cityIds = array_keys(Yii::$app->request->post('area'));
            $data['city'] = implode(',', $cityIds);
            $model->load($data, '');
            ShopManager::expressAreaScaleDate($model, $expressTemplateModel);   //按比例转换数据
            $model->save();
            return $this->redirect('express-area-list?id='.$model->express_template);
        }

        $data = ShopManager::filterCity($model);    //获取筛选的城市数据

        if (empty($data)) {
            Yii::$app->session->setFlash('error', '已无地区选择');
            return $this->redirect('express-area-list?id='.$expressTemplateModel->id);
        }
        return $this->render('express_area_create', [
            'model' => $model,
            'data' => $data,
            'expressTemplateModel' => $expressTemplateModel
        ]);
    }

    /**
     * @return array|mixed|string|Response
     * 运费区域模板区域更新方法
     */
    public function actionExpressAreaUpdate($id)
    {
        $model = ExpressArea::findOne($id);

        //数据按比例转换
        $expressTemplateModel = ExpressTemplate::findOne($model->express_template);
        $model->basic_price /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
        $model->extra_price /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_MONEY);
        if ($expressTemplateModel->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
            $model->basic_count /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_WEIGHT);
            $model->extra_count /= ShopManager::proportionalConversion(ShopManager::UNIT_TYPE_WEIGHT);
        }

        $data = Yii::$app->request->post('ExpressArea');
        if ($data) {
            if (Yii::$app->request->post('area') == null) {
                return $this->redirect(Yii::$app->request->referrer . '&status=1');
            }
            $cityIds = array_keys(Yii::$app->request->post('area'));
            $data['city'] = implode(',', $cityIds);
            $model->load($data, '');
            ShopManager::expressAreaScaleDate($model, $expressTemplateModel);   //按比例转换数据
            $model->save();
            return $this->redirect('express-area-list?id='.$model->express_template);
        }

        $data = ShopManager::filterCity($model);    //获取筛选的城市数据

        return $this->render('express_area_update', [
            'model' => $model, 'data' => $data, 'cities' => explode(',', $model->city), 'expressTemplateModel' => $expressTemplateModel
        ]);
    }

    /**
     * @param $id
     * @return string
     * 运费区域模板区域查看方法
     */
    public function actionExpressAreaView($id)
    {
        $expressAreaModel = ExpressArea::findOne($id);
        $expressTemplateModel = ExpressTemplate::findOne($expressAreaModel->express_template);
        return $this->render('express_area_view', [
            'model' => $expressAreaModel,
            'expressTemplateModel' => $expressTemplateModel
        ]);
    }

    public function actionExpressAreaDelete($id)
    {
        $expressAreaModel = ExpressArea::findOne($id);
        $expressTemplateId = $expressAreaModel->express_template;
        $expressAreaModel->delete();
        return $this->redirect('express-area-list?id='.$expressTemplateId);
    }
}