package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.Dealership;
import com.rj.service.IDealershipService;
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/dealership")
@Tag(name = "经销商管理", description = "经销商门店管理相关接口")
public class DealershipController {

    @Autowired
    private IDealershipService dealershipService;

    /**
     * 新增经销商
     */
    @PostMapping("/add")
    @Operation(summary = "新增经销商", description = "添加新的经销商门店信息")
    public ResponseEntity<Map<String, Object>> addDealership(
            @Parameter(description = "经销商信息", required = true)
            @RequestBody Dealership dealership) {
        Map<String, Object> result = new HashMap<>();
        try {
            dealership.setCreateTime(LocalDateTime.now());
            dealership.setUpdateTime(LocalDateTime.now());
            boolean success = dealershipService.save(dealership);
            if (success) {
                result.put("success", true);
                result.put("message", "经销商添加成功");
                result.put("data", dealership);
                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>> getDealershipById(
            @Parameter(description = "经销商ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Dealership dealership = dealershipService.getById(id);
            if (dealership != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", dealership);
                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("/getByCode")
    @Operation(summary = "根据经销商代码查询", description = "根据经销商代码查询经销商信息")
    public ResponseEntity<Map<String, Object>> getDealershipByCode(
            @Parameter(description = "经销商代码", required = true)
            @RequestParam String dealershipCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<Dealership> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dealership::getDealershipCode, dealershipCode);
            List<Dealership> dealershipList = dealershipService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", dealershipList);
            result.put("count", dealershipList.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>> getDealershipList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "经销商名称（模糊查询）")
            @RequestParam(required = false) String dealershipName,
            @Parameter(description = "经销商代码（模糊查询）")
            @RequestParam(required = false) String dealershipCode,
            @Parameter(description = "地区")
            @RequestParam(required = false) String region,
            @Parameter(description = "状态")
            @RequestParam(required = false) Boolean status) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Dealership> page = new Page<>(current, size);
            LambdaQueryWrapper<Dealership> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (dealershipName != null && !dealershipName.trim().isEmpty()) {
                queryWrapper.like(Dealership::getDealershipName, dealershipName);
            }
            if (dealershipCode != null && !dealershipCode.trim().isEmpty()) {
                queryWrapper.like(Dealership::getDealershipCode, dealershipCode);
            }
            if (region != null && !region.trim().isEmpty()) {
                queryWrapper.eq(Dealership::getRegion, region);
            }
            if (status != null) {
                queryWrapper.eq(Dealership::getStatus, status);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(Dealership::getUpdateTime);
            
            Page<Dealership> dealershipPage = dealershipService.page(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", dealershipPage.getRecords());
            result.put("total", dealershipPage.getTotal());
            result.put("current", dealershipPage.getCurrent());
            result.put("size", dealershipPage.getSize());
            result.put("pages", dealershipPage.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>> updateDealership(
            @Parameter(description = "经销商信息", required = true)
            @RequestBody Dealership dealership) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (dealership.getId() == null || dealership.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "经销商ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            dealership.setUpdateTime(LocalDateTime.now());
            boolean success = dealershipService.updateById(dealership);
            
            if (success) {
                result.put("success", true);
                result.put("message", "经销商信息更新成功");
                result.put("data", dealership);
                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>> deleteDealership(
            @Parameter(description = "经销商ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = dealershipService.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>> batchDeleteDealerships(
            @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 = dealershipService.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>> getDealershipStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = dealershipService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalDealerships", 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);
        }
    }
}
