<?php
/**
 * Created by PhpStorm.
 * User: sicilon_IT
 * Date: 2020/1/22
 * Time: 21:19
 */
namespace app\admin\logic;

use app\admin\model\rolesmodel;
use app\admin\model\roleusermodel;
use app\admin\model\webusermodel;
use think\facade\Log;

class webuserlogic
{
    public function getlogininfo($lname, $lpwd)
    {
        $webusertable = new webusermodel();
        $userinfo = $webusertable->getlogininfo($lname, $lpwd);
        //var_dump($userinfo);
        return $userinfo;
    }
    /**
     * 校验登录 并修改token
     */
    public function userlogin($lname, $lpwd, $updateToken = true)
    {
        $m_wu = new webusermodel();
        $userinfo = $m_wu->getlogininfomd5($lname, $lpwd);
        if (empty($userinfo)) {
            return backarr(0, '无用户信息');
        }
        $token = $userinfo['token'];
        if ($updateToken) {
            $result = $this->updateToken($userinfo['id']);
            if (1 != $result['status']) {
                return $result;
            }
        }
        $token = $result['data']['token'];
        return backarr(1, '登录成功', ['token' => $token, 'id' => $userinfo['id']]);
    }
    /**
     * 用户登出
     * 改用户token
     * 20211204
     * wj
     */
    public function updateToken($uid = 0)
    {
        $m_wu = new webusermodel();
        $m_r = new rolesmodel();
        $m_ru = new roleusermodel();
        $rwhere = ['name' => '普通用户', 'is_active' => 1];
        $rid = 0; //不改token组id
        $userinfo = [];
        $rinfo = $m_r->getInfo($rwhere);
        if (!empty($rinfo)) {
            $rid = $rinfo['id'];
        }
        if (empty($uid)) {
            $token = request()->server('HTTP_TOKEN');
            if (empty($token)) {
                return backarr(0, "无token数据");
            }
            $where = ['token' => $token];
            $field = ['id', 'user_name', 'token'];
            $userinfo = $m_wu->getInfo($where, $field);
        } else {
            $where = ['id' => $uid];
            $field = ['id', 'user_name', 'token'];
            $userinfo = $m_wu->getInfo($where);
        }
        if (empty($userinfo)) {
            return backarr(0, "无用户信息");
        }
        $ruwhere = ['uid' => $userinfo['id']];
        $ruinfo = $m_ru->getInfo($ruwhere);
        $changeToken = true;
        if (!empty($ruinfo) && !empty($rid)) {
            if ($ruinfo['rid'] == $rid) {
                $changeToken = false;
            }
        }
        if ($changeToken) {
            $token = $this->getToken($userinfo['user_name']);
            $updateData = [
                'token' => $token,
            ];
            $where = ['id' => $userinfo['id']];
            $row = $m_wu->updateinfo($where, $updateData);
            if (empty($row)) {
                log::info($userinfo['user_name'] . " token 修改失败");
                return backarr(0, "token 修改失败");
            }
        } else {
            $token = $userinfo['token'];
        }
        return backarr(1, "操作成功", ['uid' => $userinfo['id'], 'token' => $token]);
    }
    /***
     * 获取用户token
     */
    private function getToken($username)
    {
        $str = md5(uniqid(md5(microtime(true)), true));
        $token = sha1($str . $username);
        return $token;
    }
    /**
     * 获取用户信息 权限组名 和头像 待改
     * 20211101
     * wj
     */
    public function queryinfobytoken($arr)
    {
        if (!isset($arr['token']) || empty($arr['token'])) {
            return backarr(0, "请求错误");
        }
        $defaultData = [
            //'access' => 'admin',
            'avatar' => 'https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png',
        ];
        $token = $arr['token'];
        $m_wu = new webusermodel();
        $where = ['token' => $token];
        $field = ['id', 'user_name'];
        $userinfo = $m_wu->getInfo($where, $field);
        if (empty($userinfo)) {
            return backarr(0, "无用户数据");
        }
        //获取权限组名
        $m_ru = new roleusermodel();
        $ruwhere = [
            'uid' => $userinfo['id'],
        ];
        $ruinfo = $m_ru->getInfo($ruwhere);
        if (!empty($ruinfo)) {
            $rwhere = [
                'id' => $ruinfo['rid'],
                'is_active' => 1,
            ];
            $m_r = new rolesmodel();
            $rinfo = $m_r->getInfo($rwhere);
            if ($rinfo) {
                $userinfo['access'] = $rinfo['flag_bit'];
            }
        }
        if (!isset($userinfo['access'])) {
            $userinfo['access'] = "";
        }
        if (empty($userinfo)) {
            return backarr(0, "无数据");
        } else {
            $userinfo = array_merge($defaultData, $userinfo->toArray());
            return backarr(1, "查询成功", $userinfo);
        }
    }

