package shop.alien.lawyer.controller;

import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerConsultationOrder;
import shop.alien.entity.store.vo.LawyerConsultationOrderVO;
import shop.alien.lawyer.service.LawyerClientConsultationOrderService;

import java.util.Map;

/**
 * 咨询订单 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"律师端-咨询订单"})
@ApiSort(14)
@CrossOrigin
@RestController
@RequestMapping("/lawyerClient/consultationOrder")
@RequiredArgsConstructor
public class LawyerClientConsultationOrderController {

    private final LawyerClientConsultationOrderService lawyerClientConsultationOrderService;

    @ApiOperation("删除咨询订单（律师端）")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", dataType = "Integer", paramType = "query", required = true)
    })
    @DeleteMapping("/deleteConsultationOrder")
    public R<Boolean> deleteConsultationOrder(@RequestParam(value = "id", required = true) Integer id) {
        log.info("删除咨询订单，订单ID={}", id);
        if (id == null) {
            log.warn("删除咨询订单失败：订单ID为空");
            return R.fail("订单ID不能为空");
        }
        return lawyerClientConsultationOrderService.deleteConsultationOrder(id);
    }

    @ApiOperation("保存或更新咨询订单（律师端）")
    @ApiOperationSupport(order = 2)
    @PostMapping("/saveOrUpdate")
    public R<LawyerConsultationOrder> saveOrUpdate(@RequestBody LawyerConsultationOrder consultationOrder) {
        log.info("LawyerConsultationOrderController.saveOrUpdate?consultationOrder={}", consultationOrder);
        boolean result = lawyerClientConsultationOrderService.saveOrUpdate(consultationOrder);
        if (result) {
            return R.data(consultationOrder);
        }
        return R.fail("操作失败");
    }

    @ApiOperation("查询订单详情（律师端）")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawyerOrderId", value = "法律订单ID", dataType = "String", paramType = "query")
    })
    @GetMapping("/getConsultationOrderDetail")
    public R<LawyerConsultationOrderVO> getConsultationOrderDetail(@RequestParam(required = false) String lawyerOrderId) {
        log.info("LawyerConsultationOrderController.getConsultationOrderDetail?lawyerOrderId={}",
                lawyerOrderId);
        return R.data(lawyerClientConsultationOrderService.getConsultationOrderDetail(lawyerOrderId));
    }

    @ApiOperation("查询咨询订单信息（律师端）")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "clientUserName", value = "用户姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付,1.待接单 2:进行中, 3:已完成, 4:已取消，5.已退款", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "lawyerId", value = "律师ID", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/getLawyerConsultationOrderInfo")
    public R<Map<String, Object>> getLawyerConsultationOrderInfo(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String clientUserName,
            @RequestParam(required = false) String orderStatus,
            @RequestParam(required = true) String lawyerId) {
        log.info("LawyerConsultationOrderController.getLawyerConsultationOrderInfo?page={},size={},startDate={},endDate={},clientUserName={},orderStatus={},lawyerId={}",
                page, size, startDate, endDate, clientUserName, orderStatus, lawyerId);

        // 参数校验
        if (lawyerId == null || lawyerId.trim().isEmpty()) {
            log.warn("查询咨询订单信息失败：律师ID为空");
            return R.fail("律师ID不能为空");
        }

        // 分页参数校验和规范化
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;

        return R.data(lawyerClientConsultationOrderService.getLawyerConsultationOrderInfo(pageNum, pageSize, startDate, endDate, clientUserName, orderStatus, lawyerId));
    }

    /**
     * 律师确认订单（律师端）
     * <p>
     * 支持两种操作类型：
     * 1. 接单：将订单状态从待接单更新为进行中
     * 2. 取消：将订单状态更新为已取消
     * </p>
     *
     * @param id        订单ID
     * @param actionType 操作类型：1-接单，2-取消
     * @return 操作结果
     */
    @ApiOperation("律师确认订单（律师端）")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "actionType", value = "操作类型：1-接单，2-取消", dataType = "String", paramType = "query", required = true)
    })
    @PutMapping("/confirmOrder")
    public R<Boolean> confirmOrder(@RequestParam(value = "id", required = true) String id,
                                   @RequestParam(value = "actionType", required = true) String actionType) {
        log.info("律师确认订单，订单ID={}, 操作类型={}", id, actionType);
        
        // 参数校验
        if (id == null || id.trim().isEmpty()) {
            log.warn("律师确认订单失败：订单ID为空");
            return R.fail("订单ID不能为空");
        }
        
        if (actionType == null || actionType.trim().isEmpty()) {
            log.warn("律师确认订单失败：操作类型为空");
            return R.fail("操作类型不能为空");
        }
        
        // 操作类型格式校验
        if (!"1".equals(actionType.trim()) && !"2".equals(actionType.trim())) {
            log.warn("律师确认订单失败：操作类型无效，actionType={}", actionType);
            return R.fail("操作类型无效，1-接单，2-取消");
        }
        
        return lawyerClientConsultationOrderService.confirmOrder(id, actionType);
    }

    @ApiOperation("申请退款（律师端）")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "refundReason", value = "退款原因", dataType = "String", paramType = "query", required = true)
    })
    @PostMapping("/requestRefund")
    public R<Boolean> requestRefund(@RequestParam(value = "id", required = true) Integer id,
                                     @RequestParam(value = "refundReason", required = true) String refundReason) {
        log.info("申请退款，订单ID={}, 退款原因={}", id, refundReason);
        if (id == null) {
            log.warn("申请退款失败：订单ID为空");
            return R.fail("订单ID不能为空");
        }
        if (refundReason == null || refundReason.trim().isEmpty()) {
            log.warn("申请退款失败：退款原因为空");
            return R.fail("退款原因不能为空");
        }
        return lawyerClientConsultationOrderService.requestRefund(id, refundReason);
    }


    @ApiOperation("退款申请处理（律师端）")
    @ApiOperationSupport(order = 7)
    @PostMapping("/refundApplyProcess")
    public R<Boolean> refundApplyProcess(@RequestBody LawyerConsultationOrder lawyerConsultationOrder) {
        return lawyerClientConsultationOrderService.refundApplyProcess(lawyerConsultationOrder);
    }

    /**
     * 订单开始计时（律师端）
     * <p>
     * 订单开始计时：
     * 1. 当订单为按时收费，订单状态为进行中时，订单开始计时
     * </p>
     *
     * @param id        订单ID
     * @return 操作结果
     */
    @ApiOperation("订单开始计时（律师端）")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/orderStartTiming")
    public R<Boolean> orderStartTiming(@RequestParam(value = "id", required = true) String id) {
        log.info("订单开始计时，订单ID={}", id);

        // 参数校验
        if (id == null || id.trim().isEmpty()) {
            log.warn("订单开始计时失败：订单ID为空");
            return R.fail("订单ID不能为空");
        }

        return lawyerClientConsultationOrderService.orderStartTiming(id);
    }

    /**
     * 检查订单接单后是否有消息记录（律师端）
     * <p>
     * 根据订单ID查询订单信息，获取律师接单时间、用户ID和律师ID，
     * 然后查询 life_message 表，检查是否存在律师发送给用户的消息记录，
     * 且消息创建时间大于接单时间。
     * </p>
     * <p>
     * 处理流程：
     * 1. 参数校验：订单ID不能为空
     * 2. 查询订单信息：获取接单时间、用户ID、律师ID
     * 3. 查询律师和用户信息：获取律师手机号和用户手机号
     * 4. 构建消息查询条件：sender_id=律师phone，receiver_id=用户phone，created_time>接单时间
     * 5. 查询消息记录：如果存在记录返回true，否则返回false
     * </p>
     *
     * @param id 订单ID，不能为空
     * @return 统一响应结果，true表示有消息记录，false表示无消息记录
     * @author system
     * @since 2025-01-XX
     */
    @ApiOperation("检查订单接单后是否有消息记录（律师端）")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/checkMessageAfterAccept")
    public R<Boolean> checkMessageAfterAccept(@RequestParam(value = "id", required = true) String id) {
        log.info("检查订单接单后是否有消息记录请求开始，订单ID={}", id);

        // 参数校验
        if (id == null || id.trim().isEmpty()) {
            log.warn("检查订单接单后是否有消息记录失败：订单ID为空");
            return R.fail("订单ID不能为空");
        }

        try {
            Boolean hasMessage = lawyerClientConsultationOrderService.checkMessageAfterAccept(id);
            log.info("检查订单接单后是否有消息记录成功，订单ID={}，是否有消息={}", id, hasMessage);
            return R.data(hasMessage);
        } catch (IllegalArgumentException e) {
            log.warn("检查订单接单后是否有消息记录参数校验失败，订单ID={}，错误信息：{}", id, e.getMessage());
            return R.fail(e.getMessage());
        } catch (RuntimeException e) {
            log.error("检查订单接单后是否有消息记录异常，订单ID={}，异常信息：{}", id, e.getMessage(), e);
            return R.fail("检查消息记录失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("检查订单接单后是否有消息记录未知异常，订单ID={}，异常信息：{}", id, e.getMessage(), e);
            return R.fail("检查消息记录失败，请稍后重试");
        }
    }
}

