<?php

namespace goods\controllers;

use goods\logic\goods\GoodsManager;
use backend\models\ars\File;
use Yii;
use goods\models\ars\ShopCategory;
use goods\models\searchs\ShopCategorySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

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

    public function actions()
    {
        return [
            'upload' => [
                'class' => 'iron\actions\UploadAction',
                'path' => 'xls/',
                'maxSize' => 20480,
            ]
        ];
    }

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

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

    /**
     * Displays a single ShopCategory 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 ShopCategory model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ShopCategory();
        $model->is_show = ShopCategory::IS_SHOW_HIDE;
        $model->sort_order = 0;

        if ($model->load(Yii::$app->request->post())) {
            if ($model->filter_attr != null && is_array($model->filter_attr)) {
                $model->filter_attr = implode(',', $model->filter_attr);
            } else {
                $model->filter_attr = '';
            }

            //类目图片上传保存处理
            $icon_image_id_str = $model->iconImageId;
            $model->save();
            $save_icon_image_res = GoodsManager::saveFile(explode(',', $icon_image_id_str), $model, [], File::OWN_TYPE_CATEGORY_ICON);
            if($save_icon_image_res['status']){
                $model->icon = $save_icon_image_res['first_file_id'];
                $model->save();
            }

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

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

    /**
     * Updates an existing ShopCategory 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->filter_attr != null) {
            $model->filter_attr = explode(',', $model->filter_attr);
        }
        $model->iconImageId = $model->icon;
        $icon_image_old_id_arr = $model->icon;//记录已保存的类目图片id,用于修改

        if ($model->load(Yii::$app->request->post())) {
            if ($model->filter_attr != null && is_array($model->filter_attr)) {
                $model->filter_attr = implode(',', $model->filter_attr);
            } else {
                $model->filter_attr = '';
            }

            //类目图片上传保存处理
            $icon_image_id_str = $model->iconImageId;
            $model->save();
            $save_icon_image_res = GoodsManager::saveFile(explode(',', $icon_image_id_str), $model, explode(',', $icon_image_old_id_arr), File::OWN_TYPE_CATEGORY_ICON);
            if($save_icon_image_res['status'] && $save_icon_image_res['first_file_id'] !== 0){
                $model->icon = $save_icon_image_res['first_file_id'];
                $model->save();
            }

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

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

    /**
     * Deletes an existing ShopCategory 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)
    {
        $model = $this->findModel($id);
        $model->is_delete = ShopCategory::IS_DELETE_YES;
        $model->save();

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

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

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    /**
    * @author iron
    * 文件导出
    */
    public function actionExport()
    {
        $searchModel = new ShopCategorySearch();
        $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' =>'Shop Categories'. "-" .date('Y-m-d H/i/s', time()),
            'columns' => $searchModel->columns()
        ]);
    }

    /**
     * 处理文件上传成功后回调保存到临时文件表中,并返回临时文件id
     */
    public function actionSaveFile()
    {
        if(!class_exists('\backend\models\ars\TemFile') || !class_exists('\backend\logic\file\FileManager')){
            return '';
        }

        $data = Yii::$app->request->get('data');
        $file_name = Yii::$app->request->get('fileName')[0];

        if ($data['status'] == true) {
            $model = new \backend\models\ars\TemFile();
            $model->user_id = Yii::$app->user->identity->id;
            $model->name = $file_name;
            $file_manager = new \backend\logic\file\FileManager();
            $type_res = $file_manager->searchType(\backend\logic\file\FileManager::$extension, pathinfo($data['path'])['extension']);
            if ($type_res['status']) {
                $model->type = $type_res['type'];
            }
            $model->alias = $data['alias'];
            $model->path = $data['path'];
            $model->save();
            return $model->id;
        }
    }

    /**
     * @return string
     * 点击删除按钮时同时删除字符串中的id
     */
    public function actionImgIdDel()
    {
        //判断该类是否存在
        if(!class_exists('\backend\models\ars\TemFile') || !class_exists('\backend\models\ars\File')){
            return '';
        }

        $img_id = Yii::$app->request->get('imgid');
        $img_id_arr = explode(',', $img_id);
        if(isset(Yii::$app->request->get('data')['alias'])) {
            $alias = Yii::$app->request->get('data')['alias'];
            $tem_file = \backend\models\ars\TemFile::findOne(['alias' => $alias]);
            if ($tem_file) {
                $img_id_arr = array_diff($img_id_arr, [$tem_file->id]);
            }
        }else{
            foreach (Yii::$app->request->get() as $key => $value) {
                $tem_file = \backend\models\ars\File::findOne(['alias' => $value]);
                if ($tem_file) {
                    $img_id_arr = array_diff($img_id_arr, [$tem_file->id]);
                }
            }
        }
        $img_id_str = implode(',', $img_id_arr);
        return $img_id_str;
    }

    /**
     * @return bool|false|string
     * 加载已有的文件
     */
    public function actionImageFile()
    {
        //判断该类是否存在
        if(!class_exists('\backend\models\ars\File')){
            return false;
        }

        $file_id_str = Yii::$app->request->get('fileidstr');
        $file_id_arr = explode(',', $file_id_str);
        $data = \backend\models\ars\File::find()->where(['id' => $file_id_arr])->all();
        $res = array();
        if($data) {
            $i = 0;
            foreach ($data as $key => $value) {
                $res[$i]['name'] = $value->alias;
                $res[$i]['path'] = Yii::$app->request->hostInfo . '/' . $value->path;
                $res[$i]['size'] = filesize($value->path);
                $i++;
            }
        }
        return json_encode($res);
    }
}