    /***
     * 获取用户信息 通过id
     * 20211103
     * wj
     */
    public function queryinfobyid($arr)
    {
        $id = $arr['id'];
        $m_wu = new webusermodel();
        $where = ['id' => $id];
        $fields = ['id', 'user_name', 'email', 'create_date', 'isactive', 'create_id'];
        $userinfo = $m_wu->getInfo($where, $fields);
        if (empty($userinfo)) {
            return backarr(0, "无数据");
        }
        if (!empty($userinfo['create_id'])) {
            $where = ['id' => $userinfo['create_id']];
            $createinfo = $m_wu->getInfo($where, ['user_name']);
            $userinfo['create_user_name'] = $createinfo['user_name'];
        }
        return backarr(1, "查询成功", $userinfo);
    }

    public function queryinfowitchsetting($id)
    {
        $m_wu = new webusermodel();
        $m_ru = new roleusermodel();
        $where = ['id' => $id];
        $fields = ['id', 'user_name', 'email', 'create_date', 'isactive', 'create_id'];
        $userinfo = $m_wu->getInfo($where, $fields);
        if (empty($userinfo)) {
            return backarr(0, "无数据");
        }
        if (!empty($userinfo['create_id'])) {
            $where = ['id' => $userinfo['create_id']];
            $createinfo = $m_wu->getInfo($where, ['user_name']);
            $userinfo['create_user_name'] = $createinfo['user_name'];
        }
        $userinfo['setting'] = ['access' => '', 'access_name' => ''];
        $roleinfo = $m_ru->getinfoforuser($id);
        if ($roleinfo) {
            $roleinfo = $roleinfo[0];
            $setting = [
                'access' => $roleinfo['flag_bit'],
                'access_name' => $roleinfo['name'],
            ];
            $userinfo['setting'] = $setting;
        }

        return backarr(1, "查询成功", $userinfo);
    }

    public function editwebuser($arr)
    {
        if (isset($arr['id']) && !empty($arr['id'])) {
            $result = $this->updatewebuserinfo($arr);
        } else {
            $result = $this->newwebuser($arr);
        }
        return $result;
    }
    /**
     * 新建web用户
     * 登录名不可重复
     */
    public function newwebuser($arr)
    {
        $name = $arr['name'];
        $m_wu = new webusermodel();
        $where = ['user_name' => $name];
        $userinfo = $m_wu->getInfo($where);
        if ($userinfo) {
            return backarr(0, "用户已存在");
        }
        $insertData = [];
        $insertData['user_name'] = $name;
        $insertData['user_password'] = md5($name . $arr['password']);
        $insertData['token'] = $this->getToken($name);
        $insertData['create_date'] = date('Y-m-d H:i:s');
        $insertData['create_id'] = $arr['userid'];
        if (isset($arr['email']) && !empty($arr['email'])) {
            $insertData['email'] = $arr['email'];
        }
        $id = $m_wu->insertData($insertData);
        if (empty($id)) {
            return backarr(0, "操作失败");
        }
        return backarr(1, "操作成功", ['id' => $id]);
    }
    /***
     * 改用户信息
     * 20211103
     * wj
     * 仅改用户邮箱
     */
    public function updatewebuserinfo($arr)
    {
        $id = $arr['id'];
        $m_wu = new webusermodel();
        $where = ['id' => $id];
        $userinfo = $m_wu->getInfo($where);
        if (empty($userinfo)) {
            return backarr(0, "用户不存在");
        }
        $updateData = [];
        if (isset($arr['email']) && !empty($arr['email'])) {
            $updateData['email'] = $arr['email'];
        }
        if (!empty($updateData)) {
            $row = $m_wu->updateinfo($where, $updateData);
            if (empty($row)) {
                return backarr(0, "操作失败");
            }
            return backarr(1, "操作成功", ['id' => $id]);
        }
        return backarr(0, "无修改数据");
    }
    /***
     * 改用户密码
     * 20211103
     * wj
     */
    public function updatepasswd($arr)
    {
        $fillfields = [
            'name', 'password',
        ];
        foreach ($fillfields as $key => $value) {
            if (!isset($arr[$value]) || empty($arr[$value])) {
                return backarr(0, "请求错误");
            }
        }
        $m_wu = new webusermodel();
        $name = trim($arr['name']);
        $password = trim($arr['password']);
        $where = ['user_name' => $name];
        $userinfo = $m_wu->getInfo($where);
        if (empty($userinfo)) {
            return backarr(0, "用户不存在");
        }
        $updateData = [
            'user_password' => md5($name . $password),
            'token' => $this->getToken($name),
        ];
        $id = $userinfo['id'];
        $where = ['id' => $id];
        $row = $m_wu->updateinfo($where, $updateData);
        if (empty($row)) {
            return backarr(0, "操作失败");
        }
        return backarr(1, "操作成功", ['id' => $id]);
    }

