package com.usky.system.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.BeanMapperUtils;
import com.usky.common.core.util.JwtUtils;
import com.usky.common.core.util.StringUtils;
import com.usky.common.security.auth.AuthUtil;
import com.usky.common.security.service.TokenService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.*;
import com.usky.system.mapper.SysUserMapper;
import com.usky.system.model.LoginUser;
import com.usky.system.service.*;
import com.usky.system.service.util.IpUtils;
import com.usky.system.service.vo.LoginBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private SysPersonService sysPersonService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private MceMbuserService mceMbuserService;

    @Autowired
    private MceSettingService mceSettingService;

    @Autowired
    private SysUserTenantService sysUserTenantService;

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    @PostMapping("login")
    public ApiResult<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(), form.getTenantId());
        // 获取登录token
        return ApiResult.success(tokenService.createToken(userInfo,""));
    }


    @PostMapping("appLogin")
    public ApiResult<?> appLogin(@RequestBody LoginBody form) {
//        String phone = null;
        // 用户登录
        SysUser userInfo = sysLoginService.appLogin(form.getUsername(), form.getPassword(), form.getTenantId(),
                form.getPhone(), form.getVerify(), form.getMethod());
        Integer isDefaulTenant = sysUserTenantService.getIsDefaultByUser(userInfo.getUserId());
        LoginUser sysUser = new LoginUser();
        SysUserVO sysUserVO = BeanMapperUtils.map(userInfo, SysUserVO.class);
        if (null != form.getMethod() && form.getMethod().equals("switch")){
            sysUserVO.setTenantId(userInfo.getTenantId());
        }else {
            sysUserVO.setTenantId(isDefaulTenant);
        }
        sysUser.setSysUser(sysUserVO);
        Set<String> rolePermission = permissionService.getRolePermission(userInfo.getUserId());
        sysUser.setRoles(rolePermission);
        SysPerson sysPerson = sysPersonService.getsysPerson(userInfo.getUserId());
        sysUser.setSysPerson(sysPerson);
        String openId = form.getOpenId();

        if(StringUtils.isNotEmpty(form.getType())){
            Long userId = userInfo.getUserId();
            int count = userMapper.selectMbUserCount(userId);
            String type = form.getType();
            if(type.equals("app")){   //app登录
                //插入或更新mce_mbuser消息中心_移动端注册表表记录cids，通过userId去这个表中查询，有记录则更新对应的cids，没有就插入
                String cids = form.getCids();
                if(count > 0){
                    userMapper.updateMbUser(null,null,userId,cids, userInfo.getUserName());
                }else{
                    userMapper.insertMbUser(userId,cids, userInfo.getUserName());
                }
            }else if(type.equals("wx")){
                String phone = form.getPhone();
                if(count > 0){
                    userMapper.updateMbUser(phone,openId,userId,null, userInfo.getUserName());
                }else {
                    MceMbuser one = new MceMbuser();
                    one.setPhone(phone);
                    if((openId != null) && (StringUtils.isNotBlank(openId))){
                        one.setOpenid(openId);
                    }
                    one.setCreateBy(userInfo.getUserName());
                    one.setUserId(userInfo.getUserId());
                    one.setCreateTime(LocalDateTime.now());

                    if(!mceMbuserService.save(one)){
                        throw new BusinessException("注册失败，重新注册");
                    }
                }
            }
        }

        LambdaQueryWrapper<MceSetting> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MceSetting::getCreateBy,userInfo.getUserName()).eq(MceSetting::getTenantId,userInfo.getTenantId());
        List<MceSetting> list = mceSettingService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            //新增消息设置记录
            MceSetting mceSetting = new MceSetting();
            mceSetting.setAppMode("{\"1\":true,\"2\":true,\"3\":true,\"4\":true,\"5\":true}");
            mceSetting.setPcMode("{\"1\":true,\"2\":true,\"3\":true,\"4\":true,\"5\":true}");
            mceSetting.setWcMode("{\"1\":true,\"2\":true,\"3\":true,\"4\":true,\"5\":true}");

            mceSetting.setCreateBy(userInfo.getUserName());
            mceSetting.setCreateTime(LocalDateTime.now());
            mceSetting.setTenantId(userInfo.getTenantId());
            long longValue = userInfo.getDeptId();
            Integer intValue = (int) longValue;
            mceSetting.setDeptId(intValue);
            mceSettingService.save(mceSetting);
        }



        // 获取登录token
        return ApiResult.success(tokenService.createToken(sysUser,openId));
    }

    @PostMapping("getIp")
    public ApiResult<?> getIp() {
        String clientIp = IpUtils.getClientIp(request);
        return ApiResult.success(clientIp);
    }


    //手机端发送扫码信息，二维码编号，用户名信息
    @GetMapping("getQrCodeResult")
    public ApiResult<String> getQrCodeResult(@RequestParam String qrCode){
        String qrCodeResult = sysLoginService.getQrCodeResult(qrCode);
        return ApiResult.success(qrCodeResult);
    }

    //PC通过二维码编号获取用户登录授权



//    @PostMapping("login1")
//    public ApiResult<?> login1(@RequestBody LoginBody form) {
//        // 用户登录
//        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword(), form.getTenantId());
//        // 获取登录token
//        return ApiResult.success(tokenService.createToken(userInfo));
//    }

    @DeleteMapping("logout")
    public ApiResult<?> logout(HttpServletRequest request,@RequestParam(value = "openId",required = false) String openId) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token,openId);
            // 记录用户退出日志
            sysLoginService.logout(SecurityUtils.getTenantId(),username);
        }
        return ApiResult.success();
    }

    @PostMapping("refresh")
    public ApiResult<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return ApiResult.success();
        }
        return ApiResult.success();
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public ApiResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", sysUserService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ApiResult.success(ajax);
    }


//    @PostMapping("register")
//    public ApiResult<?> register(@RequestBody RegisterBody registerBody)
//    {
//        // 用户注册
//        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
//        return ApiResult.success();
//    }

    @GetMapping("/qrCodeSend")
    public ApiResult<Void> qrCodeSend(@RequestParam String userName, @RequestParam String qrCode,@RequestParam Integer tenantId) {
        sysLoginService.qrCodeSend(userName,qrCode,tenantId);
        return ApiResult.success();
    }
}
