<?php
/**
 * User: nickbai
 * Date: 2017/10/23 13:33
 * Email: 1902822973@qq.com
 */
namespace app\admin\controller;

class Users extends Base
{
    // 客服列表
    public function index()
    {
        if(request()->isAjax()){
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where = [];
            if (empty($param['searchText']) === false || intval($param['searchText']) == 0) {
                if($param['user'] == 'user_account'){
                    $where['user_account'] = ['like', '%' . $param['searchText'] . '%'];
                }
                if($param['user'] == 'user_name'){
                    $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
                }
               // $where['user_account|user_name|user_job_number|fullname'] = ['like', '%' . $param['searchText'] . '%'];
            }else{
                return 1;
            }
            //客服组
            if ($param['group_id'] != '' && $param['group_id'] != 0) {
                $where['group_id'] = $param['group_id'];
            }
            $result = db('users')->where($where)->limit($offset, $limit)->order('id', 'desc')->select();
            foreach($result as $key=>$vo){
                // 优化显示头像
                $result[$key]['user_avatar'] = '<img src="' . $vo['user_avatar'] . '" height="40px">';

                // 优化显示状态
                if(1 == $vo['status']){
                    $result[$key]['status'] = '<span style="color: #2fbe1b">启用</span>';
                }else{
                    $result[$key]['status'] = '<span style="color: red">禁用</span>';
                }

                // 优化显示状态
                if(1 == $vo['user_overview']){
                    $result[$key]['user_overview'] = '<span style="color: #2fbe1b">启用</span>';
                }else{
                    $result[$key]['user_overview'] = '<span style="color: red">禁用</span>';
                }

                // 查询分组
                $result[$key]['group'] = '-';
                $groups = db('groups')->field('name')->where('id', $vo['group_id'])->find();
                if(!empty($groups)){
                    $result[$key]['group'] = $groups['name'];
                }

                // 优化显示在线状态
                /*if(1 == $vo['online']){
                    $result[$key]['online'] = '<span class="label label-primary">在线</span>';
                }else{
                    $result[$key]['online'] = '<span class="label label-danger">离线</span>';
                }*/

                // 生成操作按钮
                $result[$key]['operate'] = $this->makeBtn($vo['id']);
            }

            $return['total'] = db('users')->where($where)->count();  //总数据
            $return['rows'] = $result;

            return json($return);

        }

        //所有客服组
        $users = db('groups')->select();
        $groupsoption = '';
        if(!empty($users)){
            $option = '<option value="0">所有客服组</option>';
            for($i=0;$i<count($users);$i++){
                $option = $option.'<option value="'.$users[$i]['id'].'">'.$users[$i]['name'].'</option>';
            }
            $groupsoption = '<select lay-verify="required" lay-filter="group">'.$option.'</select>';
        }
        $this->assign([
            'groupsoption' => $groupsoption
        ]);

        return $this->fetch();
    }

