package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.CommunicationRecord;
import com.rj.service.ICommunicationRecordService;
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 jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 沟通记录表 前端控制器
 * </p>
 *
 * @author 系统生成
 * @since 2025-01-30
 */
@RestController
@RequestMapping("/api/communication-record")
@Tag(name = "沟通记录管理", description = "沟通记录管理相关接口")
@Slf4j
public class CommunicationRecordController {

    @Autowired
    private ICommunicationRecordService communicationRecordService;

    /**
     * 分页查询沟通记录
     */

    @GetMapping("/page")
    @Operation(summary = "分页查询沟通记录", description = "根据条件分页查询沟通记录列表")
    public ResponseEntity<Map<String, Object>> getPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "客户姓名") @RequestParam(required = false) String customerName,
            @Parameter(description = "客户电话") @RequestParam(required = false) String customerPhone,
            @Parameter(description = "沟通类型") @RequestParam(required = false) String communicationType,
            @Parameter(description = "所属人姓名") @RequestParam(required = false) String ownerName) {
        
        try {
            Page<CommunicationRecord> page = new Page<>(current, size);
            LambdaQueryWrapper<CommunicationRecord> queryWrapper = new LambdaQueryWrapper<>();
            
            // 构建查询条件
            queryWrapper.like(customerName != null, CommunicationRecord::getCustomerName, customerName)
                       .like(customerPhone != null, CommunicationRecord::getCustomerPhone, customerPhone)
                       .like(communicationType != null, CommunicationRecord::getCommunicationType, communicationType)
                       .like(ownerName != null, CommunicationRecord::getOwnerName, ownerName)
                       .eq(CommunicationRecord::getStatus, 1)
                       .orderByDesc(CommunicationRecord::getCreateTime);
            
            Page<CommunicationRecord> result = communicationRecordService.page(page, queryWrapper);
            log.info("分页查询沟通记录成功，结果：{}", result.toString());
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", result.getRecords());
            response.put("total", result.getTotal());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("pages", result.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("分页查询沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据ID查询沟通记录
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询沟通记录", description = "根据ID查询沟通记录详情")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "沟通记录ID") @PathVariable String id) {
        try {
            CommunicationRecord record = communicationRecordService.getById(id);
            if (record == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 404);
                response.put("message", "沟通记录不存在");
                response.put("data", null);
                return ResponseEntity.ok(response);
            }
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", record);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 新增沟通记录
     */
    @PostMapping
    @Operation(summary = "新增沟通记录", description = "新增沟通记录")
    public ResponseEntity<Map<String, Object>> save(@Valid @RequestBody CommunicationRecord communicationRecord) {
        try {
            // 设置创建时间
            communicationRecord.setCreateTime(LocalDateTime.now());
            communicationRecord.setStatus(1);
            
            boolean success = communicationRecordService.save(communicationRecord);
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 200);
                response.put("message", "新增成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "新增失败");
                response.put("data", null);
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("新增沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "新增失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 修改沟通记录
     */
    @PutMapping
    @Operation(summary = "修改沟通记录", description = "修改沟通记录")
    public ResponseEntity<Map<String, Object>> update(@Valid @RequestBody CommunicationRecord communicationRecord) {
        try {
            // 设置更新时间
            communicationRecord.setUpdateTime(LocalDateTime.now());
            
            boolean success = communicationRecordService.updateById(communicationRecord);
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 200);
                response.put("message", "修改成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "修改失败");
                response.put("data", null);
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("修改沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "修改失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 删除沟通记录（软删除）
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除沟通记录", description = "删除沟通记录（软删除）")
    public ResponseEntity<Map<String, Object>> delete(@Parameter(description = "沟通记录ID") @PathVariable String id) {
        try {
            CommunicationRecord record = communicationRecordService.getById(id);
            if (record == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 404);
                response.put("message", "沟通记录不存在");
                response.put("data", null);
                return ResponseEntity.ok(response);
            }
            
            // 软删除
            record.setStatus(0);
            record.setUpdateTime(LocalDateTime.now());
            boolean success = communicationRecordService.updateById(record);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                response.put("code", 200);
                response.put("message", "删除成功");
                response.put("data", null);
            } else {
                response.put("code", 500);
                response.put("message", "删除失败");
                response.put("data", null);
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "删除失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据客户ID查询沟通记录
     */
    @GetMapping("/customer/{customerId}")
    @Operation(summary = "根据客户ID查询沟通记录", description = "根据客户ID查询该客户的所有沟通记录")
    public ResponseEntity<Map<String, Object>> getByCustomerId(
            @Parameter(description = "客户ID") @PathVariable String customerId) {
        try {
            LambdaQueryWrapper<CommunicationRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommunicationRecord::getCustomerId, customerId)
                       .eq(CommunicationRecord::getStatus, 1)
                       .orderByDesc(CommunicationRecord::getCommunicationTime);
            
            List<CommunicationRecord> records = communicationRecordService.list(queryWrapper);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据客户ID查询沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

    /**
     * 根据所属人查询沟通记录
     */
    @GetMapping("/owner/{ownerName}")
    @Operation(summary = "根据所属人查询沟通记录", description = "根据所属人姓名查询沟通记录")
    public ResponseEntity<Map<String, Object>> getByOwnerName(
            @Parameter(description = "所属人姓名") @PathVariable String ownerName) {
        try {
            LambdaQueryWrapper<CommunicationRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CommunicationRecord::getOwnerName, ownerName)
                       .eq(CommunicationRecord::getStatus, 1)
                       .orderByDesc(CommunicationRecord::getCreateTime);
            
            List<CommunicationRecord> records = communicationRecordService.list(queryWrapper);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", records);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据所属人查询沟通记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.ok(response);
        }
    }

}