package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.DataEnrichmentUtil;
import com.rj.entity.AudioManagement;
import com.rj.entity.VideoManagement;
import com.rj.service.IVideoManagementService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 视频管理表 前端控制器
 * </p>
 *
 * @author 李中华 ,spllzh
 * @since 2025-08-07
 */
@RestController
@RequestMapping("/api/videoManagement")
@Tag(name = "视频管理", description = "视频管理相关接口")
public class VideoManagementController {

    @Autowired
    private IVideoManagementService videoManagementService;

    /**
     * 新增视频
     */
    @PostMapping("/add")
    @Operation(summary = "新增视频", description = "添加新的视频信息")
    public ResponseEntity<Map<String, Object>> addVideo(
            @Parameter(description = "视频信息", required = true)
            @RequestBody VideoManagement videoManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            videoManagement.setCreateTime(LocalDateTime.now());
            videoManagement.setUpdateTime(LocalDateTime.now());
            boolean success = videoManagementService.save(videoManagement);
            if (success) {
                result.put("success", true);
                result.put("message", "视频添加成功");
                result.put("data", videoManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "视频添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "视频添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询视频
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询视频", description = "根据视频ID获取视频详细信息")
    public ResponseEntity<Map<String, Object>> getVideoById(
            @Parameter(description = "视频ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            VideoManagement video = videoManagementService.getById(id);
            if (video != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", video);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "视频不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据客户手机号查询视频
     */
    @GetMapping("/getByCustomerPhone")
    @Operation(summary = "根据客户手机号查询视频", description = "根据客户手机号查询视频信息")
    public ResponseEntity<Map<String, Object>> getVideoByCustomerPhone(
            @Parameter(description = "客户手机号", required = true)
            @RequestParam String customerPhone) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<VideoManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VideoManagement::getCustomerPhone, customerPhone);
            List<VideoManagement> videoList = videoManagementService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", videoList);
            result.put("count", videoList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @Autowired
    private DataEnrichmentUtil dataEnrichmentUtil;



    /**
     * 分页查询视频列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询视频列表", description = "分页查询视频信息列表")
    public ResponseEntity<Map<String, Object>> getVideoList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "视频名称（模糊查询）")
            @RequestParam(required = false) String videoName,
            @Parameter(description = "客户手机号（模糊查询）")
            @RequestParam(required = false) String customerPhone,
            @Parameter(description = "所属门店ID")
            @RequestParam(required = false) String dealershipId,
            @Parameter(description = "所属销售ID")
            @RequestParam(required = false) String salesId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<VideoManagement> page = new Page<>(current, size);
            LambdaQueryWrapper<VideoManagement> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (videoName != null && !videoName.trim().isEmpty()) {
                queryWrapper.like(VideoManagement::getVideoName, videoName);
            }
            if (customerPhone != null && !customerPhone.trim().isEmpty()) {
                queryWrapper.like(VideoManagement::getCustomerPhone, customerPhone);
            }
            if (dealershipId != null && !dealershipId.trim().isEmpty()) {
                queryWrapper.eq(VideoManagement::getDealershipId, dealershipId);
            }
            if (salesId != null && !salesId.trim().isEmpty()) {
                queryWrapper.eq(VideoManagement::getSalesId, salesId);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(VideoManagement::getCreateTime);
            
            Page<VideoManagement> videoPage = videoManagementService.page(page, queryWrapper);

            // 使用工具类提取ID列表
            List<String> dealershipIds = DataEnrichmentUtil.extractIds(videoPage.getRecords(), VideoManagement::getDealershipId);
            List<String> salesIds = DataEnrichmentUtil.extractIds(videoPage.getRecords(), VideoManagement::getSalesId);

            // 使用工具类批量获取关联数据
            Map<String, String> dealershipNameMap = dataEnrichmentUtil.getDealershipIdNameMap(dealershipIds);
            Map<String, String> saleNameMap = dataEnrichmentUtil.getSalesIdNameMap(salesIds);

            videoPage.getRecords().forEach(video -> {
                video.setDealershipName(dealershipNameMap.get(video.getDealershipId()));
                video.setSalesName(saleNameMap.get(video.getSalesId()));
            });


            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", videoPage.getRecords());
            result.put("total", videoPage.getTotal());
            result.put("current", videoPage.getCurrent());
            result.put("size", videoPage.getSize());
            result.put("pages", videoPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新视频信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新视频信息", description = "更新视频详细信息")
    public ResponseEntity<Map<String, Object>> updateVideo(
            @Parameter(description = "视频信息", required = true)
            @RequestBody VideoManagement videoManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (videoManagement.getId() == null || videoManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            videoManagement.setUpdateTime(LocalDateTime.now());
            boolean success = videoManagementService.updateById(videoManagement);
            
            if (success) {
                result.put("success", true);
                result.put("message", "视频信息更新成功");
                result.put("data", videoManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "视频信息更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID删除视频
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除视频", description = "根据视频ID删除视频信息")
    public ResponseEntity<Map<String, Object>> deleteVideo(
            @Parameter(description = "视频ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = videoManagementService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "视频删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "视频删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除视频
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除视频", description = "根据视频ID列表批量删除视频信息")
    public ResponseEntity<Map<String, Object>> batchDeleteVideos(
            @Parameter(description = "视频ID列表", required = true)
            @RequestBody List<String> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "视频ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = videoManagementService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取视频统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取视频统计信息", description = "获取视频总数等统计信息")
    public ResponseEntity<Map<String, Object>> getVideoStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = videoManagementService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalVideos", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}




