package com.ruoyi.predict.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.AddressUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.common.core.domain.entity.SysLogininfor;
import com.ruoyi.system.service.ISysLogininforService;
import com.ruoyi.system.service.ISysUserService;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author hlf
 * @date 2022/3/10 10:41
 * 文件说明：用户统计
 */
@Api(value = "用户统计Controller", tags = {"用户统计操作接口"})
@Controller
@RequestMapping("/predict/api/us")
public class UserStatisticsController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysLogininforService sysLogininforService;

    @Autowired
    private SysPasswordService passwordService;

    @ApiOperation("用户统计列表")
    @PostMapping("/userList")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名称"),
            @ApiImplicitParam(name = "loginNumber", value = "登录次数"),
            @ApiImplicitParam(name = "sysLogininfors", value = "登录信息"),
            @ApiImplicitParam(name = "loginDuration", value = "登录时长"),
    })
    public TableDataInfo userList(SysUser user) {
        startPage();
        List<SysUser> list = sysUserService.selectUserList1(user);
        for (SysUser sysUser : list) {
            List<SysLogininfor> sysLogininforList = sysLogininforService.selectLogininfors(sysUser.getLoginName(), "登录成功");
            if (sysLogininforList.size() > 0) {
                for (SysLogininfor sysLogininfor : sysLogininforList) {
                    List<SysLogininfor> logininforList = sysLogininforService.selectLogininfor(sysUser.getLoginName(), sysLogininfor.getIdentifier(), "退出登录");
                    if (logininforList.size() > 0) {
                        sysLogininfor.setLoginDuration((logininforList.get(0).getLoginTime().getTime() - sysLogininfor.getLoginTime().getTime()) / 1000);
                    }
                }
            }
            sysUser.setSysLogininfors(sysLogininforList);
        }
        return getDataTable(list);
    }

    @ApiOperation("插入登录信息")
    @PostMapping("/insertLoginInformation")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "登录名称", required = true),
            @ApiImplicitParam(name = "identifier", value = "识别码"),
    })
    public AjaxResult insertLoginInformation(SysLogininfor logininfor) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = ShiroUtils.getIp();
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        String address = AddressUtils.getRealAddressByIP(ip);
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setStatus("0");
        logininfor.setMsg("登录成功");
        long identifier = IdUtil.getSnowflake(1, 1).nextId();
        logininfor.setIdentifier(identifier);
        sysLogininforService.insertLogininfor(logininfor);
        SysUser sysUser = sysUserService.selectUserByLoginName(logininfor.getLoginName());
        sysUser.setLoginNumber(sysUser.getLoginNumber() + 1);
        sysUserService.updateUserInfo(sysUser);
        JSONObject json = new JSONObject();
        json.put("identifier", Convert.toStr(identifier));
        return AjaxResult.success(json);
    }

    @ApiOperation("插入登出信息")
    @PostMapping("/insertLogoutInformation")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "登录名称", required = true),
            @ApiImplicitParam(name = "identifier", value = "识别码", required = true),
    })
    public AjaxResult insertLogoutInformation(SysLogininfor logininfor) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = ShiroUtils.getIp();
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        String address = AddressUtils.getRealAddressByIP(ip);
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setStatus("0");
        logininfor.setMsg("退出登录");
        sysLogininforService.insertLogininfor(logininfor);
        return AjaxResult.success();
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/modifyUserPassword")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true),
    })
    public AjaxResult modifyUserPassword(String username, String password)
    {
        SysUser sysUser = sysUserService.selectUserByUsername(username);
        sysUser.setSalt(ShiroUtils.randomSalt());
        sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), password, sysUser.getSalt()));
        sysUserService.updateUserInfo(sysUser);
        return AjaxResult.success();
    }
}
