<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\AreaT;
use common\models\UserT;
use Yii;
use yii\web\Response;

class AreaController extends \yii\web\Controller
{
    public $enableCsrfValidation = false;
    public $my = null;

    public function init()
    {
        parent::init();

        $cookie = Yii::$app->request->cookies;
        $user_id = MyLib::encrypt($cookie->get('aid'),'DECODE');

        if($user_id != 0)
        {
            $this->my = UserT::findOne(['id'=>$user_id]);
        } else {
            Yii::$app->response->redirect('/common/login')->send();
            exit;
        }
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionAjaxList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $items = AreaT::find()->all();

        $data = array();
        foreach($items as $item) {
            $row = array();
            $row[] = $item->id;
            $row[] = $item->name;
            $data[] = $row;
        }
        $result = array();
        $result['data'] = $data;
        return $result;
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        if($id > 0) {
            $info = AreaT::findOne(['id'=>$id]);
        } else {
            $info = new AreaT();
        }

        return $this->renderPartial('edit',[
            'info' => $info
        ]);
    }

    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $name = $request->post('name');

            if($name == '') {
                $result['msg'] = '请输入区域名称!';
                return $result;
            }

            $row = null;
            if($id > 0) {
                $row = AreaT::findOne(['id'=>$id]);
            } else {
                $row = new AreaT();
            }
            $row->name = $name;
            $row->save();

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            if($id > 0) {
                $row = AreaT::findOne(['id'=>$id]);
                $row->delete();

                $result['success'] = true;
                $result['msg'] = '删除成功';
            }
        }
        return $result;
    }
}
