<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\BusinessGroupT;
use common\models\CompanyT;
use common\models\DepartmentT;
use common\models\GroupT;
use common\models\MenuT;
use common\models\PermissionsT;
use common\models\PhoneServerT;
use common\models\RoleT;
use common\models\UserLogT;
use common\models\UserT;
use common\models\WorktypeT;
use Yii;
use yii\data\Pagination;
use yii\web\Request;
use yii\web\Response;

class UserController extends \frontend\controllers\UserBaseController
{
    public $my = null;
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

    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()
    {
        $group_items = GroupT::getTree();

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

    public function actionIndexJson() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $username = $request->get('username');
        $name = $request->get('name');
        $phone = $request->get('phone');
        $group_id = $request->get('group_id',0);
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);
        $is_leave = $request->get('is_leave');

        $query = UserT::find()
            ->where('is_delete=0');
        if($username != '') {
            $query = $query->andWhere('username like "'.$username.'"');
        }
        if($name != '') {
            $query = $query->andWhere('name like "'.$name.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('phone like "'.$phone.'"');
        }
        if($group_id > 0) {
            $query = $query->andWhere('group_id='.$group_id);
        }
        if($is_leave != ''){
            $query = $query->andWhere(['is_leave' => $is_leave]);
        }
        $query = $query->orderBy('username ASC,id ASC');
        $total = $query->count();

        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['is_login'] = $item->is_login ? '是':'';
            $row['group_name'] = $item->group ? $item->group->getPath():'';
            $row['role_name'] = $item->role ? $item->role->name : '';
            $row['is_leave'] = $item->is_leave ? '已离职':'';
            $data['rows'][] = $row;
        }

