<?php

namespace App\User\Controllers;

use App\Exceptions\ApiException;
use App\Http\Controllers\BaseController;
use App\Models\BaseModel;
use App\User\Facades\AttachmentFacade;
use App\User\Facades\SysAdminUserFacade;
use App\User\Facades\SysMenuFuncAuthFacade;
use App\User\Facades\SysMenuFuncFacade;
use App\User\Facades\SysRoleFacade;
use App\User\Services\SysAdminUserService;
use Illuminate\Http\Request;


class SysAdminUserController extends BaseController
{

    protected $service = null;
    public function __construct(SysAdminUserService $service) {
        $this->service = $service;
    }
    /**
     * 用户登录
     * */
    public function login(Request $request)
    {
        $this->validate($request, [
            'user_name' => 'required',
            'password' => 'required'
        ], [
            'user_name.required' => '账号不能为空！',
            'password.required' => '密码不能为空！'
        ]);
        $ret = SysAdminUserFacade::adminLoginByPassword($request->only('user_name', 'password'));
        return $this->jsonResponse('', $ret['data'], $ret['code']);
    }

    /**
     * 登出
     * @param Request $request
     */
    public function logout(Request $request)
    {
        $token = $request->header('token');
        $rst = SysAdminUserFacade::logout($token);
        return $this->jsonResponse('ok', []);
    }

    /**
     * 获取后台登陆用户详情
     * */
    public function getUser()
    {
        $ret = SysAdminUserFacade::getUserDetail();
        return $this->jsonResponse('ok', $ret['data'], $ret['code']);
    }

    /**
     * 获取后台用户列表
     * */
    public function getAdminUserList(Request $request)
    {
        $params = [];
        $params['page_size'] = $request->input('page_size', 10);
        $params['page'] = $request->input('page', 1);
        $params['keyword'] = $request->input('keyword', '');
        $userListData = SysAdminUserFacade::getAdminUserList($params);
        return $this->jsonResponse('ok', $userListData);
    }

    /**
     * 新增用户
     * */
    public function addAdminUser(Request $request)
    {
        $params = $request->only(['user_name', 'real_name', 'phone', 'password', 'role_id']);
        $ret = SysAdminUserFacade::saveAdminUser($params);
        return $this->jsonResponse('ok', $ret);
    }

    /**
     * 编辑后台用户
     * */
    public function editAdminUser(Request $request)
    {
        $params = $request->only(['id', 'user_name', 'real_name', 'phone', 'password', 'login_password', 'role_id']);
        $ret = SysAdminUserFacade::saveAdminUser($params);
        return $this->jsonResponse('ok', $ret);
    }

    /**
     * 更改后台用户状态
     * */
    public function setAdminUserStatus(Request $request)
    {
        $params = $request->only(['id', 'status']);
        $ret = SysAdminUserFacade::saveAdminUser($params);
        return $this->jsonResponse('ok', $ret);
    }

    /****后台用户角色****/

    /**
     * 编辑/新增角色
     * */
    public function saveRole(Request $request)
    {
        $this->validate($request, [
            'role_name' => 'required|max:30'
        ], [
            'role_name.required' => '角色名不能为空！',
            'role_name.max' => '角色名不能超过30个字符长度'
        ]);
        $params = $request->only(['id', 'role_name']);
        $ret = SysRoleFacade::saveRole($params);
        return $this->jsonResponse('', $ret['data'], $ret['code']);
    }

    /**
     * 删除角色
     * */
    public function delRole($id)
    {
        $status = BaseModel::STATUS_DELETED;
        $id = SysRoleFacade::setStatus($id, $status);
        return $this->jsonResponse('ok', $id);
    }

    /**
     * 获取角色列表
     * */
    public function getRoleList(Request $request)
    {
        $params = $request->only(['page_size', 'page', 'keyword']);
        $results = SysRoleFacade::getRoleList($params);
        return $this->jsonResponse('ok', $results);
    }

    /**
     * 获取角色列表
     * */
    public function roleAuth(Request $request)
    {
        $params = $request->only(['role_id', 'menu_func_ids']);
        $this->validate($request, [
            'role_id' => 'required'
        ], [
            'role_id.required' => '角色id不能为空！'
        ]);
        $menuFuncIds = $params['menu_func_ids'];
        $roleId = $params['role_id'];
        $results = SysMenuFuncAuthFacade::saveMenuFuncAuth($menuFuncIds, $roleId);
        return $this->jsonResponse('ok', $results);
    }

    /****后台菜单****/

    /**
     * 编辑/新增菜单
     * */
    public function saveMenuFunc(Request $request)
    {
        $this->validate($request, [
            'menu_func_name' => 'required',
            'route_path' => 'required'
        ], [
            'menu_func_name.required' => '菜单/功能不能为空！',
            'route_path.required' => '路劲不能为空！'
        ]);
        $params = $request->only(['id', 'menu_func_name', 'p_id', 'type', 'route_path']);
        $ret = SysMenuFuncFacade::saveMenuFunc($params);
        return $this->jsonResponse('', $ret['data'], $ret['code']);
    }

    /**
     * 删除菜单
     * */
    public function delMenuFunc($id)
    {
        $status = BaseModel::STATUS_DELETED;
        $id = SysMenuFuncFacade::setStatus($id, $status);
        return $this->jsonResponse('ok', $id);
    }

    /**
     * 获取菜单列表
     * */
    public function getMenuFuncList(Request $request)
    {
        $params = $request->only(['page_size', 'page', 'keyword', 'type']);
        $results = SysMenuFuncFacade::getMenuFuncList($params);
        return $this->jsonResponse('ok', $results);
    }

