package com.ylx.web.controller.massage;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ylx.common.core.controller.BaseController;
import com.ylx.common.core.domain.R;
import com.ylx.common.core.domain.model.WxLoginUser;
import com.ylx.common.utils.SecurityUtils;
import com.ylx.massage.domain.TComment;
import com.ylx.massage.domain.TCommentUser;
import com.ylx.massage.service.TCommentUserAuditService;
import com.ylx.massage.service.TCommentUserService;
import com.ylx.system.domain.vo.ReviewUserCommentsDto;
import com.ylx.system.domain.vo.BatchAuditCommentsDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 用户评论表(TCommentUser)表控制层
 *
 * @author makejava
 * @since 2024-08-08 10:32:07
 */
@RestController
@RequestMapping("tCommentUser")
@Api(tags = {"用户评论"})
public class TCommentUserController extends BaseController {

    @Resource
    private TCommentUserService tCommentUserService;

    @Resource
    private TCommentUserAuditService tCommentUserAuditService;

    /**
     * 分页查询所有用户评论数据
     *
     * @param current
     * @param size
     * @param tCommentUser
     * @return R
     */
    @GetMapping("selectAll")
    @ApiOperation("分页查询所有评论数据")
    public R selectAll(@RequestParam Integer current, @RequestParam Integer size, TCommentUser tCommentUser) {
        try {
            PageHelper.startPage(current, size);
            List<TCommentUser> tCommentUsers = tCommentUserService.selectAll(tCommentUser);
            PageInfo<TCommentUser> pageInfo = new PageInfo<>(tCommentUsers);
            return R.ok(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过主键查询单条评论数据
     *
     * @param id 主键
     * @return R
     */
    @GetMapping("{id}")
    @ApiOperation("通过主键查询单条评论数据")
    public R selectOne(@PathVariable Serializable id) {
        return R.ok(this.tCommentUserService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param tCommentUser 实体对象
     * @return 新增结果
     */
    @PostMapping("add")
    @ApiOperation("新增数据")
    public R insert(@RequestBody TCommentUser tCommentUser) {
        tCommentUser.setCommentTime(new Date());
        return R.ok(this.tCommentUserService.save(tCommentUser));
    }


    /**
     * 新增用户评论（用户端）
     *
     * @param commentUser
     * @return R
     */
    @ApiOperation("新增用户评论")
    @RequestMapping(value = "wx/add", method = RequestMethod.POST)
    public R add(@RequestBody TCommentUser commentUser) {
        try {
            WxLoginUser wxLoginUser = getWxLoginUser();
            return R.ok(tCommentUserService.saveComment(commentUser, wxLoginUser));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改用户评论数据
     *
     * @param tCommentUser 实体对象
     * @return 修改结果
     */
    @PostMapping("update")
    @ApiOperation("修改用户评论数据")
    public R update(@RequestBody TCommentUser tCommentUser) {
        return R.ok(this.tCommentUserService.updateById(tCommentUser));
    }

    /**
     * 删除用户评论数据
     *
     * @param id 主键
     * @return R 删除结果
     */
    @DeleteMapping("delete")
    @ApiOperation("删除用户评论数据")
    public R delete(@RequestParam String id) {
        return R.ok(this.tCommentUserService.removeById(id));
    }

    /**
     * 审核用户评论
     * <p>
     * 管理员审核用户提交的评论，可以选择通过或拒绝。
     * 审核通过后，评论状态更新为"通过"；
     * 审核拒绝时，需要填写拒绝理由，评论状态更新为"拒绝"。
     * </p>
     *
     * @param commentId 评论ID，必填
     * @param auditStatus 审核状态：1-通过，2-拒绝，必填
     * @param auditReason 审核原因/拒绝理由，审核拒绝时必填
     * @return R 操作结果
     */
    @PostMapping("audit")
    @ApiOperation("审核用户评论")
    public R auditComment(@RequestBody ReviewUserCommentsDto reviewUserCommentsDto) {
        try {
            logger.info("reviewUserCommentsDto参数的值：{}", JSON.toJSONString(reviewUserCommentsDto));
            // 获取当前登录用户信息
            String auditorId = SecurityUtils.getUserId().toString();
            String auditorName = SecurityUtils.getUsername();

            // 调用审核服务
            Boolean result = tCommentUserAuditService.auditComment(
                    reviewUserCommentsDto.getCommentId(),
                    reviewUserCommentsDto.getAuditStatus(),
                    reviewUserCommentsDto.getAuditReason(),
                    auditorId,
                    auditorName
            );
            if (result) {
                return R.ok("审核成功");
            } else {
                return R.fail("审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 批量审核用户评论
     * <p>
     * 管理员批量审核多条用户评论，支持统一通过或拒绝。
     * 审核通过后，所有评论状态更新为"通过"；
     * 审核拒绝时，需要填写拒绝理由，所有评论状态更新为"拒绝"。
     * 返回审核结果统计，包括成功数量、失败数量和失败详情。
     * </p>
     *
     * @param batchAuditCommentsDto 批量审核请求参数
     * @return R 操作结果
     */
    @PostMapping("batchAudit")
    @ApiOperation("批量审核用户评论")
    public R batchAuditComments(@RequestBody BatchAuditCommentsDto batchAuditCommentsDto) {
        try {
            logger.info("batchAuditCommentsDto参数的值：{}", JSON.toJSONString(batchAuditCommentsDto));

            // 获取当前登录用户信息
            String auditorId = SecurityUtils.getUserId().toString();
            String auditorName = SecurityUtils.getUsername();

            // 调用批量审核服务
            TCommentUserAuditService.BatchAuditResult result = tCommentUserAuditService.batchAuditComments(
                    batchAuditCommentsDto.getCommentIds(),
                    batchAuditCommentsDto.getAuditStatus(),
                    batchAuditCommentsDto.getAuditReason(),
                    auditorId,
                    auditorName
            );

            // 构建响应数据
            java.util.Map<String, Object> responseData = new java.util.HashMap<>();
            responseData.put("successCount", result.getSuccessCount());
            responseData.put("failCount", result.getFailCount());
            responseData.put("totalCount", result.getTotalCount());
            responseData.put("allSuccess", result.isAllSuccess());

            // 如果有失败的，添加失败详情
            if (!result.isAllSuccess() && result.getFailDetails() != null && !result.getFailDetails().isEmpty()) {
                responseData.put("failDetails", result.getFailDetails());
            }

            // 构建响应消息
            String message = String.format("批量审核完成，成功：%d条，失败：%d条", result.getSuccessCount(), result.getFailCount());
            // 返回结果
            return R.ok(responseData, message);
        } catch (Exception e) {
            logger.error("批量审核失败", e);
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }
}

