package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.BarPerformance;
import shop.alien.entity.store.dto.BarPerformanceOnlineStatusDto;
import shop.alien.entity.store.vo.BarPerformanceDetailVo;
import shop.alien.store.service.BarPerformanceService;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 酒吧演出Controller
 * 提供酒吧演出的CRUD、审核、上下线等RESTful API接口
 *
 * @author assistant
 * @since 2025-12-17
 */
@Slf4j
@Api(tags = {"商户端-酒吧演出"})
@CrossOrigin
@RestController
@RequestMapping("/store/bar/performance")
@RequiredArgsConstructor
public class BarPerformanceController {

    private final BarPerformanceService barPerformanceService;

    /**
     * 获取酒吧演出列表（分页）
     *
     * @param page    分页页数
     * @param size    分页条数
     * @param status  演出状态
     * @return 演出列表
     */
    @ApiOperation("获取酒吧演出列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "演出状态", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/list")
    public R<IPage<BarPerformance>> getBarPerformanceList(
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String status) {
        log.info("BarPerformanceController.getBarPerformanceList?page={}, size={}, status={}", page, size, status);
        try {
            IPage<BarPerformance> performanceList = barPerformanceService.getBarPerformanceList(page, size, status);
            return R.data(performanceList);
        } catch (Exception e) {
            log.error("获取酒吧演出列表失败", e);
            return R.fail("获取酒吧演出列表失败：" + e.getMessage());
        }
    }

    /**
     * 新增或更新酒吧演出
     *
     * @param barPerformance 演出信息
     * @return 操作结果
     */
    @ApiOperation("新增或更新酒吧演出")
    @PostMapping("/saveOrUpdate")
    public R<BarPerformance> addOrUpdateBarPerformance(@RequestBody BarPerformance barPerformance) {
        log.info("BarPerformanceController.addOrUpdateBarPerformance?barPerformance={}", barPerformance);
        try {
            BarPerformance result = barPerformanceService.addOrUpdateBarPerformance(barPerformance);
            if (result != null) {
                // 根据审核状态返回不同的提示信息
                if (result.getReviewStatus() != null && result.getReviewStatus() == 2) {
                    // 审核拒绝：数据已保存，但审核未通过
                    return R.success("数据保存成功，但内容审核未通过：" + 
                            (result.getRejectReason() != null ? result.getRejectReason() : "内容包含违规信息"));
                } else if (result.getReviewStatus() != null && result.getReviewStatus() == 1) {
                    // 审核通过
                    return R.success("操作成功");
                } else {
                    // 其他状态
                    return R.success("操作成功");
                }
            } else {
                return R.fail("操作失败");
            }
        } catch (Exception e) {
            log.error("新增或更新酒吧演出失败", e);
            return R.fail("新增或更新酒吧演出失败：" + e.getMessage());
        }
    }

    /**
     * 获取酒吧演出详情
     *
     * @param id 演出ID
     * @return 演出详情（包含表演嘉宾信息）
     */
    @ApiOperation("获取酒吧演出详情")
    @ApiImplicitParam(name = "id", value = "演出ID", dataType = "Integer", paramType = "query", required = true)
    @GetMapping("/detail")
    public R<BarPerformanceDetailVo> getBarPerformanceDetail(@RequestParam Integer id) {
        log.info("BarPerformanceController.getBarPerformanceDetail?id={}", id);
        try {
            BarPerformanceDetailVo performance = barPerformanceService.getBarPerformanceDetail(id);
            if (performance != null) {
                return R.data(performance);
            } else {
                return R.fail("演出不存在");
            }
        } catch (Exception e) {
            log.error("获取酒吧演出详情失败", e);
            return R.fail("获取酒吧演出详情失败：" + e.getMessage());
        }
    }

    /**
     * 删除酒吧演出
     *
     * @param id 演出ID
     * @return 操作结果
     */
    @ApiOperation("删除酒吧演出")
    @ApiImplicitParam(name = "id", value = "演出ID", dataType = "Integer", paramType = "query", required = true)
    @DeleteMapping("/delete")
    public R<Integer> deleteBarPerformance(@RequestParam Integer id) {
        log.info("BarPerformanceController.deleteBarPerformance?id={}", id);
        try {
            Integer result = barPerformanceService.deleteBarPerformance(id);
            if (result > 0) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除酒吧演出失败", e);
            return R.fail("删除酒吧演出失败：" + e.getMessage());
        }
    }

