package com.ruoyi.web.controller.back;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ShopUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.IShopUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户管理Controller
 * 
 * @author ruoyi
 * @date 2025-07-15
 */
@RestController
@RequestMapping("/back/user")
public class ShopUserController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ShopUserController.class);
    
    @Autowired
    private IShopUserService shopUserService;

    /**
     * 查询用户管理列表
     */
   // @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(ShopUser shopUser)
    {
        startPage();
        List<ShopUser> list = shopUserService.selectShopUserList(shopUser);
        return getDataTable(list);
    }

    /**
     * 导出用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShopUser shopUser)
    {
        List<ShopUser> list = shopUserService.selectShopUserList(shopUser);
        ExcelUtil<ShopUser> util = new ExcelUtil<ShopUser>(ShopUser.class);
        util.exportExcel(response, list, "用户管理数据");
    }

    /**
     * 获取用户管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(shopUserService.selectShopUserById(id));
    }

    /**
     * 新增用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShopUser shopUser)
    {
        return toAjax(shopUserService.insertShopUser(shopUser));
    }

    /**
     * 修改用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShopUser shopUser)
    {
        return toAjax(shopUserService.updateShopUser(shopUser));
    }

    /**
     * 删除用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(shopUserService.deleteShopUserByIds(ids));
    }
    
    /**
     * 更新用户在线时长
     * 客户端每5分钟调用一次，更新数据库在线时长字段online
     */
    @GetMapping("/updateOnlineTime/{online}")
    public AjaxResult updateOnlineTime(@PathVariable("online") String online)
    {
        try {
            // 获取当前登录用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null || loginUser.getUserId() == null) {
                return AjaxResult.error("用户未登录或用户ID为空");
            }
            ShopUser shopUser =  loginUser.getShopUser();

            // 设置在线时长
            shopUser.setOnline(online);

            // 记录用户在线时长更新日志
            log.info("更新用户[{}]在线时长: {}", shopUser.getUserId(), online);

            // 调用服务更新用户在线时长
            int rows = shopUserService.updateUserOnlineTime(shopUser);

            if (rows > 0) {
                return AjaxResult.success("更新在线时长成功");
            } else {
                return AjaxResult.error("更新在线时长失败，用户可能不存在");
            }
        } catch (Exception e) {
            log.error("更新用户在线时长异常", e);
            return AjaxResult.error("更新在线时长异常: " + e.getMessage());
        }
    }
    
    /**
     * 更新指定用户的在线时长（管理员使用）
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @PostMapping("/updateUserOnlineTime")
    public AjaxResult updateUserOnlineTime(@RequestBody ShopUser shopUser)
    {
        if (shopUser == null || shopUser.getUserId() == null) {
            return AjaxResult.error("用户ID不能为空");
        }
        
        if (shopUser.getOnline() == null) {
            return AjaxResult.error("在线时长不能为空");
        }
        
        try {
            // 记录用户在线时长更新日志
            log.info("管理员更新用户[{}]在线时长: {}", shopUser.getUserId(), shopUser.getOnline());
            
            // 调用服务更新用户在线时长
            int rows = shopUserService.updateUserOnlineTime(shopUser);
            
            if (rows > 0) {
                return AjaxResult.success("更新在线时长成功");
            } else {
                return AjaxResult.error("更新在线时长失败，用户可能不存在");
            }
        } catch (Exception e) {
            log.error("更新用户[{}]在线时长异常", shopUser.getUserId(), e);
            return AjaxResult.error("更新在线时长异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户标签
     * 根据用户历史记录中的音乐标签来返回用户的标签列表
     */
    @GetMapping("/tags/{userId}")
    public AjaxResult getUserTags(@PathVariable("userId") String userId)
    {
        if (userId == null || userId.isEmpty()) {
            return AjaxResult.error("用户ID不能为空");
        }
        
        try {
            // 调用服务获取用户标签
            String tags = shopUserService.getUserTags(userId);
            
            if (tags != null && !tags.isEmpty()) {
                return AjaxResult.success("获取用户标签成功", tags);
            } else {
                return AjaxResult.success("用户暂无标签", "");
            }
        } catch (Exception e) {
            log.error("获取用户[{}]标签异常", userId, e);
            return AjaxResult.error("获取用户标签异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录用户的标签
     */
    @GetMapping("/myTags")
    public AjaxResult getMyTags()
    {
        try {
            // 获取当前登录用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null || loginUser.getUserId() == null) {
                return AjaxResult.error("用户未登录或用户ID为空");
            }
            ShopUser shopUser = loginUser.getShopUser();
            
            // 调用服务获取用户标签
            String tags = shopUserService.getUserTags(shopUser.getUserId().toString());
            
            if (tags != null && !tags.isEmpty()) {
                return AjaxResult.success("获取用户标签成功", tags);
            } else {
                return AjaxResult.success("用户暂无标签", "");
            }
        } catch (Exception e) {
            log.error("获取当前用户标签异常", e);
            return AjaxResult.error("获取用户标签异常: " + e.getMessage());
        }
    }
}
