package com.rj.controller.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.CustomerProfileAnalysis;
import com.rj.service.biz.ICustomerProfileAnalysisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户画像分析 前端控制器
 * 
 * @author 李中华
 * @date 2025/1/15
 */
@Slf4j
@RestController
@RequestMapping("/api/customer-profile-analysis")
@Tag(name = "客户画像分析", description = "客户画像分析相关接口")
public class CustomerProfileAnalysisController {

    @Autowired
    private ICustomerProfileAnalysisService customerProfileAnalysisService;

    /**
     * 分页查询客户画像分析列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询客户画像分析列表", description = "根据条件分页查询客户画像分析信息列表")
    public ResponseEntity<Map<String, Object>> getAnalysisList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "分析记录ID") @RequestParam(required = false) String profileAnalysisRecordId,
            @Parameter(description = "业务ID") @RequestParam(required = false) String relatedBusinessId,
            @Parameter(description = "经销商编码") @RequestParam(required = false) String dealerCode,
            @Parameter(description = "经销商名称（模糊查询）") @RequestParam(required = false) String dealerName,
            @Parameter(description = "大区") @RequestParam(required = false) String bigArea,
            @Parameter(description = "分析场景类型") @RequestParam(required = false) Integer analysisSceneType,
            @Parameter(description = "客户姓名（模糊查询）") @RequestParam(required = false) String clientName,
            @Parameter(description = "客户电话") @RequestParam(required = false) String clientPhone,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        log.info("分页查询客户画像分析列表，分析记录ID={}, 业务ID={}, 经销商编码={}, 经销商名称={}, 大区={}, 分析场景类型={}, 客户姓名={}, 客户电话={}, 开始日期={}, 结束日期={}", 
                profileAnalysisRecordId, relatedBusinessId, dealerCode, dealerName, bigArea, analysisSceneType, clientName, clientPhone, startDate, endDate);

        Map<String, Object> result = new HashMap<>();
        try {
            Page<CustomerProfileAnalysis> page = new Page<>(current, size);
            LambdaQueryWrapper<CustomerProfileAnalysis> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (profileAnalysisRecordId != null && !profileAnalysisRecordId.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getProfileAnalysisRecordId, profileAnalysisRecordId);
            }
            if (relatedBusinessId != null && !relatedBusinessId.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getRelatedBusinessId, relatedBusinessId);
            }
            if (dealerCode != null && !dealerCode.trim().isEmpty()) {
                queryWrapper.like(CustomerProfileAnalysis::getDealerCode, dealerCode);
            }
            if (dealerName != null && !dealerName.trim().isEmpty()) {
                queryWrapper.like(CustomerProfileAnalysis::getDealerName, dealerName);
            }
            if (bigArea != null && !bigArea.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getBigArea, bigArea);
            }
            if (analysisSceneType != null) {
                queryWrapper.eq(CustomerProfileAnalysis::getAnalysisSceneType, analysisSceneType);
            }
            if (clientName != null && !clientName.trim().isEmpty()) {
                queryWrapper.like(CustomerProfileAnalysis::getClientName, clientName);
            }
            if (clientPhone != null && !clientPhone.trim().isEmpty()) {
                queryWrapper.like(CustomerProfileAnalysis::getClientPhone, clientPhone);
            }
            if (startDate != null) {
                queryWrapper.ge(CustomerProfileAnalysis::getInteractionDate, startDate.atStartOfDay());
            }
            if (endDate != null) {
                queryWrapper.le(CustomerProfileAnalysis::getInteractionDate, endDate.atTime(23, 59, 59));
            }
            
            // 只查询未删除的记录
            queryWrapper.eq(CustomerProfileAnalysis::getIsDeleted, 0);
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(CustomerProfileAnalysis::getCreatedAt);
            
            Page<CustomerProfileAnalysis> analysisPage = customerProfileAnalysisService.page(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", analysisPage.getRecords());
            result.put("total", analysisPage.getTotal());
            result.put("current", analysisPage.getCurrent());
            result.put("size", analysisPage.getSize());
            result.put("pages", analysisPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询客户画像分析列表失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据条件查询客户画像分析（不分页）
     */
    @GetMapping("/query")
    @Operation(summary = "根据条件查询客户画像分析", description = "根据条件查询客户画像分析信息（不分页）")
    public ResponseEntity<Map<String, Object>> getAnalysisList(
            @Parameter(description = "分析记录ID") @RequestParam(required = false) String profileAnalysisRecordId,
            @Parameter(description = "业务ID") @RequestParam(required = false) String relatedBusinessId,
            @Parameter(description = "经销商编码") @RequestParam(required = false) String dealerCode,
            @Parameter(description = "大区") @RequestParam(required = false) String bigArea,
            @Parameter(description = "分析场景类型") @RequestParam(required = false) Integer analysisSceneType,
            @Parameter(description = "客户姓名") @RequestParam(required = false) String clientName,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<CustomerProfileAnalysis> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (profileAnalysisRecordId != null && !profileAnalysisRecordId.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getProfileAnalysisRecordId, profileAnalysisRecordId);
            }
            if (relatedBusinessId != null && !relatedBusinessId.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getRelatedBusinessId, relatedBusinessId);
            }
            if (dealerCode != null && !dealerCode.trim().isEmpty()) {
                queryWrapper.like(CustomerProfileAnalysis::getDealerCode, dealerCode);
            }
            if (bigArea != null && !bigArea.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getBigArea, bigArea);
            }
            if (analysisSceneType != null) {
                queryWrapper.eq(CustomerProfileAnalysis::getAnalysisSceneType, analysisSceneType);
            }
            if (clientName != null && !clientName.trim().isEmpty()) {
                queryWrapper.like(CustomerProfileAnalysis::getClientName, clientName);
            }
            if (startDate != null) {
                queryWrapper.ge(CustomerProfileAnalysis::getInteractionDate, startDate.atStartOfDay());
            }
            if (endDate != null) {
                queryWrapper.le(CustomerProfileAnalysis::getInteractionDate, endDate.atTime(23, 59, 59));
            }
            
            // 只查询未删除的记录
            queryWrapper.eq(CustomerProfileAnalysis::getIsDeleted, 0);
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(CustomerProfileAnalysis::getCreatedAt);
            
            List<CustomerProfileAnalysis> analysisList = customerProfileAnalysisService.list(queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", analysisList);
            result.put("total", analysisList.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("根据条件查询客户画像分析失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询客户画像分析
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询客户画像分析", description = "根据主键ID查询单条客户画像分析信息")
    public ResponseEntity<Map<String, Object>> getAnalysisById(
            @Parameter(description = "客户画像分析ID", required = true)
            @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            CustomerProfileAnalysis analysis = customerProfileAnalysisService.getById(id);
            if (analysis != null && analysis.getIsDeleted() == 0) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "客户画像分析不存在或已删除");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据ID查询客户画像分析失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据分析记录ID查询客户画像分析
     */
    @GetMapping("/by-record-id/{profileAnalysisRecordId}")
    @Operation(summary = "根据分析记录ID查询客户画像分析", description = "根据分析记录ID查询客户画像分析信息")
    public ResponseEntity<Map<String, Object>> getAnalysisByRecordId(
            @Parameter(description = "分析记录ID", required = true)
            @PathVariable String profileAnalysisRecordId) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            CustomerProfileAnalysis analysis = customerProfileAnalysisService.getByProfileAnalysisRecordId(profileAnalysisRecordId);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到对应的客户画像分析记录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据分析记录ID查询客户画像分析失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据业务ID查询客户画像分析
     */
    @GetMapping("/by-business-id/{businessId}")
    @Operation(summary = "根据业务ID查询客户画像分析", description = "根据业务ID查询客户画像分析信息")
    public ResponseEntity<Map<String, Object>> getAnalysisByBusinessId(
            @Parameter(description = "业务ID", required = true)
            @PathVariable String businessId) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            CustomerProfileAnalysis analysis = customerProfileAnalysisService.getByBusinessId(businessId);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到对应的客户画像分析记录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据业务ID查询客户画像分析失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 新增客户画像分析
     */
    @PostMapping("/add")
    @Operation(summary = "新增客户画像分析", description = "新增一条客户画像分析记录")
    public ResponseEntity<Map<String, Object>> addAnalysis(
            @Parameter(description = "客户画像分析信息", required = true)
            @Valid @RequestBody CustomerProfileAnalysis analysis) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 设置系统字段
            LocalDateTime now = LocalDateTime.now();
            analysis.setCreatedAt(now);
            analysis.setUpdatedAt(now);
            analysis.setRecordVersion(0);
            analysis.setIsDeleted(0);
            
            boolean success = customerProfileAnalysisService.saveCustomerProfileAnalysis(analysis);
            if (success) {
                result.put("success", true);
                result.put("message", "客户画像分析添加成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "客户画像分析添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("新增客户画像分析失败", 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>> updateAnalysis(
            @Parameter(description = "客户画像分析信息", required = true)
            @Valid @RequestBody CustomerProfileAnalysis analysis) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            if (analysis.getId() == null || analysis.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查记录是否存在
            CustomerProfileAnalysis existingAnalysis = customerProfileAnalysisService.getById(analysis.getId());
            if (existingAnalysis == null || existingAnalysis.getIsDeleted() == 1) {
                result.put("success", false);
                result.put("message", "客户画像分析不存在或已删除");
                return ResponseEntity.notFound().build();
            }
            
            // 设置更新时间
            analysis.setUpdatedAt(LocalDateTime.now());
            
            boolean success = customerProfileAnalysisService.updateById(analysis);
            if (success) {
                result.put("success", true);
                result.put("message", "客户画像分析修改成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "客户画像分析修改失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("修改客户画像分析失败", e);
            result.put("success", false);
            result.put("message", "修改异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除客户画像分析（逻辑删除）
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除客户画像分析", description = "根据ID逻辑删除客户画像分析记录")
    public ResponseEntity<Map<String, Object>> deleteAnalysis(
            @Parameter(description = "客户画像分析ID", required = true)
            @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查记录是否存在
            CustomerProfileAnalysis existingAnalysis = customerProfileAnalysisService.getById(id);
            if (existingAnalysis == null || existingAnalysis.getIsDeleted() == 1) {
                result.put("success", false);
                result.put("message", "客户画像分析不存在或已删除");
                return ResponseEntity.notFound().build();
            }
            
            // 逻辑删除
            existingAnalysis.setIsDeleted(1);
            existingAnalysis.setUpdatedAt(LocalDateTime.now());
            
            boolean success = customerProfileAnalysisService.updateById(existingAnalysis);
            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) {
            log.error("删除客户画像分析失败", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除客户画像分析（逻辑删除）
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除客户画像分析", description = "根据ID列表批量逻辑删除客户画像分析记录")
    public ResponseEntity<Map<String, Object>> batchDeleteAnalysis(
            @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);
            }
            
            LocalDateTime now = LocalDateTime.now();
            int successCount = 0;
            int failCount = 0;
            
            for (String id : ids) {
                try {
                    CustomerProfileAnalysis existingAnalysis = customerProfileAnalysisService.getById(id);
                    if (existingAnalysis != null && existingAnalysis.getIsDeleted() == 0) {
                        existingAnalysis.setIsDeleted(1);
                        existingAnalysis.setUpdatedAt(now);
                        if (customerProfileAnalysisService.updateById(existingAnalysis)) {
                            successCount++;
                        } else {
                            failCount++;
                        }
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("删除客户画像分析失败，ID: {}", id, e);
                    failCount++;
                }
            }
            
            result.put("success", true);
            result.put("message", String.format("批量删除完成，成功：%d，失败：%d", successCount, failCount));
            result.put("data", Map.of("successCount", successCount, "failCount", failCount));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("批量删除客户画像分析失败", 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>> getAnalysisStatistics(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "经销商编码") @RequestParam(required = false) String dealerCode,
            @Parameter(description = "大区") @RequestParam(required = false) String bigArea) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<CustomerProfileAnalysis> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (startDate != null) {
                queryWrapper.ge(CustomerProfileAnalysis::getInteractionDate, startDate.atStartOfDay());
            }
            if (endDate != null) {
                queryWrapper.le(CustomerProfileAnalysis::getInteractionDate, endDate.atTime(23, 59, 59));
            }
            if (dealerCode != null && !dealerCode.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getDealerCode, dealerCode);
            }
            if (bigArea != null && !bigArea.trim().isEmpty()) {
                queryWrapper.eq(CustomerProfileAnalysis::getBigArea, bigArea);
            }
            
            // 只查询未删除的记录
            queryWrapper.eq(CustomerProfileAnalysis::getIsDeleted, 0);
            
            List<CustomerProfileAnalysis> analysisList = customerProfileAnalysisService.list(queryWrapper);
            
            // 计算统计信息
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCount", analysisList.size());
            statistics.put("uniqueDealers", analysisList.stream().map(CustomerProfileAnalysis::getDealerCode).distinct().count());
            statistics.put("uniqueClients", analysisList.stream().map(CustomerProfileAnalysis::getClientId).distinct().count());
            
            // 按分析场景类型统计
            Map<Integer, Long> sceneTypeStats = analysisList.stream()
                    .collect(java.util.stream.Collectors.groupingBy(
                            CustomerProfileAnalysis::getAnalysisSceneType,
                            java.util.stream.Collectors.counting()));
            statistics.put("sceneTypeStatistics", sceneTypeStats);
            
            // 按大区统计
            Map<String, Long> bigAreaStats = analysisList.stream()
                    .filter(analysis -> analysis.getBigArea() != null)
                    .collect(java.util.stream.Collectors.groupingBy(
                            CustomerProfileAnalysis::getBigArea,
                            java.util.stream.Collectors.counting()));
            statistics.put("bigAreaStatistics", bigAreaStats);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取客户画像分析统计信息失败", e);
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
