package shop.alien.store.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerConsultationOrder;
import shop.alien.entity.store.dto.LawyerConsultationOrderDto;
import shop.alien.entity.store.dto.PayStatusRequest;
import shop.alien.entity.store.vo.LawyerConsultationOrderVO;
import shop.alien.store.service.LawyerConsultationOrderService;
import shop.alien.store.service.OrderExpirationService;
import shop.alien.util.myBaticsPlus.QueryBuilder;

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

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

    private final LawyerConsultationOrderService consultationOrderService;
    private final OrderExpirationService orderExpirationService;

    @ApiOperation("分页查询咨询订单列表（支持按律师姓名关联查询，返回结果包含律师信息）")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "orderNumber", value = "订单编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerName", value = "律师姓名（支持模糊查询，关联查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付, 1:已支付, 2:进行中, 3:已完成, 4:已取消", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getConsultationOrderList")
    public R<IPage<LawyerConsultationOrderVO>> getConsultationOrderList(@RequestParam(defaultValue = "1") int page,
                                                                 @RequestParam(defaultValue = "10") int size,
                                                                 @RequestParam(required = false) String orderNumber,
                                                                 @RequestParam(required = false) Integer clientUserId,
                                                                 @RequestParam(required = false) Integer lawyerUserId,
                                                                 @RequestParam(required = false) String lawyerName,
                                                                 @RequestParam(required = false) Integer orderStatus) {
        log.info("LawyerConsultationOrderController.getConsultationOrderList?page={},size={},orderNumber={},clientUserId={},lawyerUserId={},lawyerName={},orderStatus={}",
                page, size, orderNumber, clientUserId, lawyerUserId, lawyerName, orderStatus);
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;
        return consultationOrderService.getConsultationOrderList(pageNum, pageSize, orderNumber, clientUserId, lawyerUserId, lawyerName, orderStatus);
    }

    @ApiOperation("新增咨询订单")
    @ApiOperationSupport(order = 2)
    @PostMapping("/addConsultationOrder")
    public R<LawyerConsultationOrder> addConsultationOrder(@RequestBody LawyerConsultationOrder consultationOrder) {
        log.info("LawyerConsultationOrderController.addConsultationOrder?consultationOrder={}", consultationOrder);
        return consultationOrderService.addConsultationOrder(consultationOrder);
    }

    @ApiOperation("编辑咨询订单")
    @ApiOperationSupport(order = 3)
    @PostMapping("/editConsultationOrder")
    public R<LawyerConsultationOrder> editConsultationOrder(@RequestBody LawyerConsultationOrder consultationOrder) {
        log.info("开始编辑咨询订单，订单ID={}, 订单编号={}", 
                consultationOrder != null ? consultationOrder.getId() : null,
                consultationOrder != null ? consultationOrder.getOrderNumber() : null);
        
        // 参数校验：订单ID不能为空
        if (consultationOrder == null || consultationOrder.getId() == null) {
            log.warn("编辑咨询订单失败：订单ID为空");
            return R.fail("订单ID不能为空");
        }
        
        // 记录修改前的关键信息
        Integer orderId = consultationOrder.getId();
        Integer newOrderStatus = consultationOrder.getOrderStatus();
        Integer newPaymentStatus = consultationOrder.getPaymentStatus();
        log.info("编辑咨询订单，订单ID={}, 新订单状态={}, 新支付状态={}", 
                orderId, newOrderStatus, newPaymentStatus);
        
        R<LawyerConsultationOrder> result = consultationOrderService.editConsultationOrder(consultationOrder);
        
        if (result.isSuccess()) {
            log.info("编辑咨询订单成功，订单ID={}, 订单编号={}", 
                    orderId, consultationOrder.getOrderNumber());
        } else {
            log.warn("编辑咨询订单失败，订单ID={}, 失败原因={}", 
                    orderId, result.getMsg());
        }
        
        return result;
    }

    @ApiOperation("删除咨询订单")
    @ApiOperationSupport(order = 4)
    @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 consultationOrderService.deleteConsultationOrder(id);
    }

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

    @ApiOperation("通用列表查询")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderNumber", value = "订单编号（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "problemScenarioId", value = "法律问题场景ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付, 1:已支付, 2:进行中, 3:已完成, 4:已取消", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "paymentStatus", value = "支付状态, 0:未支付, 1:已支付", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getList")
    public R<List<LawyerConsultationOrder>> getList(@ModelAttribute LawyerConsultationOrder consultationOrder) {
        log.info("LawyerConsultationOrderController.getList?consultationOrder={}", consultationOrder);
        List<LawyerConsultationOrder> list = QueryBuilder.of(consultationOrder)
                .likeFields("orderNumber")  // 订单编号支持模糊查询
                .build()
                .list(consultationOrderService);
        return R.data(list);
    }

    @ApiOperation("通用分页查询")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderNumber", value = "订单编号（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "problemScenarioId", value = "法律问题场景ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付, 1:已支付, 2:进行中, 3:已完成, 4:已取消", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "paymentStatus", value = "支付状态, 0:未支付, 1:已支付", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPage")
    public R<IPage<LawyerConsultationOrder>> getPage(@ModelAttribute LawyerConsultationOrder consultationOrder,
                                                      @RequestParam(defaultValue = "1") int page,
                                                      @RequestParam(defaultValue = "10") int size) {
        log.info("LawyerConsultationOrderController.getPage?consultationOrder={},page={},size={}", consultationOrder, page, size);
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;
        IPage<LawyerConsultationOrder> pageResult = QueryBuilder.of(consultationOrder)
                .likeFields("orderNumber")  // 订单编号支持模糊查询
                .page(pageNum, pageSize)
                .build()
                .page(consultationOrderService);
        return R.data(pageResult);
    }

    /*@ApiOperation("开始咨询律师")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawyerId", value = "律师ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "question", value = "咨询问题（可选）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sessionId", value = "关联的AI会话ID（可选）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID（可选）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "problemScenarioId", value = "法律问题场景ID（可选）", dataType = "Integer", paramType = "query")
    })
    @PostMapping("/start")
    public R<Map<String, Object>> startConsultation(
            @RequestParam Integer lawyerId,
            @RequestParam(required = false) String question,
            @RequestParam(required = false) String sessionId,
            @RequestParam(required = false) Integer clientUserId,
            @RequestParam(required = false) Integer problemScenarioId) {
        log.info("LawyerConsultationOrderController.startConsultation?lawyerId={},question={},sessionId={},clientUserId={},problemScenarioId={}",
                lawyerId, question, sessionId, clientUserId, problemScenarioId);
        return consultationOrderService.startConsultation(lawyerId, question, sessionId, clientUserId, problemScenarioId);
    }*/



    @ApiOperation("立即咨询")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "problemScenarioId", value = "法律问题场景ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "problemDescription", value = "问题描述", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "alipayNo", value = "支付宝订单编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStr", value = "支付宝订单字符串", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "lawyerName", value = "律师姓名（支持模糊查询，关联查询）", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "consultationFee", value = "咨询费用,单位分", dataType = "Integer", paramType = "query"),
