package com.dora.controller;

import com.dora.dto.ApiResponse;
import com.dora.dto.WechatQrCodeDto;
import com.dora.entity.WechatQrCode;
import com.dora.service.WechatQrCodeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 企业微信二维码控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Validated
@Tag(name = "企业微信二维码", description = "企业微信二维码管理接口")
public class WechatQrCodeController {

    private final WechatQrCodeService wechatQrCodeService;
    
    private static final String ERROR_MESSAGE = "获取企业微信二维码列表失败";

    /**
     * 获取企业微信二维码列表（用户端接口，不需要JWT）
     */
    @GetMapping("/user/wechat-qr/list")
    @Operation(summary = "获取企业微信二维码列表", description = "获取所有企业微信二维码列表，用户端接口无需认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "获取成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<WechatQrCodeDto.QrCodeListResponse> getAllQrCodes() {
        try {
            log.info("获取企业微信二维码列表");
            
            List<WechatQrCode> qrCodes = wechatQrCodeService.getAllQrCodes();
            List<WechatQrCodeDto.QrCodeInfo> qrCodeInfos = qrCodes.stream()
                    .map(this::convertToDto)
                    .toList();
            
            WechatQrCodeDto.QrCodeListResponse response = new WechatQrCodeDto.QrCodeListResponse();
            response.setQrCodes(qrCodeInfos);
            response.setTotal(qrCodeInfos.size());
            
            log.info("获取企业微信二维码列表成功，共 {} 个", qrCodeInfos.size());
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            log.error(ERROR_MESSAGE, e);
            return ApiResponse.error(ERROR_MESSAGE);
        }
    }

    /**
     * 获取所有企业微信二维码列表（管理员接口）
     */
    @GetMapping("/admin/wechat-qr/list")
    @Operation(summary = "获取所有企业微信二维码列表", description = "管理员获取所有企业微信二维码列表")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "获取成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<WechatQrCodeDto.QrCodeListResponse> getAdminQrCodes() {
        try {
            log.info("管理员获取所有企业微信二维码列表");
            
            List<WechatQrCode> qrCodes = wechatQrCodeService.getAllQrCodes();
            List<WechatQrCodeDto.QrCodeInfo> qrCodeInfos = qrCodes.stream()
                    .map(this::convertToDto)
                    .toList();
            
            WechatQrCodeDto.QrCodeListResponse response = new WechatQrCodeDto.QrCodeListResponse();
            response.setQrCodes(qrCodeInfos);
            response.setTotal(qrCodeInfos.size());
            
            log.info("管理员获取企业微信二维码列表成功，共 {} 个", qrCodeInfos.size());
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            log.error("管理员" + ERROR_MESSAGE, e);
            return ApiResponse.error(ERROR_MESSAGE);
        }
    }