    // 添加客服
    public function addUser()
    {
        if(request()->isPost()){

            $param = input('post.');
            unset($param['file']); // 删除layui头像上传隐藏字段

            // 检测账号
            if(!empty($param['user_account'])){
                $user = db('users')->where('user_account', $param['user_account'])->find();
                if(!empty($user)){
                    return json(['code' => -1, 'data' => '', 'msg' => '该账号已存在']);
                }
            }
            // 检测客服工号
            if(!empty($param['user_job_number'])){
                $user_job_number = db('users')->where('user_job_number', $param['user_job_number'])->find();
                if(!empty($user_job_number)){
                    return json(['code' => -2, 'data' => '', 'msg' => '该工号已经存在']);
                }
            }
            if(empty($param['group_id'])){
                return json(['code' => -3, 'data' => '', 'msg' => '请选择分组']);
            }
            // 检测密码
            $n = preg_match_all("/^[a-zA-Z\d_]{6,}$/",$param['user_pwd'],$array);
            if($n != 1){
                return json(['code' => -8, 'data' => '', 'msg' => '密码长度不够，请重新输入']);
            }
            // 检测头像
//            if(empty($param['user_avatar'])){
//                return json(['code' => -4, 'data' => '', 'msg' => '请上传头像']);
//            }

            $param['user_pwd'] = md5($param['user_pwd'] . config('salt'));
            $param['online'] = 2; // 离线状态

            try{
                db('users')->insert($param);
            }catch(\Exception $e){
                return json(['code' => -5, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => 'users/index', 'msg' => '添加客服成功']);
        }

        $this->assign([
            'groups' => db('groups')->select(),
            'status' => config('kf_status')
        ]);

        return $this->fetch('adduser');
    }

    // 编辑客服
    public function editUser()
    {
        if(request()->isAjax()){

            $param = input('post.');
            unset($param['file']); // 删除layui头像上传隐藏字段

            // 检测客服工号
            if(!empty($param['user_job_number'])){
                $user_job_number = db('users')->where('user_job_number', $param['user_job_number'])->where('id','<>',$param['id'])->find();
                if(!empty($user_job_number)){
                    return json(['code' => -2, 'data' => '', 'msg' => '该工号已经存在']);
                }
            }
            if(empty($param['group_id'])){
                return json(['code' => -3, 'data' => '', 'msg' => '请选择分组']);
            }
            // 检测密码
            if(!empty($param['user_pwd'])){
                $n = preg_match_all("/^[a-zA-Z\d_]{6,}$/",$param['user_pwd'],$array);
                if($n != 1){
                    return json(['code' => -8, 'data' => '', 'msg' => '密码长度不够，请重新输入']);
                }
            }

            if(empty($param['group_id'])){
                return json(['code' => -2, 'data' => '', 'msg' => '请选择分组']);
            }

            $addar = array();
            $addar['user_name'] = $param['user_name'];
            $addar['user_job_number'] = $param['user_job_number'];
            if(!empty($param['user_pwd'])){
                $addar['user_pwd'] = md5($param['user_pwd'] . config('salt'));
            }
            $addar['user_email'] = $param['user_email'];
            $addar['phone'] = $param['phone'];
            $addar['fullname'] = $param['fullname'];
            $addar['signature'] = $param['signature'];
            $addar['group_id'] = $param['group_id'];
            $addar['status'] = $param['status'];
            $addar['user_overview'] = $param['user_overview'];
            if(!empty($param['user_avatar'])){
                $addar['user_avatar'] = $param['user_avatar'];
            }

            try{
                db('users')->where('id', $param['id'])->update($addar);
            }catch(\Exception $e){
                return json(['code' => -6, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => 'users/index', 'msg' => '编辑客服成功']);
        }
        $id = input('param.id/d');
        $info = db('users')->where('id', $id)->find();

        $this->assign([
            'info' => $info,
            'status' => config('kf_status'),
            'groups' => db('groups')->select()
        ]);
        return $this->fetch('edituser');
    }

    //重置密码为123456
    public function resetPwd(){
        if(request()->isAjax()){
            $id = input('param.id/d');
            $password = md5('123456' . config('salt'));
            try{
                db('users')->where('id', $id)->update(['user_pwd' => $password]);
            }catch(\Exception $e){
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => 'accounts/index', 'msg' => '重置密码成功']);
        }
    }

    // 删除客服
    public function delUser()
    {
        if(request()->isAjax()){
            $id = input('param.id/d');

            try{
                db('users')->where('id', $id)->delete();
            }catch(\Exception $e){
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => '', 'msg' => '删除客服成功']);
        }
    }

    // 上传客服头像
    public function upAvatar()
    {
        if(request()->isAjax()) {

            $file = request()->file('file');
            if (!empty($file)) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    $src = '/uploads' . '/' . date('Ymd') . '/' . $info->getFilename();
                    return json(['code' => 0, 'data' => ['src' => $src], 'msg' => 'ok']);
                } else {
                    // 上传失败获取错误信息
                    return json(['code' => -1, 'data' => '', 'msg' => $file->getError()]);
                }
            }
        }
    }

    // 生成按钮
    private function makeBtn($id)
    {
//        $operate = '<a href="javascript:resetPwd(' . $id . ')"><button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 重置密码</button></a>';

        $operate = '<a href="' . url('users/editUser', ['id' => $id]) . '">';
//        $operate .= '<button type="button" class="btn btn-primary btn-sm"><i class="fa fa-paste"></i> 编辑</button></a> ';
        $operate .= '<button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';

        $operate .= '<a href="javascript:userDel(' . $id . ')"><button type="button" class="btn btn-danger btn-sm">';
//        $operate .= '<i class="fa fa-trash-o"></i> 删除</button></a> ';
        $operate .= ' 删除</button></a> ';

        //$operate .= '<a href="javascript:;">';
        //$operate .= '<button type="button" class="btn btn-info btn-sm"><i class="fa fa-institution"></i> 详情</button></a>';

        return $operate;
    }
}