    /**
     * 设置演出上线下线状态
     *
     * @param dto 包含演出ID和上线状态的DTO对象
     * @return 操作结果
     */
    @ApiOperation("设置演出上线状态")
    @PostMapping("/setOnlineStatus")
    public R<Integer> setOnlineStatus(@RequestBody BarPerformanceOnlineStatusDto dto) {
        log.info("BarPerformanceController.setOnlineStatus?dto={}", dto);
        try {
            // 参数验证
            if (dto == null || dto.getId() == null || dto.getOnlineStatus() == null) {
                log.warn("设置演出上线状态参数不完整：dto={}", dto);
                return R.fail("参数不完整，演出ID和上线状态不能为空");
            }
            Integer result = barPerformanceService.setOnlineStatus(dto.getId(), dto.getOnlineStatus());
            if (result > 0) {
                return R.success("设置成功");
            } else {
                return R.fail("设置失败");
            }
        } catch (Exception e) {
            log.error("设置演出上线状态失败，dto={}", dto, e);
            return R.fail("设置演出上线状态失败：" + e.getMessage());
        }
    }

    /**
     * 根据门店ID查询演出列表
     *
     * @param page    分页页数
     * @param size    分页条数
     * @param storeId 门店ID
     * @param statusReview 审核状态（0-待审核 1-审核通过 2-审核拒绝）（已废弃，请使用reviewStatus）
     * @param category 演出分类（all-全部, not_started-未开始, in_progress-进行中, ended-已结束）
     * @param performanceName 演出名称（可选，支持模糊搜索）
     * @param performanceType 演出类型（0-特邀演出，1-常规演出）
     * @param onlineStatus 上线状态（0-下线，1-上线）
     * @param reviewStatus 审核状态（0-待审核 1-审核通过 2-审核拒绝）
     * @param startCreatedTime 创建时间开始（yyyy-MM-dd HH:mm:ss）
     * @param endCreatedTime 创建时间结束（yyyy-MM-dd HH:mm:ss）
     * @return 演出列表
     */
    @ApiOperation("根据门店ID查询演出列表（支持按审核状态、分类和名称搜索）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页页数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "statusReview", value = "审核状态（0-待审核 1-审核通过 2-审核拒绝）（已废弃，请使用reviewStatus）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "category", value = "演出分类（all-全部, not_started-未开始, in_progress-进行中, ended-已结束）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "performanceName", value = "演出名称（支持模糊搜索）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "performanceType", value = "演出类型（0-特邀演出，1-常规演出）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "onlineStatus", value = "上线状态（0-下线，1-上线）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "reviewStatus", value = "审核状态（0-待审核 1-审核通过 2-审核拒绝）", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "startCreatedTime", value = "创建时间开始（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endCreatedTime", value = "创建时间结束（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/listByStoreId")
    public R<IPage<BarPerformance>> queryPerformanceListByStoreId(
            @RequestParam Integer page,
            @RequestParam Integer size,
            @RequestParam Integer storeId,
            @RequestParam(required = false) Integer statusReview,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String performanceName,
            @RequestParam(required = false) Integer performanceType,
            @RequestParam(required = false) Integer onlineStatus,
            @RequestParam(required = false) Integer reviewStatus,
            @RequestParam(required = false) String startCreatedTime,
            @RequestParam(required = false) String endCreatedTime) {
        // 兼容旧参数：如果reviewStatus为空但statusReview不为空，使用statusReview
        Integer finalReviewStatus = reviewStatus != null ? reviewStatus : statusReview;
        
        // 解析时间参数
        Date startTime = null;
        Date endTime = null;
        if (startCreatedTime != null && !startCreatedTime.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startTime = sdf.parse(startCreatedTime);
            } catch (Exception e) {
                log.warn("解析开始时间失败: {}", startCreatedTime, e);
            }
        }
        if (endCreatedTime != null && !endCreatedTime.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                endTime = sdf.parse(endCreatedTime);
            } catch (Exception e) {
                log.warn("解析结束时间失败: {}", endCreatedTime, e);
            }
        }
        
        log.info("BarPerformanceController.queryPerformanceListByStoreId?page={}, size={}, storeId={}, statusReview={}, category={}, performanceName={}, performanceType={}, onlineStatus={}, reviewStatus={}, startCreatedTime={}, endCreatedTime={}",
                page, size, storeId, statusReview, category, performanceName, performanceType, onlineStatus, reviewStatus, startCreatedTime, endCreatedTime);
        try {
            IPage<BarPerformance> performanceList = barPerformanceService.queryPerformanceListByStoreIdAndCategory(
                    page, size, storeId, finalReviewStatus, category != null ? category : "all", performanceName, performanceType, onlineStatus, startTime, endTime);
            return R.data(performanceList);
        } catch (Exception e) {
            log.error("根据门店ID查询演出列表失败", e);
            return R.fail("根据门店ID查询演出列表失败：" + e.getMessage());
        }
    }

}