    /***
     * 改用户状态
     * 20211103
     * wj
     */
    public function updateisactive($arr)
    {
        $id = $arr['id'];
        $isactive = $arr['isactive'];
        $m_wu = new webusermodel();
        $where = ['id' => $id];
        $userinfo = $m_wu->getInfo($where);
        if (empty($userinfo)) {
            return backarr(0, "用户不存在");
        }
        //默认 isactive 0
        $isactive = in_array($isactive, [0, 1]) ? $isactive : 0;
        $updateData = ['isactive' => $isactive];
        $row = $m_wu->updateinfo($where, $updateData);
        if (empty($row)) {
            return backarr(0, "操作失败");
        }
        return backarr(1, "操作成功", ['id' => $id]);
    }

    /***
     * 获取用户列表
     * 20211103
     * wj
     */
    public function getalllist($arr)
    {
        $searchData = [];
        if (isset($arr['userName']) && !empty($arr['userName'])) {
            $searchData['user_name'] = ['like', '%' . $arr['userName'] . '%'];
        }
        if (isset($arr['isactive']) && in_array($arr['isactive'], [0, 1]) && is_numeric($arr['isactive'])) {
            $searchData['isactive'] = $arr['isactive'];
        }
        $m_wu = new webusermodel();
        $count = $m_wu->getList($searchData, 'count');
        if ($count <= 0) {
            return backarr(0, "无数据");
        }
        $page = !isset($arr['page']) || empty($arr['page']) ? 1 : $arr['page'];
        $size = !isset($arr['size']) || empty($arr['size']) ? 10 : $arr['size'];
        $fields = ['id'];
        $list = $m_wu->getList($searchData, $fields, $page, $size);
        foreach ($list as $key => &$value) {
            $result = $this->queryinfowitchsetting($value['id']);
            if (1 != $result['status']) {
                return backarr(0, $result['msg']);
            }
            $list[$key] = $result['data'];
        }
        $data = [
            'count' => $count,
            'list' => $list->toArray(),
        ];
        return backarr(1, "查询成功", $data);
    }

    /**
     * 按照id查用户信息
     * 20211110
     * wj
     */
    public function searchUserInfo($arr)
    {
        $id = 0;
        if (isset($arr['id']) && !empty($arr['id'])) {
            $id = $arr['id'];
        }
        if (empty($id)) {
            return backarr(0, "无数据");
        }
        $result = $this->queryinfowitchsetting($id);
        return $result;
    }

    /**
     * 保存用户和用户组关系
     * 20211110
     * wj
     */
    public function saveuserrole($arr)
    {
        $fillfields = ['access', 'uid'];
        foreach ($fillfields as $key => $value) {
            if (!isset($arr[$value]) || !isset($arr[$value])) {
                return backarr(0, "请求错误");
            }
        }

        $m_r = new rolesmodel();
        $m_wu = new webusermodel();
        $m_ru = new roleusermodel();

        $userid = $arr['uid'];
        $access = $arr['access'];

        $mrinfo = $m_r->getInfo(['flag_bit' => $access, 'is_active' => 1]);
        if (empty($mrinfo)) {
            return backarr(0, "无权限组");
        }

        $wuinfo = $m_wu->getInfo(['id' => $userid]);
        if (empty($wuinfo)) {
            return backarr(0, "用户不存在");
        }
        $ruinfo = $m_ru->getInfo(['uid' => $userid]);
        if (empty($ruinfo)) {
            $insertData = [
                'uid' => $userid,
                'rid' => $mrinfo['id'],
            ];
            $id = $m_ru->insertData($insertData);
        } else {
            $ruwhere = ['id' => $ruinfo['id']];
            $updateData = [
                'rid' => $mrinfo['id'],
            ];
            $row = $m_ru->updateinfo($ruwhere, $updateData);
            if ($row <= 0) {
                $id = 0;
            } else {
                $id = $ruinfo['id'];
            }
        }

        if (empty($id)) {
            return backarr(0, "操作失败");
        }
        return backarr(1, "操作成功", ['id' => $id]);
    }
}