    /**
     * 根据ID获取企业微信二维码信息（管理员接口）
     */
    @GetMapping("/admin/wechat-qr/{id}")
    @Operation(summary = "根据ID获取企业微信二维码信息", description = "管理员根据ID获取企业微信二维码详细信息")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "获取成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "二维码不存在")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<WechatQrCodeDto.QrCodeInfo> getQrCodeById(
            @Parameter(description = "二维码ID")
            @PathVariable Long id) {
        try {
            log.info("管理员获取企业微信二维码信息，ID: {}", id);
            
            WechatQrCode qrCode = wechatQrCodeService.getById(id);
            if (qrCode == null) {
                log.warn("未找到企业微信二维码，ID: {}", id);
                return ApiResponse.error("未找到对应的二维码");
            }
            
            WechatQrCodeDto.QrCodeInfo qrCodeInfo = convertToDto(qrCode);
            log.info("管理员获取企业微信二维码信息成功，ID: {}", id);
            return ApiResponse.success(qrCodeInfo);
            
        } catch (Exception e) {
            log.error("管理员获取企业微信二维码信息失败，ID: {}", id, e);
            return ApiResponse.error("获取企业微信二维码信息失败");
        }
    }

    /**
     * 获取企业微信二维码列表（管理员接口，简化路径）
     * 此接口与 /admin/wechat-qr/list 功能相同，提供更简洁的访问路径
     */
    @GetMapping("/admin/wechat-qr")
    @Operation(summary = "获取企业微信二维码列表", description = "管理员获取所有企业微信二维码列表（简化路径）")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "获取成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<WechatQrCodeDto.QrCodeListResponse> getQrCodes() {
        try {
            log.info("管理员获取企业微信二维码列表（简化路径）");
            
            List<WechatQrCode> qrCodes = wechatQrCodeService.getAllQrCodes();
            List<WechatQrCodeDto.QrCodeInfo> qrCodeInfos = qrCodes.stream()
                    .map(this::convertToDto)
                    .toList();
            
            WechatQrCodeDto.QrCodeListResponse response = new WechatQrCodeDto.QrCodeListResponse();
            response.setQrCodes(qrCodeInfos);
            response.setTotal(qrCodeInfos.size());
            
            log.info("管理员获取企业微信二维码列表成功（简化路径），共 {} 个", qrCodeInfos.size());
            return ApiResponse.success(response);
            
        } catch (Exception e) {
            log.error("管理员" + ERROR_MESSAGE + "（简化路径）", e);
            return ApiResponse.error(ERROR_MESSAGE);
        }
    }

    /**
     * 创建企业微信二维码（管理员接口）
     */
    @PostMapping("/admin/wechat-qr")
    @Operation(summary = "创建企业微信二维码", description = "管理员创建新的企业微信二维码")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<WechatQrCodeDto.QrCodeInfo> createQrCode(
            @Parameter(description = "创建二维码请求")
            @Valid @RequestBody WechatQrCodeDto.QrCodeCreateRequest request) {
        try {
            log.info("管理员创建企业微信二维码");
            
            WechatQrCode qrCode = new WechatQrCode();
            BeanUtils.copyProperties(request, qrCode);
            
            WechatQrCode createdQrCode = wechatQrCodeService.createQrCode(qrCode);
            WechatQrCodeDto.QrCodeInfo qrCodeInfo = convertToDto(createdQrCode);
            
            log.info("管理员创建企业微信二维码成功，ID: {}", createdQrCode.getId());
            return ApiResponse.success(qrCodeInfo);
            
        } catch (Exception e) {
            log.error("管理员创建企业微信二维码失败", e);
            return ApiResponse.error("创建企业微信二维码失败: " + e.getMessage());
        }
    }

    /**
     * 更新企业微信二维码（管理员接口）
     */
    @PutMapping("/admin/wechat-qr/{id}")
    @Operation(summary = "更新企业微信二维码", description = "管理员更新企业微信二维码信息")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "二维码不存在")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<WechatQrCodeDto.QrCodeInfo> updateQrCode(
            @Parameter(description = "二维码ID")
            @PathVariable Long id,
            @Parameter(description = "更新二维码请求")
            @Valid @RequestBody WechatQrCodeDto.QrCodeUpdateRequest request) {
        try {
            log.info("管理员更新企业微信二维码，ID: {}", id);
            
            WechatQrCode qrCode = new WechatQrCode();
            BeanUtils.copyProperties(request, qrCode);
            
            WechatQrCode updatedQrCode = wechatQrCodeService.updateQrCode(id, qrCode);
            WechatQrCodeDto.QrCodeInfo qrCodeInfo = convertToDto(updatedQrCode);
            
            log.info("管理员更新企业微信二维码成功，ID: {}", id);
            return ApiResponse.success(qrCodeInfo);
            
        } catch (Exception e) {
            log.error("管理员更新企业微信二维码失败，ID: {}", id, e);
            return ApiResponse.error("更新企业微信二维码失败: " + e.getMessage());
        }
    }

    /**
     * 删除企业微信二维码（管理员接口）
     */
    @DeleteMapping("/admin/wechat-qr/{id}")
    @Operation(summary = "删除企业微信二维码", description = "管理员删除企业微信二维码")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未认证")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "二维码不存在")
    @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误")
    public ApiResponse<Void> deleteQrCode(
            @Parameter(description = "二维码ID")
            @PathVariable Long id) {
        try {
            log.info("管理员删除企业微信二维码，ID: {}", id);
            
            boolean result = wechatQrCodeService.deleteQrCode(id);
            if (!result) {
                log.warn("删除企业微信二维码失败，可能不存在，ID: {}", id);
                return ApiResponse.error("删除失败，二维码可能不存在");
            }
            
            log.info("管理员删除企业微信二维码成功，ID: {}", id);
            return ApiResponse.success();
            
        } catch (Exception e) {
            log.error("管理员删除企业微信二维码失败，ID: {}", id, e);
            return ApiResponse.error("删除企业微信二维码失败: " + e.getMessage());
        }
    }

    /**
     * 将WechatQrCode实体转换为DTO
     */
    private WechatQrCodeDto.QrCodeInfo convertToDto(WechatQrCode wechatQrCode) {
        WechatQrCodeDto.QrCodeInfo dto = new WechatQrCodeDto.QrCodeInfo();
        BeanUtils.copyProperties(wechatQrCode, dto);
        return dto;
    }
}