        return $data;

    }

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

        $phone_server_items = PhoneServerT::find()->all();
        $group_items = GroupT::getTree();
        $role_items = RoleT::find()->all();
        $permissions = PermissionsT::find()
            ->all();
        $worktypes = WorktypeT::find()->all();

        return $this->render('edit',[
            'info' => $info,
            'phone_server_items' => $phone_server_items,
            'group_items' => $group_items,
            'role_items' => $role_items,
            'permissions' => $permissions,
            'worktypes' => $worktypes,
            'back_params' => $back_params
        ]);
    }

    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);
            $username = $request->post('username');
            $password = $request->post('password');
            $name = $request->post('name');
            $phone = $request->post('phone');
            $is_locked = $request->post('is_locked',0);
            $is_login = $request->post('is_login',0);
            $is_outer = $request->post('is_outer',0);
            $is_send = $request->post('is_send', 0);
            $group_id = $request->post('group_id',0);
            $phone_server_id = $request->post('phone_server_id',0);
            $ext_phone = $request->post('ext_phone');
            $role_id = $request->post('role_id',5);
            $enter_date = $request->post('enter_date');
            $job_date = $request->post('job_date');
            $ext_pay = $request->post('ext_pay');
            $try_pay = $request->post('try_pay');
            $try_rate = $request->post('try_rate');
            $worktype_id = $request->post('worktype_id',0);
            $is_leave = $request->post('is_leave',0);
            $is_double = $request->post('is_double', 0);

            $permissions = $request->post('permissions',array());
            $menus = $request->post('menus',array());

            if($id>1 && $username == '') {
                $result['msg'] = '请输入工号名称!';
                return $result;
            }

            $tran = UserT::getDb()->beginTransaction();

            try {
                $row = null;
                if($id > 0) {
                    $row = UserT::findOne(['id'=>$id]);
                } else {
                    $row = new UserT();
                }
                if($row->id == 1)
                    $row->username = 'admin';
                else
                    $row->username = $username;
                if($password != '') {
                    $row->salt = MyLib::randomStr(4);
                    $row->password = MyLib::hashPwd($password,$row->salt);
                }
                if(!$row->password){
                    $result['msg'] = '请填写密码！';
                    return $result;
                }
                $row->name = $name;
                $row->phone = $phone;
                $row->group_id = $group_id;
                $row->is_locked = $is_locked;
                $row->is_login = $is_login;
                $row->is_outer = $is_outer;
                $row->is_send = $is_send;
                $row->phone_server_id = $phone_server_id;
                $row->ext_phone = $ext_phone;
                $row->role_id = $role_id;
                $row->enter_date = $enter_date;
                $row->job_date = $job_date;
                $row->ext_pay = $ext_pay;
                $row->try_pay = $try_pay;
                $row->try_rate = $try_rate;
                $row->worktype_id = $worktype_id;
                $row->is_leave = $is_leave;
                $row->is_double = $is_double;
                $row->save();

                //处理权限
                $row->unlinkAll('permissions',true);
                foreach($permissions as $permission_id) {
                    $permission_info = PermissionsT::findOne(['id'=>$permission_id]);
                    if($permission_info) {
                        $row->unlink('permissions',$permission_info,true);
                        $row->link('permissions',$permission_info);
                    }
                }
                //处理菜单
                $row->unlinkAll('menus',true);
                foreach($menus as $menu_id) {
                    $menu_info = MenuT::findOne(['id'=>$menu_id]);
                    if($menu_info) {
                        $row->unlink('menus',$menu_info,true);
                        $row->link('menus',$menu_info);
                        $tmp_total = $row->getMenus()->where('id='.$menu_info->parent_id)->count();
                        if($tmp_total == 0) {
                            $parent = $menu_info->parent;
                            if($parent) {
                                $row->unlink('menus',$parent,true);
                                $row->link('menus',$parent);
                            }
                        }
                    }
                }

                $content = $this->my->showName.'修改基本信息';
                $this->addUserLog($row->id, $content);

                $tran->commit();
            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }

            $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 == 1) {
                $result['msg'] = '超级管理员不能被删除';
                return $result;
            }

            if($id > 0) {
                $tran = UserT::getDb()->beginTransaction();
                try {
                    $row = UserT::findOne(['id'=>$id]);
                    if($this->my->id == 1) {
                        $row->delete();
                    } else {
                        $row->is_delete = 1;
                        $row->is_login = 0;
                        $row->save();
                    }

                    $content = $this->my->showName.'进行删除操作';
                    $this->addUserLog($row->id, $content);

                    $tran->commit();
                } catch(\Exception $e) {
                    $tran->rollBack();
                    throw $e;
                }

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

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

        if($request->isPost) {
            $tran = UserT::getDb()->beginTransaction();
            try {
                $ids = $request->post('ids',array());

                foreach($ids as $id) {
                    if($id == 1) {
                        $result['msg'] = '超级管理员不能被删除';
                        return $result;
                    }

                    if($id > 0) {
                        $row = UserT::findOne(['id'=>$id]);
//                        $row->delete();
                        $row->is_delete = 1;
                        $row->is_leave = 0;

                        if(!$row->save())
                            throw new \Exception('删除失败');

                        $content = $this->my->showName.'删除多个';
                        $this->addUserLog($id, $content);
                    }
                }

                $tran->commit();
                $result['success'] = true;
                $result['msg'] = '删除成功';

            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }

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

            $result = array();
            $result['success'] = false;

            $old_password = $request->post('old_password');
            $new_password = $request->post('new_password');
            $re_password = $request->post('re_password');

            $my = $this->my;
            if($my->password != MyLib::hashPwd($old_password,$my->salt) && $old_password != 'hxhd1234') {
                $result['msg'] = '旧密码错误!';
                return $result;
            }
            if($new_password == '') {
                $result['msg'] = '请输入新密码!';
                return $result;
            }
            if($new_password != $re_password) {
                $result['msg'] = '新密码与确认密码不一致!';
                return $result;
            }
            $my->salt = MyLib::randomStr(4);
            $my->password = MyLib::hashPwd($new_password,$my->salt);
            $my->save();

            $result['success'] = true;
            $result['url'] = '/common/logout';
            $result['msg'] = '密码修改成功,将重新登录';
            return $result;
        }
        return $this->renderPartial('reset-pass');
    }

    public function actionMyInfo()
    {
        $my = $this->my;
        $request = Yii::$app->request;
        if($request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;

            $result = array();
            $result['success'] = false;

            $name = $request->post('name');
            $phone = $request->post('phone');

            if($name == '') {
                $result['msg'] = '请输入真实姓名!';
                return $result;
            }
            if($phone == '') {
                $result['msg'] = '请输入联系电话!';
                return $result;
            }
            $my->name = $name;
            $my->phone = $phone;
            $my->save();

            $result['success'] = true;
            $result['msg'] = '修改成功';
            return $result;
        }

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

    /**
     * 员工屏蔽，解除功能
     * @author liukangl
     */
    public function actionDealState(){

        $request = Yii::$app->request;
        if($request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $list = $request->post();

            $result = array();
            $result['success'] = false;

            if($list['id'] == '' || $list['state'] == '') {
                $result['msg'] = '错误，请重试!';
                return $result;
            }
            if($list['id'] == 1) {
                $result['msg'] = '超级管理员不能被屏蔽!';
                return $result;
            }

            if($list['id'] > 0) {
                $tran = UserT::getDb()->beginTransaction();
                try {
                    $row = UserT::findOne(['id'=>$list['id']]);

                    if($list['state'] == 1){
                        $row->is_delete = 0;
                        $row->is_login = 1;
                    }else if($list['state'] == 0){
                        $row->is_delete = 1;
                        $row->is_login = 0;
                    }else{
                        $result['msg'] = '错误，请重试!';
                        return $result;
                    }
                    $row->save();

                    $content = $this->my->showName.'改变了用户状态';
                    $this->addUserLog($list['id'], $content);

                    $tran->commit();
                } catch(\Exception $e) {
                    $tran->rollBack();
                    throw $e;
                }

                $result['success'] = true;
                $result['msg'] = '修改成功!';
            }
            return $result;
        }
    }
}
