<?php
namespace frontend\controllers;

use common\libs\MyLib;
use common\models\UserT;
use common\models\BusinessGroupT;
use yii;
use yii\web\Response;
use yii\web\Request;

class BusinessGroupController extends \yii\web\Controller
{
    public $my = null;
    public $result = [
        'success' => false,
        'msg' => '操作失败',
    ];

    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()
    {
        $request = Yii::$app->request;

        $name = $request->get('name');

        $query = BusinessGroupT::find();

        if($name != '')
            $query = $query->andWhere(['like', 'name', $name]);

        $query = $query->orderBy('created_at DESC');
        $info = $query->all();

        return $this->render('index', [
            'name' => $name,
            'info' => $info,
        ]);
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;

        $id = $request->get('id', 0);
        if($id > 0){
            $info = BusinessGroupT::findOne(['id' => $id]);
        }else{
            $info = new BusinessGroupT;
        }

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

    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;

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

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

            $row = null;

            if($id > 0){
                $row = BusinessGroupT::findOne(['id' => $id]);
            }else{
                $row = new BusinessGroupT;
            }

            $row->name = $name;

            if(!$row->save()){
                return $this->result;
            }

            $this->result = [
                'success' => true,
                'msg' => '操作成功',
            ];
        }

        return $this->result;
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;

        if($request->isPost){
            $row = null;

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

            if($id > 0)
                $row = BusinessGroupT::findOne(['id' => $id]);

            if(!$row->delete())
                return $this->result;

            $this->result = [
                'success' => true,
                'msg' => '操作成功',
            ];
        }

        return $this->result;
    }
}