package com.fs.user.controller;

import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.utils.StringUtils;
import com.fs.his.domain.FsUser;
import com.fs.his.domain.FsUserIntegralLogs;
import com.fs.his.mapper.FsUserIntegralLogsMapper;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.service.IFsUserIntegralLogsService;
import com.fs.his.service.IFsUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 添加积分参数
 */
class AddIntegralParam {
    private Long userId;
    private Integer logType;
    private Long integral;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Integer getLogType() {
        return logType;
    }

    public void setLogType(Integer logType) {
        this.logType = logType;
    }

    public Long getIntegral() {
        return integral;
    }

    public void setIntegral(Long integral) {
        this.integral = integral;
    }
}

/**
 * 用户积分管理Controller 提供给卓美 完成直播积分发放
 *
 * @author fs
 * @date 2025-01-01
 */
@Api("用户积分管理")
@RestController
@RequestMapping("/user/integral")
public class FsUserIntegralController {

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsUserIntegralLogsService integralLogsService;

    @Autowired
    private FsUserMapper userMapper;

    @Autowired
    private FsUserIntegralLogsMapper integralLogsMapper;

    /**
     * 查询用户列表（支持手机号和昵称筛选）
     */
    @ApiOperation("查询用户列表")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String phone,
                              @RequestParam(required = false) String nickName,
                              @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        
        // 构建查询条件
        FsUser queryUser = new FsUser();
        if (StringUtils.isNotEmpty(phone)) {
            queryUser.setPhone(phone);
        }
        if (StringUtils.isNotEmpty(nickName)) {
            queryUser.setNickName(nickName);
            queryUser.setNickname(nickName);
        }
        
        // 查询用户列表（只返回需要的字段）
        List<FsUser> userList = userMapper.selectFsUserListForIntegral(queryUser);
        
        PageInfo<FsUser> pageInfo = new PageInfo<>(userList);
        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setCode(200);
        dataTable.setMsg("查询成功");
        dataTable.setRows(pageInfo.getList());
        dataTable.setTotal(pageInfo.getTotal());
        return dataTable;
    }

    /**
     * 查询用户积分明细
     */
    @ApiOperation("查询用户积分明细")
    @GetMapping("/logs/{userId}")
    public R getIntegralLogs(@PathVariable Long userId,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(required = false) Integer logType) {
        PageHelper.startPage(pageNum, pageSize);
        FsUserIntegralLogs queryLogs = new FsUserIntegralLogs();
        queryLogs.setUserId(userId);
        if (logType != null) {
            queryLogs.setLogType(logType);
        }
        // 按创建时间倒序查询（Mapper XML 中已添加排序）
        List<FsUserIntegralLogs> logsList = integralLogsService.selectFsUserIntegralLogsList(queryLogs);
        PageInfo<FsUserIntegralLogs> pageInfo = new PageInfo<>(logsList);
        return R.ok().put("data", pageInfo.getList()).put("total", pageInfo.getTotal());
    }

    /**
     * 添加积分
     */
    @ApiOperation("添加积分")
    @PostMapping("/add")
    public R addIntegral(@RequestBody AddIntegralParam param) {
        Long userId = param.getUserId();
        Integer logType = param.getLogType();
        Long integral = param.getIntegral();
        // 查询用户信息
        FsUser user = userService.selectFsUserByUserId(userId);
        if (user == null) {
            return R.error("用户不存在");
        }

        // 查询用户最新的积分记录
        FsUserIntegralLogs latestLog = integralLogsMapper.selectLatestIntegralLogByUserId(userId);
        
        // 计算新的积分余额
        Long currentIntegral = user.getIntegral() != null ? user.getIntegral() : 0L;
        Long newIntegral = currentIntegral + integral;
        
        // 创建时间默认往后移动2个小时，使用整点的创建时间和更新时间
        Date now = new Date();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault());
        // 往后移动2小时
        localDateTime = localDateTime.plusHours(2);
        // 设置为整点（分钟和秒都设为0）
        localDateTime = localDateTime.withMinute(0).withSecond(0).withNano(0);
        Date createTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        Date updateTime = createTime;

        // 更新用户积分
        user.setIntegral(newIntegral);

        userService.increaseIntegral(Collections.singletonList(user.getUserId()),integral);

        // 创建积分记录
        FsUserIntegralLogs integralLogs = new FsUserIntegralLogs();
        integralLogs.setUserId(userId);
        integralLogs.setLogType(logType);
        integralLogs.setIntegral(integral);
        integralLogs.setBalance(newIntegral);
        integralLogs.setCreateTime(createTime);
        integralLogs.setUpdateTime(updateTime);
        integralLogsService.insertFsUserIntegralLogs(integralLogs);

        return R.ok("添加积分成功");
    }
}
