package shop.alien.lawyer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerUserViolation;
import shop.alien.entity.store.StoreDictionary;
import shop.alien.entity.store.dto.LawyerUserViolationDto;
import shop.alien.entity.store.vo.LawyerUserViolationVo;
import shop.alien.entity.store.vo.LawyerViolationDetailVO;
import shop.alien.lawyer.service.LawyerUserViolationService;

import java.util.List;
import java.util.Map;


/**
 * <p>
 * 律师用户举报 前端控制器
 * </p>
 *
 * @author system
 * @since 2025-01-XX
 */
@Api(tags = {"律师订单用户举报"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/lawyer/user-violation")
@RequiredArgsConstructor
public class LawyerUserViolationController {

    private final LawyerUserViolationService lawyerUserViolationService;

    /**
     * 用户举报接口
     * <p>
     * 用于律师用户提交举报信息，包括被举报用户信息、举报类型、举报内容等
     * </p>
     *
     * @param lawyerUserViolation 举报信息对象，包含以下必填字段：
     *                            <ul>
     *                            <li>reportedUserId: 被举报用户ID</li>
     *                            <li>reportingUserId: 举报用户ID</li>
     *                            <li>violationType: 违规类型（1-12）</li>
     *                            <li>reportContextType: 举报内容分类</li>
     *                            </ul>
     * @return 统一响应结果，成功返回"举报成功"，失败返回"举报失败"
     * @author system
     * @since 2025-01-XX
     */
    @ApiOperation(value = "用户举报", notes = "提交用户举报信息，系统将自动发送通知消息")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reportedUserId", value = "被举报用户ID", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "reportingUserId", value = "举报用户ID", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "violationType", value = "违规类型1-服务态度差,2-专业能力差,3-响应时间超过24小时,4-其他原因", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "reportContextType", value = "举报内容分类", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "otherReasonContent", value = "其他原因具体内容（当violationType为12时必填）", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "reportEvidenceImg", value = "举报凭证图片", required = false, dataType = "String", paramType = "body")
    })
    @PostMapping("/userReporting")
    public R<String> userReporting(@RequestBody LawyerUserViolation lawyerUserViolation) {
        log.info("用户举报请求，被举报用户ID：{}，举报用户ID：{}",
                lawyerUserViolation.getReportedUserId(),
                lawyerUserViolation.getReportingUserId());

        try {
            int result = lawyerUserViolationService.userReporting(lawyerUserViolation);
            if (result > 0) {
                log.info("用户举报成功，被举报用户ID：{}，举报用户ID：{}",
                        lawyerUserViolation.getReportedUserId(),
                        lawyerUserViolation.getReportingUserId());
                return R.success("举报成功");
            } else {
                log.warn("用户举报失败，被举报用户ID：{}，举报用户ID：{}",
                        lawyerUserViolation.getReportedUserId(),
                        lawyerUserViolation.getReportingUserId());
                return R.fail("举报失败");
            }
        } catch (RuntimeException e) {
            // 业务异常，返回具体的错误信息
            String errorMessage = e.getMessage();
            log.warn("用户举报业务异常，被举报用户ID：{}，举报用户ID：{}，异常信息：{}",
                    lawyerUserViolation.getReportedUserId(),
                    lawyerUserViolation.getReportingUserId(),
                    errorMessage);
            return R.fail(StringUtils.isNotEmpty(errorMessage) ? errorMessage : "举报失败");
        } catch (Exception e) {
            log.error("用户举报异常，被举报用户ID：{}，举报用户ID：{}，异常信息：{}",
                    lawyerUserViolation.getReportedUserId(),
                    lawyerUserViolation.getReportingUserId(),
                    e.getMessage(), e);
            return R.fail("举报处理异常，请稍后重试");
        }
    }

    @ApiOperation("举报结果")
    @ApiOperationSupport(order = 2)
    @GetMapping("/reportListByUserId")
    public R<Map<String, Object>> reportListByUserId(@RequestParam(value = "userId") String userId) {
        return R.data(lawyerUserViolationService.reportListByUserId(userId));
    }

    /**
     * 根据ID查询举报详情
     * <p>
     * 根据举报ID查询举报详细信息，包括被举报人信息、举报原因、举报凭证等
     * </p>
     *
     * @param id 举报记录ID
     * @return 统一响应结果，包含举报详情VO对象
     * @author system
     * @since 2025-01-XX
     */
    @ApiOperation(value = "举报详细信息", notes = "根据举报ID查询举报详细信息")
    @ApiOperationSupport(order = 3)
    @GetMapping("/reportListById")
    public R<LawyerUserViolationVo> reportListById(@RequestParam(value = "id") String id) {
        log.info("查询举报详情请求，ID：{}", id);
        try {
            LawyerUserViolationVo violationVo = lawyerUserViolationService.reportListById(id);
            if (violationVo == null) {
                log.warn("举报记录不存在，ID：{}", id);
                return R.fail("举报记录不存在");
            }
            return R.data(violationVo);
        } catch (RuntimeException e) {
            log.warn("查询举报详情业务异常，ID：{}，异常信息：{}", id, e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("查询举报详情异常，ID：{}，异常信息：{}", id, e.getMessage(), e);
            return R.fail("查询举报详情失败，请稍后重试");
        }
    }

    @ApiOperation("举报分页")
    @ApiOperationSupport(order = 4)
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "orderNumber", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "用户电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reportedUserName", value = "律师名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "processingStatus", value = "状态(0：待处理，1：已通过，2：已驳回)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reportedPhone", value = "律师电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "violationReason", value = "举报原因", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", paramType = "query")
    })
    public R<IPage<LawyerUserViolationDto>> getViolationPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String reportedUserName,
            @RequestParam(required = false) String processingStatus,
            @RequestParam(required = false) String reportedPhone,
            @RequestParam(required = false) String violationReason,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime

    ) {
        log.info("LawyerUserViolationController.getViolationPage?pageNum={},pageSize={},orderId={},processingStatus={},reportedUserName={},violationReason={}", pageNum, pageSize, orderNumber, processingStatus, reportedUserName, violationReason);
        return R.data(lawyerUserViolationService.getViolationPage(pageNum, pageSize, orderNumber, phone, processingStatus, reportedUserName, reportedPhone, violationReason, startTime, endTime));
    }

    @ApiOperation(value = "举报审核")
    @ApiOperationSupport(order = 5)
    @GetMapping("/approve")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "processingStatus", value = "审批状态（1：审批成功，2：审批失败）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reportResult", value = "处理结果", dataType = "String", paramType = "query")
    })
    @ResponseBody
    public R<String> approveStoreInfo(@RequestParam("id") int id, @RequestParam("processingStatus") String processingStatus, @RequestParam("reportResult") String reportResult) {
        log.info("LawyerUserViolationController.approveStoreInfo?id={}&processingStatus={}", id, processingStatus);
        lawyerUserViolationService.approve(id, processingStatus, reportResult);
        return R.success("审批完成");
    }

    @ApiOperation("查看详情")
    @ApiOperationSupport(order = 6)
    @GetMapping("/byId")
    public LawyerUserViolationDto byId(@RequestParam(defaultValue = "10") int id) {
        return lawyerUserViolationService.byId(id);
    }

    @ApiOperation("查看通知详情")
    @ApiOperationSupport(order = 7)
    @GetMapping("/byIdNotice")
    public LawyerUserViolationDto byIdNotice(@RequestParam(defaultValue = "10") int id) {
        return lawyerUserViolationService.byIdNotice(id);
    }

    /**
     * 获取举报原因列表
     * <p>
     * 用于获取所有可用的律师违规举报原因选项，供前端下拉选择使用
     * </p>
     *
     * @return 统一响应结果，包含举报原因字典列表
     * @author system
     * @since 2025-01-XX
     */
    @ApiOperation(value = "获取举报原因", notes = "获取所有可用的律师违规举报原因选项列表")
    @ApiOperationSupport(order = 8)
    @GetMapping("/getViolationReason")
    public R<List<StoreDictionary>> getViolationReason() {
        log.info("获取举报原因列表请求");
        try {
            List<StoreDictionary> violationReasonList = lawyerUserViolationService.getViolationReason();
            log.info("获取举报原因列表成功，共{}条记录", violationReasonList.size());
            return R.data(violationReasonList);
        } catch (Exception e) {
            log.error("获取举报原因列表异常，异常信息：{}", e.getMessage(), e);
            return R.fail("获取举报原因列表失败，请稍后重试");
        }
    }

    /**
     * 根据订单ID查询举报详情
     * <p>
     * 查询举报详情信息，包括举报的详情信息、订单的详情信息以及订单律师名字相关信息
     * </p>
     * <p>
     * 功能说明：
     * 1. 通过订单ID查询订单、举报、律师关联信息
     * 2. 校验订单是否存在以及是否存在举报记录
     * 3. 填充举报人姓名和订单价格字符串等附加信息
     * 4. 返回完整的举报详情信息
     * </p>
     *
     * @param orderId 订单ID，必须大于0
     * @return 统一响应结果，包含举报详情VO对象（包含举报信息、订单信息、律师信息）
     * @author system
     * @since 2025-01-XX
     */
    @ApiOperation(value = "根据订单ID查询举报详情", notes = "查询举报详情信息，包括举报的详情信息、订单的详情信息以及订单律师名字相关信息")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getViolationDetailByOrderId")
    public R<LawyerViolationDetailVO> getViolationDetailByOrderId(
            @RequestParam(value = "orderId", required = true) Integer orderId) {
        log.info("根据订单ID查询举报详情请求开始，orderId={}", orderId);

        // 参数校验
        if (!validateOrderId(orderId)) {
            log.warn("根据订单ID查询举报详情失败：订单ID为空或无效，orderId={}", orderId);
            return R.fail("订单ID不能为空");
        }

        try {
            LawyerViolationDetailVO detailVO = lawyerUserViolationService.getViolationDetailByOrderId(orderId);
            if (detailVO == null) {
                log.warn("根据订单ID查询举报详情：订单不存在或未举报，orderId={}", orderId);
                return R.fail("订单不存在或未举报");
            }

            log.info("根据订单ID查询举报详情成功，orderId={}, violationId={}, orderNumber={}",
                    orderId, detailVO.getViolationId(), detailVO.getOrderNumber());
            return R.data(detailVO);

        } catch (IllegalArgumentException e) {
            log.warn("根据订单ID查询举报详情参数校验失败，orderId={}，错误信息：{}", orderId, e.getMessage());
            return R.fail(e.getMessage());
        } catch (RuntimeException e) {
            log.warn("根据订单ID查询举报详情业务异常，orderId={}，异常信息：{}", orderId, e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("根据订单ID查询举报详情异常，orderId={}，异常信息：{}", orderId, e.getMessage(), e);
            return R.fail("查询举报详情失败，请稍后重试");
        }
    }

    /**
     * 校验订单ID
     * <p>
     * 检查订单ID是否为空或无效
     * </p>
     *
     * @param orderId 订单ID
     * @return true表示有效，false表示无效
     */
    private boolean validateOrderId(Integer orderId) {
        return orderId != null && orderId > 0;
    }

}

