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


use app\admin\model\Office;

class Accounts extends Base
{
    // 会员列表
    public function index()
    {
        $toExcel = input('param.toExcel', 0);

        if(request()->isAjax()){
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where = [];
            if (strlen($param['searchText'])) {
                if($param['account'] == 'account_name'){
                    $where['account_name'] = ['like', '%' . $param['searchText'] . '%'];
                }
                if($param['account'] == 'nick_name'){
                    $where['nick_name'] = ['like', '%' . $param['searchText'] . '%'];
                }
            }
            //标签
            if ($param['label_id'] != '' && $param['label_id'] != 0) {
                $where['label_id'] = $param['label_id'];
            }
            if (strlen($param['start']) && strlen($param['end']) && $param['start'] <= $param['end']) {
                $start = strtotime($param['start']);
                $end = strtotime($param['end'] . ' 23:59:59');
                $return['total'] = db('accounts')->where($where)->whereBetween('add_time', [$start, $end])->count();  //总数据
            }
            $result = db('accounts')->whereBetween('add_time', [$start, $end])->where($where)->limit($offset, $limit)->order('add_time', 'desc')->select();
            //所有客服
            $users = db('users')->select();
            //所有标签
            $label = db('accountslabel')->select();
            foreach($result as $key=>$vo){
                $result[$key]['add_time'] = date('Y-m-d H:i:s',$result[$key]['add_time']);
                $result[$key]['last_login_time'] = date('Y-m-d H:i:s',$result[$key]['last_login_time']);
                for($i=0;$i<count($users);$i++){
                    if($vo['user_id'] == $users[$i]['id']){
                        $result[$key]['user_name'] = $users[$i]['user_name'];
                    }
                }
                for($j=0;$j<count($label);$j++){
                    if($vo['label_id'] == $label[$j]['id']){
                        $result[$key]['label'] = $label[$j]['name'];
                    }
                }
                // 生成操作按钮
                $result[$key]['operate'] = $this->makeBtn($vo['id']);
            }
            //$return['total'] = db('accounts')->count();  //总数据
            $return['rows'] = $result;

            return json($return);
        }
        //所有标签
        $label = db('accountslabel')->select();
        if(!empty($label)){
            $option = '<option value="0">会员标签</option>';
            for($i=0;$i<count($label);$i++){
                $option = $option.'<option value="'.$label[$i]['id'].'">'.$label[$i]['name'].'</option>';
            }
            $labeloption = '<select lay-verify="required" lay-filter="label">'.$option.'</select>';
        }

        $this->assign([
            'label' => $label,
            'labeloption' => $labeloption,
            'status' => config('kf_status')
        ]);

        return $this->fetch();
    }

    //用户信息导出
    public function toexcel()
    {
        $param = input('param.');
        $start = $param['start'];
        $end = $param['end'];
        $where = [];
        if(!empty($param['label_id'])){
            $where['label_id'] = $param['label_id'];
        }
        if($param['account'] == 'account_name'){
            if(!empty($param['username'])){
                $where['account_name'] = ['like', '%' . $param['username'] . '%'];
            }
        }
        if($param['account'] == 'nick_name'){
            if(!empty($param['username'])){
                $where['nick_name'] = ['like', '%' . $param['username'] . '%'];
            }
        }
        $result = db('accounts')->whereBetween('add_time', [strtotime($start), strtotime($end . ' 23:59:59')])->where($where)->order('add_time', 'desc')->select();
        //所有标签
        $label = db('accountslabel')->select();
        foreach($result as $key=>$vo){
            $result[$key]['add_time'] = date('Y-m-d H:i:s',$result[$key]['add_time']);
            $result[$key]['last_login_time'] = date('Y-m-d H:i:s',$result[$key]['last_login_time']);
            $result[$key]['label'] = '';
            for($j=0;$j<count($label);$j++){
                if($vo['label_id'] == $label[$j]['id']){
                    $result[$key]['label'] = $label[$j]['name'];
                }
            }
        }
        $head = ['账号', '昵称', '邮箱', '电话', '注册时间', '最近一次访问时间', '标签', '备注'];
        $key = ['account_name', 'nick_name', 'account_email', 'account_phone', 'add_time', 'last_login_time', 'label', 'remark'];
        (new Office())->outdata('会员数据导出', $result, $head, $key);
        return true;
    }

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

