<?php

namespace backend\modules\shop\controllers;

use  backend\modules\shop\models\ars\City;
use  backend\modules\shop\models\ars\Province;
use Yii;
use  backend\modules\shop\models\ars\ExpressTemplate;
use  backend\modules\shop\models\searchs\ExpressTemplateSearch;
use yii\caching\Cache;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * 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();
        $model->calculation_type = ExpressTemplate::CALCULATION_TYPE_NUMBER;
        $model->basic_count = 1;
        $model->basic_price = '0.00';

        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post('ExpressTemplate');
            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, '');
            $model->basic_price *= 100;
            $model->extra_price *= 100;
            if ($model->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
                $model->basic_count *= 10;
                $model->extra_count *= 10;
            } else {
                $model->basic_count *= 1;
                $model->extra_count *= 1;
            }
            $model->save();
            return $this->redirect('index');
        }
        $data = [];
        $provinces = Province::find()->cache(0)->all();
        foreach ($provinces as $k => $v) {
            $data[$k]['province'] = $v->name;
            $cities = City::find()->cache(0)
                ->where(['province_id' => $v->province_id])
                ->all();
            foreach ($cities as $city) {
                $data[$k]['city'][] = ['id' => $city->city_id, 'name' => $city->name];
            }

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

    /**
     * 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);
        $model->basic_price /= 100;
        $model->extra_price /= 100;
        if ($model->calculation_type == ExpressTemplate::CALCULATION_TYPE_WEIGHT) {
            $model->basic_count /= 10;
            $model->extra_count /= 10;
        }
        $data = Yii::$app->request->post('ExpressTemplate');
        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, '');
            $model->save();
            return $this->render('view', ['model' => ExpressTemplate::findOne($model->id)]);
        }
        $data = [];
        $provinces = Province::find()->cache(0)->all();
        foreach ($provinces as $k => $v) {
            $data[$k]['province'] = $v->name;
            $cities = City::find()->cache(0)
                ->where(['province_id' => $v->province_id])
                ->all();
            foreach ($cities as $city) {
                $data[$k]['city'][] = ['id' => $city->city_id, 'name' => $city->name];
            }
        }
        return $this->render('update', [
            'model' => $model, 'data' => $data, 'cities' => explode(',', $model->city)
        ]);
    }

    /**
     * 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)
    {
        $this->findModel($id)->delete();

        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()
        ]);
    }
}