package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenCheckService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysLogininforService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
@Api("登录验证")
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;


    @Autowired
    private TokenService tokenService;

    @Autowired
    private TokenCheckService tokenCheckService;

    @Autowired
    private ISysLogininforService sysLogininforService;


    @Resource
    RedisCache redisCache;

    @Value("${ruoyi.downloadProductManualPath}")
    private String downloadProductManualPath;


    @Value("${ruoyi.productManualfileName}")
    private String productManualfileName;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @PostMapping("/isFirstLogin")
    @ApiOperation("用户首次登录")
    public AjaxResult isFirstLogin(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String username = loginBody.getUsername();

        List<SysLogininfor> loginRecords = sysLogininforService.selectLogininforList(new SysLogininfor(){{setUserName(username);}});
        if(loginRecords == null || loginRecords.isEmpty()){
            return AjaxResult.success("用户首次登录");
        }else {
            return AjaxResult.success("用户已有登录记录");
        }
    }


//    @PostMapping("/loginBi")
    @ApiOperation("登录BI")
    public AjaxResult loginBi(HttpServletRequest request, HttpServletResponse response)
    {
        AjaxResult ajax = AjaxResult.success();
        LoginUser biLoginUser = tokenService.getBiLoginUser(request);
        if(StringUtils.isNotNull(biLoginUser)) {
            ajax.put(Constants.JWT_USERID2, biLoginUser.getUserId().toString());
            ajax.put(Constants.RESULT,"success");
        }else {
            ajax.put(Constants.RESULT, "error");
        }
        return ajax;
    }

    @PostMapping("/loginBi")
    @ApiOperation("登录BI")
    public JSONObject loginBI(@RequestParam(value = "token") String token)
    {
        JSONObject result = new JSONObject();
        try {
            result = tokenCheckService.doPost(token);     //验证token
        }catch (ServletException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return result;

    }

    @GetMapping("/getBi")
    @ApiOperation("获取BIurl")
    public List<String> biUrl()
    {
        List<String> biUrl = tokenCheckService.biUrl();
        return biUrl;
    }


    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @ApiOperation("获取路由信息")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @PostMapping("/countMenu")
    @ApiOperation("统计菜单访问")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuId", value = "菜单id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "menuName", value = "菜单名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "component", value = "菜单路由", dataType = "String", dataTypeClass = String.class)
    })
    public AjaxResult countMenu(Long menuId,String menuName,String component)
    {
        return AjaxResult.success(menuService.insertCount(menuId,menuName,component));
    }

    @GetMapping("/downloadProductManual")
    @ApiOperation("下载产品手册")
    public ResponseEntity<?> downloadProductManual() {
//        String directoryPath = "C:\\Users\\ZJRCU\\Downloads";
//        String fileName = "product_manual_szzh.docx";
        Path filePath = Paths.get(downloadProductManualPath, productManualfileName);

        // 验证文件是否存在且是.doc文件
        if (!Files.exists(filePath) || Files.isDirectory(filePath)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件不存在");
        }

        List<SysDictData> sysDictTypeArrayList = new ArrayList<SysDictData>(redisCache.getCacheObject("sys_dict:product_manual_szzh"));
        String docName = "数智支行操作手册.docx";
        if(sysDictTypeArrayList.size() > 0){
            docName = sysDictTypeArrayList.get(0).getDictLabel();
        }
        try {
            // 设置响应头
            ContentDisposition contentDisposition = ContentDisposition
                    .attachment()
                    .filename(docName)
                    .build();

            // 打开文件输入流
            InputStream inputStream = Files.newInputStream(filePath);

            return ResponseEntity.ok()
                    .headers(headers -> headers.setContentDisposition(contentDisposition))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(Files.size(filePath))
                    .body(new InputStreamResource(inputStream));
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("下载文件时出错: " + e.getMessage());
        }
    }




}