    /**
     * 获取附件列表
     * */
    public function attachmentList(Request $request)
    {
        $pageNo = $request->input('page_no', 1);
        $pageSize = $request->input('page_size', 20);
        $keyword = $request->input('keyword', '');
        $type = $request->input('type', 0);
        $beginEndTime = $request->input('time', []);
        $month = $request->input('month', '');
        $params = [];
        $params['page'] = $pageNo;
        $params['page_size'] = $pageSize;
        $params['keyword'] = $keyword;
        $params['type'] = $type;
        $params['begin_end_time'] = $beginEndTime;
        $params['month'] = $month;
        $resultData = AttachmentFacade::getAttachmentList($params);
        return $this->jsonResponse(
            'ok',
            $resultData
        );

    }

    /**
     * @param file file 文件
     * @success number id ID
     * @success number company_id 公司id
     * @success number user_id 用户id
     * @success String file 文件地址
     * @success String ext 后缀
     * @success String des 文件描述
     * @paramExample
     * var settings = {
     * "async": true,
     * "crossDomain": true,
     * "url": "http://api.matchpages.com/api/upload_file",
     * "method": "POST",
     * "headers": {
     * "Content-Type": "application/x-www-form-urlencoded",
     * "X-Requested-With": "XMLHttpRequest",
     * "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vYXBpLmhvdXNlLmlqaWFvbC5jb20vYXBpL2xvZ2luIiwiaWF0IjoxNTUzOTI4Njg3LCJleHAiOjE1NTM5NDY2ODcsIm5iZiI6MTU1MzkyODY4NywianRpIjoiajFUOWxHR04xNVNFUDFtTiIsInN1YiI6MSwicHJ2IjoiMDMxY2JmNDYwMzJlYzhhMGFlNjRkZjQyNzcxMGJlNDllN2RiYmM1YyIsInVzZXJfbmFtZSI6IjEzNzc5OTQ4ODg4IiwidXNlcl9pZCI6MX0.XOZ672x3J8Lw65Mi7CiRsWv6gR-ObrrVUI16b_2DCzY",
     * "cache-control": "no-cache",
     * "Postman-Token": "0c533568-3c36-4387-82c1-46f2c8ef3c17"
     * },
     * "data": {"ext":"jpg,png,gif,jpeg","type":1,file: (binary)}
     * }
     *
     * $.ajax(settings).done(function (response) {
     * console.log(response);
     * });
     * @successExample
     * {"company_id":3,"user_id":3,"file":"http:\/\/oss.matchpages.cn\/matchpages\/common\/2019\/0909\/5d760e7a01387.png","first_letter":"X","name":"20190909163401862","des":"\u5c0fQ\u622a\u56fe-20190903114511.png","size":48368,"ext":"png","type":"1","update_time":"2019-09-09 16:34:02","create_time":"2019-09-09 16:34:02","id":3}
     * @author youwl
     * @header application/json 编码方式
     * @header XMLHttpRequest X-Requested-With 请求方式
     * @header token Authorization  请求方式
     * @api POST /upload_img 上传图片
     * @group 组件模块 组件管理
     */
    public function uploadImg(Request $request)
    {
        $data = $request->input('file', '');
        $fileExt = $request->input('fileExt', '');
        $selectFileName = $request->input('fileName', '');
        $this->validate($request, [
            'file' => 'required'
        ], [
            'file.required' => 'file不能为空'
        ]);
        $host= $request->root();
        $ret = AttachmentFacade::uploadImg($data, $fileExt, $selectFileName,$host);
        return $this->jsonResponse(
            'ok',
            $ret
        );
    }

    /**
     * @header application/json 编码方式
     * @header XMLHttpRequest X-Requested-With 请求方式
     * @header token Authorization  请求方式
     * @api POST /upload_file 上传文件
     * @group 组件模块 组件管理
     * */
    public function upload(Request $request)
    {
        set_time_limit(120);
        $ret= AttachmentFacade::upload($request);
        return $this->jsonResponse(
            'ok',
            $ret
        );
    }

    public function saveAttachment(Request $request)
    {
        $params = $request->all();
        $this->validate($request, [
            'id' => 'required'
        ], [
            'id.required' => 'id不能为空'
        ]);
        $ret = AttachmentFacade::saveAttachment($params);
        return $this->jsonResponse(
            'ok',
            $ret
        );
    }

    /**
     * 删除附件
     * */
    public function delAttachment(Request $request)
    {
        $id = $request->input('id', 0);
        $this->validate($request, [
            'id' => 'required'
        ], [
            'id.required' => 'id不能为空'
        ]);
        $ret = AttachmentFacade::delAttachment($id);
        return $this->jsonResponse(
            'ok',
            $ret
        );
    }

    /**
     * 批量删除附件
     * */
    public function batchDelAttachment(Request $request)
    {
        $id = $request->input('ids', []);
        $this->validate($request, [
            'ids' => 'required'
        ], [
            'ids.required' => 'id不能为空'
        ]);
        $ret = AttachmentFacade::delAttachment($id);
        return $this->jsonResponse(
            'ok',
            $ret
        );
    }

    public function heartbeat(Request $request)
    {
        $token = $request->header('token');
        $ret = $this->service->heartbeat($token);
        if(!empty($ret['token'])) {
            return $this->jsonResponse(
                'ok',
                1
            );
        } else {
            throw new ApiException(401);
        }
    }
}
