package com.qmth.distributed.print.api.client;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.core.enums.Platform;
import com.qmth.distributed.print.business.bean.params.ClientLoginParam;
import com.qmth.distributed.print.business.service.ClientService;
import com.qmth.teachcloud.common.bean.auth.ExpireTimeBean;
import com.qmth.teachcloud.common.bean.result.LoginClientResult;
import com.qmth.teachcloud.common.bean.result.LoginResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicSchool;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.entity.TBSession;
import com.qmth.teachcloud.common.enums.AppSourceEnum;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.common.enums.RoleTypeEnum;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.service.SysUserService;
import com.qmth.teachcloud.common.service.TeachcloudCommonService;
import com.qmth.teachcloud.common.util.*;
import com.qmth.teachcloud.mark.bean.sys.ActiveTimeVo;
import com.qmth.teachcloud.mark.bean.sys.ApiStatusVo;
import io.swagger.annotations.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 扫描系统相关 前端控制器
 * </p>
 *
 * @author xf
 * @since 2023-09-22
 */
@Api(tags = "扫描-登录、登出、服务器时间")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_SCAN)
public class ScanController {

    @Resource
    private TeachcloudCommonService teachcloudCommonService;
    @Resource
    private CommonCacheService commonCacheService;
    @Resource
    private ClientService clientService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 登录
     *
     * @param login 登录参数
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    @ApiResponses({@ApiResponse(code = 200, message = "用户信息", response = LoginResult.class)})
    @Aac(auth = false)
    public Result login(@ApiParam(value = "用户信息", required = true) @Valid @RequestBody ClientLoginParam login, BindingResult bindingResult) throws NoSuchAlgorithmException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        BasicSchool basicSchool = commonCacheService.schoolCache(login.getSchoolCode());
        if (Objects.isNull(basicSchool)) {
            throw ExceptionResultEnum.SCHOOL_NO_DATA.exception();
        }
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUser::getSchoolId, basicSchool.getId()).eq(SysUser::getLoginName, login.getLoginName());
        SysUser sysUser = sysUserService.getOne(wrapper);
        // 用户不存在或密码错误
        if (Objects.isNull(sysUser) || !Objects.equals(sysUser.getPassword(), login.getPassword())) {
            throw ExceptionResultEnum.USER_NO_DATA.exception();
        }
        // 是否有打印端和扫描端权限
        Set<String> roles = clientService.getRoleByUserId(sysUser.getId());
        if(CollectionUtils.isEmpty(roles) || (!roles.contains(RoleTypeEnum.PRINT.name()) && !roles.contains(RoleTypeEnum.SCANNER.name()))){
            throw ExceptionResultEnum.ERROR.exception("没有客户端登录权限");
        }

        LoginResult loginResult = teachcloudCommonService.login(login.getPassword(), sysUser, AppSourceEnum.SYSTEM);
        LoginClientResult loginClientResult = new LoginClientResult(sysUser, loginResult);
        loginClientResult.setRoleList(roles);
        loginClientResult.setCanAddCard(sysUser.getAllowManualCard());
        return ResultUtil.ok(loginClientResult);
    }

    @Aac(auth = false)
    @ApiOperation(value = "服务端状态")
    @PostMapping("server/status")
    public Result status(HttpServletRequest request) {
        ApiStatusVo vo = new ApiStatusVo();
//        vo.setFileUriPrefix(fileUriPrefix);
        vo.setVersion(SystemConstant.VERSION_VALUE);
        vo.setTime(System.currentTimeMillis());
        return ResultUtil.ok(vo);
    }

    @ApiOperation(value = "心跳接口")
    @PostMapping("server/heartbeat")
    public Result heartbeat() {
        Platform platform = ServletUtil.getRequestPlatform();
        ExpireTimeBean expireTime = AuthUtil.getExpireTime(platform);
        TBSession ts = (TBSession) ServletUtil.getRequestSession();
        redisUtil.expire(ts.getId(), expireTime.getExpireSeconds(), TimeUnit.SECONDS);
        ActiveTimeVo vo = new ActiveTimeVo();
        vo.setActiveTime(System.currentTimeMillis());
        return ResultUtil.ok(vo);
    }
}