    // 编辑用户
    public function edit()
    {
        if(request()->isAjax()){

            $param = input('post.');
            $info = array();
            $rules = '/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/';

            if(!empty($param['account_email'])){
                if(!preg_match($rules,$param['account_email'])){
                    return json(['code' => -9, 'data' => '', 'msg' => '请输入正确的邮箱']);
                }
            }

            if(!empty($param['account_phone'])){
                if(!preg_match("/^1[34578]\d{9}$/", $param['account_phone'])){
                    return json(['code' => -10, 'data' => '', 'msg' => '请输入正确的手机号码']);
                }
            }

            if($param['label_id'] == 0){
                return json(['code' => -10, 'data' => '', 'msg' => '请选择用户标签']);
            }

            $info['nick_name'] = $param['nick_name'];
            $info['account_email'] = $param['account_email'];
            $info['account_phone'] = $param['account_phone'];
            $info['address'] = $param['address'];
            $info['label_id'] = $param['label_id'];
            $info['remark'] = $param['remark'];
            if(!empty($param['user_id']) && $param['user_id'] != 0){
                $info['user_id'] = $param['user_id'];
            }
            try{
                db('accounts')->where('id', $param['id'])->update($info);
            }catch(\Exception $e){
                return json(['code' => -6, 'data' => '', 'msg' => $e->getMessage()]);
            }

            return json(['code' => 1, 'data' => url('accounts/index'), 'msg' => '编辑用户成功']);
        }

        $id = input('param.id/d');
        $info = db('accounts')->where('id', $id)->find();
        $label = db('accountslabel')->where('id', $info['label_id'])->find();
        $info['label'] = $label['name'];
        //所有标签
        $label = db('accountslabel')->select();

        //服务记录
        //前一个月的时间戳
        $start = time()-2592000;
        //当前时间戳
        $end = time();
        $service_log = db('service_log a')->join('users b','a.kf_id=b.id')->field('a.servicelog_id,a.start_time,b.user_name')->whereBetween('a.start_time', [$start, $end])->where('a.user_id', $id)->order('a.start_time','desc')->select();
        for($i=0;$i<count($service_log);$i++){
            $service_log[$i]['start_time'] = date("Y-m-d H:i:s",$service_log[$i]['start_time']);
        }

        //转为日期时间格式
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);

        //所有客服
        $users = db('users')->select();

        $this->assign([
            'info' => $info,
            'users' => $users,
            'label' => $label,
            'service_log' => $service_log,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    // 删除用户
    public function delAccount()
    {
        if(request()->isAjax()){
            $id = input('param.id/d');
            try{
                db('accounts')->where('id', $id)->delete();
            }catch(\Exception $e){
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => 'accounts/index', 'msg' => '删除客服成功']);
        }
    }

    // 生成按钮
    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 style="margin-left:5px;" href="' . url('Accounts/edit', ['id' => $id]) . '"><button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';

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

        return $operate;
    }

    // 用户标签列表
    public function label()
    {
        if(request()->isAjax()){
            $param  = input('param.');
            $limit  = $param['pageSize'];
            $offset = (($param['pageNumber'] - 1) * $limit);
            $where = [];
//            if (strlen($param['searchText'])) {
//                $where['name'] = ['like', '%' . $param['searchText'] . '%'];
//            }
            $result = db('accountslabel')->where($where)->limit($offset, $limit)->order('id', 'asc')->select();

            foreach($result as $key=>$vo){
                $result[$key]['add_time'] = date('Y-m-d H:i:s',$result[$key]['add_time']);

                // 生成操作按钮
                if($vo['id'] != 1){
                    $result[$key]['operate'] = $this->makeBtnLabel($vo['id']);
                }else{
                    $result[$key]['operate'] = $operate = '<a style="margin-left:5px;" href="' . url('Accounts/editlabel', ['id' => $vo['id']]) . '"><button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';
                }
            }
            $return['total'] = db('accountslabel')->count();  //总数据
            $return['rows'] = $result;
            return json($return);
        }
        return $this->fetch();
    }

    // 添加用户标签
    public function addlabel()
    {
        if (request()->isAjax()) {
            $param = input('post.');
            $has = db('accountslabel')->where('name',$param['name'])->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '此用户标签已存在']);
            }
            $info = array();
            $info['name'] = $param['name'];
            $info['add_time'] = time();
            try {
                db('accountslabel')->insert($info);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '添加用户标签成功']);
        }
        $this->assign([
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    // 编辑用户标签
    public function editlabel()
    {
        // 菜单id
        $id = input('param.id/d');
        if (request()->isAjax()) {
            $param = input('post.');
            $has = db('accountslabel')->where('name',$param['name'])->where('id','<>',$id)->find();
            if(!empty($has)){
                return json(['code' => -1, 'data' => '', 'msg' => '此用户标签已存在']);
            }
            $info = array();
            $info['name'] = $param['name'];

            try {
                db('accountslabel')->where('id', $param['id'])->update($info);
            } catch (\Exception $e) {
                return json(['code' => -2, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '编辑用户标签成功']);
        }
        $label = db('accountslabel')->where('id',$id)->find();

        $this->assign([
            'label' => $label,
            'id' => $id,
            'status' => config('kf_status')
        ]);
        return $this->fetch();
    }

    // 删除用户标签
    public function delLabel()
    {
        if (request()->isAjax()) {
            //留言类型id
            $id = input('param.id/d');

            try {
                db('accounts')->where('label_id', $id)->update(['label_id'=>1]);
                db('accountslabel')->where('id', $id)->delete();
            } catch (\Exception $e) {
                return json(['code' => -1, 'data' => '', 'msg' => $e->getMessage()]);
            }
            return json(['code' => 1, 'data' => '', 'msg' => '删除用户标签成功']);
        }
    }

    // 生成标签按钮
    private function makeBtnLabel($id)
    {
        $operate = '<a style="margin-left:5px;" href="' . url('Accounts/editlabel', ['id' => $id]) . '"><button type="button" class="btn btn-primary btn-sm"> 编辑</button></a> ';

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

        return $operate;
    }
}