//            @ApiImplicitParam(name = "startTime", value = "咨询开始时间", dataType = "Date", paramType = "query"),
//            @ApiImplicitParam(name = "endTime", value = "咨询结束时间", dataType = "Date", paramType = "query"),
//            @ApiImplicitParam(name = "validityPeriod", value = "订单有效期", dataType = "Date", paramType = "query"),
//            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付, 1:已支付, 2:进行中, 3:已完成, 4:已取消", dataType = "Integer", paramType = "query"),
//            @ApiImplicitParam(name = "paymentStatus", value = "支付状态, 0:未支付, 1:已支付", dataType = "Integer", paramType = "query"),
    })
    @PostMapping("/consultNow")
    public R<LawyerConsultationOrderDto> startConsultation(@RequestBody LawyerConsultationOrder lawyerConsultationOrder) {
        log.info("LawyerConsultationOrderController.consultNow?lawyerConsultationOrder={}", lawyerConsultationOrder);
        //创建订单时，存储redis中，设置过期时间
        R<LawyerConsultationOrderDto> layerConsultationOrderDto = consultationOrderService.consultNow(lawyerConsultationOrder);
        if (R.isSuccess(layerConsultationOrderDto) && layerConsultationOrderDto.getData()!=null){
            orderExpirationService.setOrderPaymentTimeout(layerConsultationOrderDto.getData().getOrderNumber(), 60 * 30);
        }

        return layerConsultationOrderDto;
    }


    @ApiOperation("是否支付成功更改订单表状态")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "订单编号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付, 1:已支付, 2:进行中, 3:已完成, 4:已取消", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "paymentStatus", value = "支付状态, 0:未支付, 1:已支付", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/payStatus")
    public R<LawyerConsultationOrderDto> payStatus(@RequestBody PayStatusRequest request) {
        log.info("LawyerConsultationOrderController.payStatus?orderNumber={},paymentStatus={},orderStatus={}",
                request.getOrderNumber(), request.getPaymentStatus(), request.getOrderStatus());
        //如果订单已支付，关闭redis中的记时
        if (request.getPaymentStatus() != null && request.getPaymentStatus() == 1){
            orderExpirationService.cancelOrderPaymentTimeout(request.getOrderNumber());
        }
        return consultationOrderService.payStatus(request);
    }

    @ApiOperation("查询根据用户id查询订单")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "客户端用户ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderStatus", value = "订单状态, 0:待支付, 1:已支付, 2:进行中, 3:已完成, 4:已取消", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "lawyerName", value = "律师姓名（支持模糊查询，关联查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getConsultationOrderListById")
    public R<IPage<LawyerConsultationOrderVO>> getConsultationOrderListById(@RequestParam(defaultValue = "1") int page,
                                                                        @RequestParam(defaultValue = "10") int size,
                                                                        @RequestParam(required = false) String userId,
                                                                        @RequestParam(required = false) String orderStatus,
                                                                        @RequestParam(required = false) String lawyerName) {
        log.info("LawyerConsultationOrderController.getConsultationOrderListById?pageNum={},pageSize={},userId={},orderStatus={},lawyerName={}",
                page, size, userId, orderStatus, lawyerName);
        return consultationOrderService.getConsultationOrderListById(page, size, userId, orderStatus, lawyerName);
    }

    @ApiOperation("查询订单详情")
    @ApiOperationSupport(order = 12)
    @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(consultationOrderService.getConsultationOrderDetail(lawyerOrderId));
    }

    @ApiOperation("取消律师咨询订单")
    @ApiOperationSupport(order = 13)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", dataType = "String", paramType = "query", required = true)
    })
    @PostMapping("/cancelOrder")
    public R<Boolean> cancelOrder(@RequestParam(value = "id", required = true) String id) {
        log.info("LawyerConsultationOrderController.cancelOrder?id={}", id);
        return R.data(consultationOrderService.cancelOrder(id));
    }

    @ApiOperation("查询咨询订单（律师端）")
    @ApiOperationSupport(order = 14)
    @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 = "lawyerId", value = "律师ID", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/getLawyerConsultationOrderList")
    public R<IPage<LawyerConsultationOrderVO>> getLawyerConsultationOrderList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = true) String lawyerId) {
        log.info("查询咨询订单（律师端）- page={}, size={}, startDate={}, endDate={}, lawyerId={}",
                page, size, startDate, endDate, lawyerId);

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

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

        return consultationOrderService.getLawyerConsultationOrderList(pageNum, pageSize, startDate, endDate, lawyerId);
    }

    @ApiOperation("创建订单前的校验")
    @ApiOperationSupport(order = 15)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "lawyerUserId", value = "律师用户ID", dataType = "Integer", paramType = "query", required = true),
    })
    @PostMapping("/checkOrder")
    public R<Map<String, String>> checkOrder(@RequestParam Integer clientUserId, @RequestParam Integer lawyerUserId) {
        log.info("LawyerConsultationOrderController.checkOrder?clientUserId={},lawyerUserId{}", clientUserId, lawyerUserId);
        return consultationOrderService.checkOrder(clientUserId, lawyerUserId);
    }


}

