<?php

namespace app\admin\controller\fastim;

use think\Db;
use Exception;
use app\common\controller\Backend;
use addons\fastim\library\Common;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户管理
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\fastim\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fastim\User;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("occupationList", Common::formatOccupation(false));// 职业
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params                = $this->preExcludeFields($params);
                $params['welcome_msg'] = Common::htmlImgUrlHandle($params['welcome_msg']);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params                = $this->preExcludeFields($params);
                $params['birthday']    = $params['birthday'] ? $params['birthday'] : date('Y-m-d');
                $params['welcome_msg'] = Common::htmlImgUrlHandle($params['welcome_msg']);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 加载im用户列表
     * @return [type] [description]
     */
    public function loaduser()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");

        $custom = (array)$this->request->request("custom/a");

        $primaryvalue = $this->request->request("keyValue");
        if ($primaryvalue !== null) {
            $where    = ['u.id' => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $custom) {
                foreach ($word as $key => $value) {
                    if ($value) {
                        $query->whereOr('u.nickname', 'like', '%' . $value . '%');
                        $query->whereOr('fu.nickname', 'like', '%' . $value . '%');
                        $query->whereOr('a.nickname', 'like', '%' . $value . '%');
                    }
                }

                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }

        $res = \think\Db::name('fastim_user')
            ->alias('u')
            ->field('u.id,u.nickname,fu.nickname as fu_nickname,a.nickname as a_nickname')
            ->join('user fu', 'fu.id=u.user_id', 'LEFT')
            ->join('admin a', 'a.id=u.admin_id', 'LEFT')
            ->where($where)
            ->order('u.createtime desc')
            ->page($page, $pagesize)
            ->select();

        $total = \think\Db::name('fastim_user')
            ->alias('u')
            ->join('user fu', 'fu.id=u.user_id', 'LEFT')
            ->join('admin a', 'a.id=u.admin_id', 'LEFT')
            ->where($where)
            ->order('u.createtime desc')
            ->count('u.id');

        foreach ($res as $key => $value) {
            if ($value['a_nickname'] || $value['fu_nickname']) {
                $res[$key]['nickname'] = $value['nickname'] . '(' . ($value['a_nickname'] ? $value['a_nickname'] : $value['fu_nickname']) . ')';
            }
            unset($res[$key]['fu_nickname'], $res[$key]['a_nickname']);
        }

        return json(['list' => $res, 'total' => $total]);
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model->with(['fauser', 'admin', 'csrgroup'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('csrgroup')->visible(['name']);

                $row->getRelation('fauser')->visible(['nickname', 'mobile']);
                $row->getRelation('admin')->visible(['nickname']);
                $row->hidden(['token', 'wechat_openid']);

                $row->trueNickname = Common::trueAttr(Common::nicknameSort([
                    $row->fauser->nickname,
                    $row->admin->nickname,
                    $row->nickname
                ], $row->id));

                $row->avatar = Common::avatarSrc([
                    $row->avatar,
                    $row->fauser->avatar,
                    $row->admin->avatar
                ], $row->trueNickname);

                $row->mobile = Common::trueAttr([
                    $row->mobile,
                    $row->fauser->mobile
                ]);
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

}
