package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.parser.JsqlParserFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.DataEnrichmentUtil;
import com.rj.entity.Dealership;
import com.rj.entity.ProjectManagement;
import com.rj.service.IDealershipService;
import com.rj.service.IProjectManagementService;
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.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;
import java.util.Objects;
import java.util.stream.Collectors;

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

    @Autowired
    private IProjectManagementService projectManagementService;

    @Autowired
    private DataEnrichmentUtil dataEnrichmentUtil;

    /**
     * 新增项目
     */
    @PostMapping("/add")
    @Operation(summary = "新增项目", description = "添加新的项目信息")
    public ResponseEntity<Map<String, Object>> addProject(
            @Parameter(description = "项目信息", required = true)
            @RequestBody ProjectManagement projectManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            projectManagement.setCreateTime(LocalDateTime.now());
            projectManagement.setUpdateTime(LocalDateTime.now());
            boolean success = projectManagementService.save(projectManagement);
            if (success) {
                result.put("success", true);
                result.put("message", "项目添加成功");
                result.put("data", projectManagement);
                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>> getProjectById(
            @Parameter(description = "项目ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            ProjectManagement project = projectManagementService.getById(id);
            if (project != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", project);
                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("/getByName")
    @Operation(summary = "根据项目名称查询", description = "根据项目名称查询项目信息")
    public ResponseEntity<Map<String, Object>> getProjectByName(
            @Parameter(description = "项目名称", required = true)
            @RequestParam String projectName) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<ProjectManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProjectManagement::getProjectName, projectName);
            List<ProjectManagement> projectList = projectManagementService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", projectList);
            result.put("count", projectList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 分页查询项目列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询项目列表", description = "分页查询项目信息列表")
    public ResponseEntity<Map<String, Object>> getProjectList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "项目名称（模糊查询）")
            @RequestParam(required = false) String projectName,
            @Parameter(description = "所属经销商ID")
            @RequestParam(required = false) String dealershipId,
            @Parameter(description = "项目状态")
            @RequestParam(required = false) Boolean status,
            @Parameter(description = "分组")
            @RequestParam(required = false) String groupName) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<ProjectManagement> page = new Page<>(current, size);
            LambdaQueryWrapper<ProjectManagement> queryWrapper = new LambdaQueryWrapper<>();

            // 添加查询条件
            if (projectName != null && !projectName.trim().isEmpty()) {
                queryWrapper.like(ProjectManagement::getProjectName, projectName);
            }
            if (dealershipId != null && !dealershipId.trim().isEmpty()) {
                queryWrapper.eq(ProjectManagement::getDealershipId, dealershipId);
            }
            if (status != null) {
                queryWrapper.eq(ProjectManagement::getStatus, status);
            }
            if (groupName != null && !groupName.trim().isEmpty()) {
                queryWrapper.eq(ProjectManagement::getGroupName, groupName);
            }

            // 按创建时间倒序排列
            queryWrapper.orderByDesc(ProjectManagement::getUpdateTime);

            Page<ProjectManagement> projectPage = projectManagementService.page(page, queryWrapper);
            JsqlParserFunction<Dealership, String> getId = Dealership::getId;



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

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

            // 构造返回数据，包含门店名称
            List<Map<String, Object>> projectDataList = projectPage.getRecords().stream().map(project -> {
                Map<String, Object> projectMap = new HashMap<>();
                projectMap.put("id", project.getId());
                projectMap.put("dealershipId", project.getDealershipId());
                projectMap.put("dealershipName", dealershipNameMap.get(project.getDealershipId()));
                projectMap.put("projectName", project.getProjectName());
                projectMap.put("scriptVersion", project.getScriptVersion());
                projectMap.put("scriptPublishTime", project.getScriptPublishTime());
                projectMap.put("salespersonCount", project.getSalespersonCount());
                projectMap.put("avgRecordingDuration", project.getAvgRecordingDuration());
                projectMap.put("step", project.getStep());
                projectMap.put("groupName", project.getGroupName());
                projectMap.put("createTime", project.getCreateTime());
                projectMap.put("description", project.getDescription());
                projectMap.put("status", project.getStatus());
                projectMap.put("updateTime", project.getUpdateTime());
                return projectMap;
            }).collect(Collectors.toList());

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", projectDataList);
            result.put("total", projectPage.getTotal());
            result.put("current", projectPage.getCurrent());
            result.put("size", projectPage.getSize());
            result.put("pages", projectPage.getPages());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询异常：", e.getMessage());
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新项目信息
     */
    @PutMapping("/update")
    @Operation(summary = "更新项目信息", description = "更新项目详细信息")
    public ResponseEntity<Map<String, Object>> updateProject(
            @Parameter(description = "项目信息", required = true)
            @RequestBody ProjectManagement projectManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (projectManagement.getId() == null || projectManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "项目ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            projectManagement.setUpdateTime(LocalDateTime.now());
            boolean success = projectManagementService.updateById(projectManagement);
            
            if (success) {
                result.put("success", true);
                result.put("message", "项目信息更新成功");
                result.put("data", projectManagement);
                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>> deleteProject(
            @Parameter(description = "项目ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = projectManagementService.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>> batchDeleteProjects(
            @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 = projectManagementService.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>> getProjectStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = projectManagementService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalProjects", 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);
        }
    }
}
