package com.ruoyi.web.controller.ai;

import cn.hutool.core.util.NumberUtil;
import com.ruoyi.ai.service.IAiUserService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.BalanceChangerConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AiUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * ai-用户信息Controller
 *
 * @author shi
 * @date 2025-11-12
 */
@Api(tags = "ai-用户信息")
@RestController
@RequestMapping("/ai/user")
public class AiUserController extends BaseController {
    @Autowired
    private IAiUserService aiUserService;


    /**
     * 查询ai-用户信息列表
     */
    @ApiOperation("查询ai-用户信息列表")
    @PreAuthorize("@ss.hasPermi('ai:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(AiUser aiUser) {
        startPage();
        List<AiUser> list = aiUserService.selectAiUserList(aiUser);
        return getDataTable(list);
    }

    /**
     * 导出ai-用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('ai:user:export')")
    @Log(title = "ai-用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AiUser aiUser) {
        List<AiUser> list = aiUserService.selectAiUserList(aiUser);
        ExcelUtil<AiUser> util = new ExcelUtil<AiUser>(AiUser.class);
        util.exportExcel(response, list, "ai-用户信息数据");
    }

    /**
     * 获取ai-用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('ai:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(aiUserService.selectAiUserById(id));
    }


    /**
     * 新增ai-用户信息
     */
    @ApiOperation("新增ai-用户信息")
    @PreAuthorize("@ss.hasPermi('ai:user:add')")
    @Log(title = "ai-用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AiUser aiUser) {
        return toAjax(aiUserService.insertAiUser(aiUser));
    }

    /**
     * 修改ai-用户信息
     */
    @ApiOperation("修改ai-用户信息")
    @PreAuthorize("@ss.hasPermi('ai:user:edit')")
    @Log(title = "ai-用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AiUser aiUser) {
        return toAjax(aiUserService.updateAiUser(aiUser));
    }

    /**
     * 分配归属部门（deptId 为空表示不归属任何部门）
     */
    @ApiOperation("分配AI用户归属部门")
    @PreAuthorize("@ss.hasPermi('ai:user:edit')")
    @Log(title = "ai-用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/dept")
    public AjaxResult assignDept(@RequestBody AiUser aiUser) {
        if (aiUser.getId() == null) {
            return error("用户主键不能为空");
        }
        return toAjax(aiUserService.updateAiUserDept(aiUser.getId(), aiUser.getDeptId()));
    }

    /**
     * 状态修改
     */
    @ApiOperation("修改ai-用户状态")
    @PreAuthorize("@ss.hasPermi('ai:user:edit')")
    @Log(title = "ai-用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody AiUser aiUser) {
        aiUser.setUpdateBy(getUsername());
        return toAjax(aiUserService.updateUserStatus(aiUser));
    }

    /**
     * 状态修改
     */
    @ApiOperation("修改ai-用户状态")
    @PreAuthorize("@ss.hasPermi('ai:user:edit')")
    @Log(title = "ai-用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/changeBalance")
    public AjaxResult changeBalance(@RequestBody AiUser aiUser) {
        aiUser.setUpdateBy(getUsername());
        // 获取原余额
        AiUser u = aiUserService.selectAiUserById(aiUser.getId());
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        String dateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String orderNo = dateTime + uuid;
        // 计算变更余额
        BigDecimal amount = NumberUtil.sub(aiUser.getBalance(), u.getBalance());
        aiUserService.addUserBalance(orderNo, aiUser.getId(), amount, BalanceChangerConstants.SYSTEM_OPERATION);
        return toAjax(1);
    }

    /**
     * 状态密码
     */
    @PreAuthorize("@ss.hasPermi('ai:user:edit')")
    @Log(title = "ai-用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody AiUser aiUser) {
        return toAjax(aiUserService.updatePassword(aiUser));
    }

    /**
     * 删除ai-用户信息
     */
    @ApiOperation("删除ai-用户信息")
    @PreAuthorize("@ss.hasPermi('ai:user:remove')")
    @Log(title = "ai-用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(aiUserService.deleteAiUserByIds(ids));
    }


//    @GetMapping("/addUserBalance")
//    public AjaxResult addUserBalance(BigDecimal amount) {
//        aiUserService.addUserBalance(SecurityUtils.getAiUserId(), amount, BalanceChangerConstants.RECHARGE);
//        return AjaxResult.success();
//    }

}
