package com.starry.admin.modules.weichat.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.starry.admin.common.aspect.CustomUserLogin;
import com.starry.admin.common.conf.ThreadLocalRequestDetail;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.task.OverdueOrderHandlerTask;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.module.enums.ClerkRoleStatus;
import com.starry.admin.modules.clerk.module.enums.ListingStatus;
import com.starry.admin.modules.clerk.module.enums.OnboardingStatus;
import com.starry.admin.modules.clerk.service.IPlayClerkCommodityService;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.custom.module.entity.PlayCustomLeaveMsgEntity;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomFollowInfoService;
import com.starry.admin.modules.custom.service.IPlayCustomGiftInfoService;
import com.starry.admin.modules.custom.service.IPlayCustomLeaveMsgService;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.order.module.constant.OrderConstant;
import com.starry.admin.modules.order.module.constant.OrderConstant.OrderActor;
import com.starry.admin.modules.order.module.constant.OrderConstant.RewardType;
import com.starry.admin.modules.order.module.dto.CommodityInfo;
import com.starry.admin.modules.order.module.dto.OrderCreationContext;
import com.starry.admin.modules.order.module.dto.OrderPlacementCommand;
import com.starry.admin.modules.order.module.dto.OrderPlacementResult;
import com.starry.admin.modules.order.module.dto.PaymentInfo;
import com.starry.admin.modules.order.module.dto.RandomOrderRequirements;
import com.starry.admin.modules.order.module.entity.PlayOrderComplaintInfoEntity;
import com.starry.admin.modules.order.module.entity.PlayOrderEvaluateInfoEntity;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.service.IOrderLifecycleService;
import com.starry.admin.modules.order.service.IPlayOrderComplaintInfoService;
import com.starry.admin.modules.order.service.IPlayOrderEvaluateInfoService;
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
import com.starry.admin.modules.shop.module.vo.PlayCommodityInfoVo;
import com.starry.admin.modules.shop.service.*;
import com.starry.admin.modules.weichat.entity.*;
import com.starry.admin.modules.weichat.entity.clerk.PlayClerkUserInfoResultVo;
import com.starry.admin.modules.weichat.entity.costom.PlayCustomHideLevelStateEditVo;
import com.starry.admin.modules.weichat.entity.costom.PlayCustomHideRankingStateEditVo;
import com.starry.admin.modules.weichat.entity.evaluate.PlayCustomOrderEvaluateReturnVo;
import com.starry.admin.modules.weichat.entity.order.PlayCustomOrderDetailsReturnVo;
import com.starry.admin.modules.weichat.entity.order.PlayCustomOrderInfoQueryVo;
import com.starry.admin.modules.weichat.entity.order.PlayCustomOrderListReturnVo;
import com.starry.admin.modules.weichat.entity.order.PlayOrderInfoCommodityAdd;
import com.starry.admin.modules.weichat.entity.user.PlayCustomUserReturnDetailVo;
import com.starry.admin.modules.weichat.service.WxCustomMpService;
import com.starry.admin.modules.weichat.service.WxCustomUserService;
import com.starry.admin.modules.weichat.service.WxGiftOrderService;
import com.starry.admin.utils.MoneyUtils;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.result.R;
import com.starry.common.utils.ConvertUtil;
import com.starry.common.utils.IdUtils;
import com.starry.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author admin
 */
@Api(tags = "微信顾客接口", description = "微信端顾客相关接口")
@Slf4j
@RestController
@RequestMapping("/wx/custom/")
public class WxCustomController {

    @Resource
    private IPlayCustomUserInfoService customUserInfoService;

    @Resource
    private IPlayClerkUserInfoService clerkUserInfoService;

    @Resource
    private IPlayGiftInfoService giftInfoService;

    @Resource
    private IPlayCommodityInfoService playCommodityInfoService;

    @Resource
    private IPlayCustomFollowInfoService playCustomFollowInfoService;

    @Resource
    private IPlayClerkCommodityService playClerkCommodityService;

    @Resource
    private WxCustomUserService customUserService;

    @Resource
    private IPlayOrderInfoService playOrderInfoService;

    @Resource
    private IOrderLifecycleService orderLifecycleService;

    @Resource
    private IPlayCustomLeaveMsgService playCustomLeaveMsgService;

    @Resource
    private IPlayOrderComplaintInfoService playOrderComplaintInfoService;

    @Resource
    private IPlayOrderEvaluateInfoService playOrderEvaluateInfoService;

    @Resource
    private IPlayCustomGiftInfoService playCustomGiftInfoService;

    @Resource
    private IPlayClerkGiftInfoService playClerkGiftInfoService;

    @Resource
    private IPlayCouponInfoService playCouponInfoService;
    @Resource
    private IPlayCouponDetailsService couponDetailsService;

    @Resource
    private WxCustomMpService wxCustomMpService;

    @Resource
    private WxGiftOrderService wxGiftOrderService;

    @Resource
    OverdueOrderHandlerTask overdueOrderHandlerTask;

    /**
     * 根据店员ID查询店员详细信息
     *
     * @param id 店员ID
     * @return 店员详细信息
     */
    @ApiOperation(value = "查询店员详细信息", notes = "根据店员ID查询店员的详细信息")
    @ApiImplicitParam(name = "id", value = "店员ID", required = true, dataType = "String", paramType = "query")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = PlayClerkUserInfoResultVo.class)})
    @GetMapping("/queryClerkDetailedById")
    public R queryClerkDetailedById(@RequestParam("id") String id) {
        String loginUserId = customUserService.getLoginUserId();
        PlayClerkUserInfoResultVo vo = clerkUserInfoService.buildCustomerDetail(id,
                StringUtils.isNotEmpty(loginUserId) ? loginUserId : "");
        return R.ok(vo);
    }

    /**
     * 顾客本人刷新头像
     */
    @ApiOperation(value = "刷新顾客头像", notes = "刷新当前登录顾客的头像信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @CustomUserLogin
    @GetMapping("/refreshAvatar")
    public R refreshAvatar() {
        return R.ok("");
    }

    /**
     * 根据顾客ID查询当前顾客详细信息
     */
    @ApiOperation(value = "查询顾客详细信息", notes = "查询当前登录顾客的详细信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = PlayCustomUserReturnDetailVo.class)})
    @CustomUserLogin
    @GetMapping("/queryById")
    public R queryById() {
        String userId = ThreadLocalRequestDetail.getCustomUserInfo().getId();
        PlayCustomUserInfoEntity customUserInfo = customUserInfoService.selectById(userId);
        PlayCustomUserReturnDetailVo vo = ConvertUtil.entityToVo(customUserInfo, PlayCustomUserReturnDetailVo.class);
        PlayClerkUserInfoEntity clerkUserInfo = clerkUserInfoService.selectByOpenid(customUserInfo.getOpenid());
        if (clerkUserInfo != null) {
            vo.setClerkState("1");
        }
        return R.ok(vo);
    }

    /**
     * 顾客本人修改隐藏等级状态
     */
    @ApiOperation(value = "修改隐藏等级状态", notes = "顾客修改自己的隐藏等级状态")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @CustomUserLogin
    @PostMapping("/updateHideLevelState")
    public R updateHideLevelState(@ApiParam(value = "隐藏等级状态信息", required = true) @Validated @RequestBody PlayCustomHideLevelStateEditVo vo) {
        vo.setId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        PlayCustomUserInfoEntity entity = new PlayCustomUserInfoEntity();
        BeanUtils.copyProperties(vo, entity);
        customUserInfoService.update(entity);
        return R.ok("成功");
    }

    /**
     * 顾客本人修改隐藏排名状态
     */
    @ApiOperation(value = "修改隐藏排名状态", notes = "顾客修改自己的隐藏排名状态")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @CustomUserLogin
    @PostMapping("/updateHideRankingState")
    public R updateHideRankingState(@ApiParam(value = "隐藏排名状态信息", required = true) @Validated @RequestBody PlayCustomHideRankingStateEditVo vo) {
        vo.setId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        PlayCustomUserInfoEntity entity = new PlayCustomUserInfoEntity();
        BeanUtils.copyProperties(vo, entity);
        customUserInfoService.update(entity);
        return R.ok("成功");
    }

    /**
     * 打赏店员-打赏余额
     */
    @ApiOperation(value = "打赏店员", notes = "使用余额打赏店员")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 998, message = "余额不足")})
    @CustomUserLogin
    @PostMapping("/order/reward")
    public R rewardToOrder(@ApiParam(value = "打赏信息", required = true) @Validated @RequestBody PlayOrderInfoRewardAdd vo) {
        MoneyUtils.verificationTypeIsNormal(vo.getMoney());
        String userId = ThreadLocalRequestDetail.getCustomUserInfo().getId();
        String orderId = IdUtils.getUuid();
        // 记录订单信息
        OrderCreationContext orderRequest = OrderCreationContext.builder()
                .orderId(orderId)
                .orderNo(playOrderInfoService.getOrderNo())
                .orderStatus(OrderConstant.OrderStatus.COMPLETED)
                .orderType(OrderConstant.OrderType.NORMAL)
                .placeType(OrderConstant.PlaceType.REWARD)
                .rewardType(RewardType.BALANCE)
                .isFirstOrder(false)
                .creatorActor(OrderActor.CUSTOMER)
                .creatorId(userId)
                .commodityInfo(CommodityInfo.builder()
                        .commodityId("")
                        .commodityType(OrderConstant.CommodityType.GIFT)
                        .commodityPrice(BigDecimal.ZERO)
                        .serviceDuration("")
                        .commodityName("")
                        .commodityNumber("0")
                        .build())
                .paymentInfo(PaymentInfo.builder()
                        .orderMoney(new BigDecimal(vo.getMoney()))
                        .finalAmount(new BigDecimal(vo.getMoney()))
                        .discountAmount(BigDecimal.ZERO)
                        .couponIds(new ArrayList<>())
                        .build())
                .purchaserBy(userId)
                .acceptBy(vo.getClerkId())
                .weiChatCode(vo.getWeiChatCode())
                .remark(vo.getRemark())
                .build();
        orderLifecycleService.placeOrder(OrderPlacementCommand.builder()
                .orderContext(orderRequest)
                .balanceOperationAction("打赏")
                .build());
        return R.ok("成功");
    }

    /**
     * 顾客下单-赠送礼物
     **/
    @ApiOperation(value = "赠送礼物", notes = "顾客向店员赠送礼物")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 998, message = "余额不足")})
    @CustomUserLogin
    @PostMapping("/order/gift")
    public R giftToOdder(@ApiParam(value = "礼物信息", required = true) @Validated @RequestBody PlayOrderInfoGiftAdd vo) {
        String orderId = wxGiftOrderService.createGiftOrder(vo);
        return R.ok().message("成功").data(orderId);
    }

    /**
     * 新增指定订单
     *
     * @param vo 指定订单查询对象
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 16:31
     **/
    @ApiOperation(value = "商品下单", notes = "顾客购买店员服务商品")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 998, message = "余额不足"), @ApiResponse(code = 500, message = "请求参数异常")})
    @CustomUserLogin
    @PostMapping("/order/commodity")
    public R commodityToOrdder(@ApiParam(value = "商品订单信息", required = true) @Validated @RequestBody PlayOrderInfoCommodityAdd vo) {
        String customId = ThreadLocalRequestDetail.getCustomUserInfo().getId();
        PlayClerkUserInfoEntity clerkUserInfo = clerkUserInfoService.selectById(vo.getClerkId());

        PlayCommodityInfoVo commodityInfo = playCommodityInfoService.queryCommodityInfo(vo.getCommodityId(), clerkUserInfo.getLevelId());

        String orderId = IdUtils.getUuid();
        String orderNo = playOrderInfoService.getOrderNo();
        // 记录订单信息
        OrderCreationContext orderRequest = OrderCreationContext.builder()
                .orderId(orderId)
                .orderNo(orderNo)
                .orderStatus(OrderConstant.OrderStatus.PENDING)
                .orderType(OrderConstant.OrderType.NORMAL)
                .placeType(OrderConstant.PlaceType.SPECIFIED)
                .rewardType(RewardType.NOT_APPLICABLE)
                .isFirstOrder(true)
                .creatorActor(OrderActor.CUSTOMER)
                .creatorId(customId)
                .commodityInfo(CommodityInfo.builder()
                        .commodityId(commodityInfo.getCommodityId())
                        .commodityType(OrderConstant.CommodityType.SERVICE)
                        .commodityPrice(commodityInfo.getCommodityPrice())
                        .serviceDuration(commodityInfo.getServiceDuration())
                        .commodityName(commodityInfo.getCommodityName())
                        .commodityNumber(String.valueOf(vo.getCommodityQuantity()))
                        .build())
                .paymentInfo(PaymentInfo.builder()
                        .orderMoney(BigDecimal.ZERO)
                        .finalAmount(BigDecimal.ZERO)
                        .discountAmount(BigDecimal.ZERO)
                        .couponIds(Collections.emptyList())
                        .build())
                .purchaserBy(customId)
                .acceptBy(clerkUserInfo.getId())
                .weiChatCode(vo.getWeiChatCode())
                .remark(vo.getRemark())
                .build();
        List<String> couponIds = CollectionUtils.isEmpty(vo.getCouponIds()) ? Collections.emptyList() : vo.getCouponIds();
        OrderPlacementCommand command = OrderPlacementCommand.builder()
                .orderContext(orderRequest)
                .balanceOperationAction("下单-指定单")
                .pricingInput(OrderPlacementCommand.PricingInput.builder()
                        .unitPrice(commodityInfo.getCommodityPrice())
                        .quantity(vo.getCommodityQuantity())
                        .couponIds(couponIds)
                        .commodityId(commodityInfo.getCommodityId())
                        .placeType(OrderConstant.PlaceType.SPECIFIED)
                        .build())
                .build();
        OrderPlacementResult result = orderLifecycleService.placeOrder(command);
        PlayOrderInfoEntity order = result.getOrder();
        BigDecimal netAmount = result.getAmountBreakdown().getNetAmount();
        // 发送通知给店员
        wxCustomMpService.sendCreateOrderMessage(
                clerkUserInfo.getTenantId(),
                clerkUserInfo.getOpenid(),
                orderNo,
                netAmount.toString(),
                commodityInfo.getCommodityName(),
                order.getId(),
                order.getPlaceType(),
                order.getRewardType());
        return R.ok("成功");
    }

    /**
     * 新增随机订单
     *
     * @param vo 随机单创建对象
     * @return R
     */
    @CustomUserLogin
    @PostMapping("/order/random")
    public R randomToOrdder(@Validated @RequestBody PlayOrderInfoRandomAdd vo) {
        // 验证当前顾客余额是否充足
        String customId = ThreadLocalRequestDetail.getCustomUserInfo().getId();
        PlayCommodityInfoVo commodityInfo = playCommodityInfoService.queryCommodityInfo(vo.getCommodityId(), vo.getLevelId());
        String orderId = IdUtils.getUuid();
        String orderNo = playOrderInfoService.getOrderNo();
        // 记录订单信息
        OrderCreationContext orderRequest = OrderCreationContext.builder()
                .orderId(orderId)
                .orderNo(orderNo)
                .orderStatus(OrderConstant.OrderStatus.PENDING)
                .orderType(OrderConstant.OrderType.NORMAL)
                .placeType(OrderConstant.PlaceType.RANDOM)
                .rewardType(RewardType.NOT_APPLICABLE)
                .isFirstOrder(true)
                .creatorActor(OrderActor.CUSTOMER)
                .creatorId(customId)
                .commodityInfo(CommodityInfo.builder()
                        .commodityId(commodityInfo.getCommodityId())
                        .commodityType(OrderConstant.CommodityType.SERVICE)
                        .commodityPrice(commodityInfo.getCommodityPrice())
                        .serviceDuration(commodityInfo.getServiceDuration())
                        .commodityName(commodityInfo.getCommodityName())
                        .commodityNumber(String.valueOf(vo.getCommodityQuantity()))
                        .build())
                .paymentInfo(PaymentInfo.builder()
                        .orderMoney(BigDecimal.ZERO)
                        .finalAmount(BigDecimal.ZERO)
                        .discountAmount(BigDecimal.ZERO)
                        .couponIds(Collections.emptyList())
                        .build())
                .purchaserBy(customId)
                .weiChatCode(vo.getWeiChatCode())
                .remark(vo.getRemark())
                .randomOrderRequirements(RandomOrderRequirements.builder()
                        .clerkGender(OrderConstant.Gender.fromCode(vo.getSex()))
                        .clerkLevelId(vo.getLevelId())
                        .excludeHistory(vo.getExcludeHistory())
                        .build())
                .build();
        List<String> couponIds = CollectionUtils.isEmpty(vo.getCouponIds()) ? Collections.emptyList() : vo.getCouponIds();
        OrderPlacementCommand command = OrderPlacementCommand.builder()
                .orderContext(orderRequest)
                .balanceOperationAction("下单-随机单")
                .pricingInput(OrderPlacementCommand.PricingInput.builder()
                        .unitPrice(commodityInfo.getCommodityPrice())
                        .quantity(vo.getCommodityQuantity())
                        .couponIds(couponIds)
                        .commodityId(commodityInfo.getCommodityId())
                        .placeType(OrderConstant.PlaceType.RANDOM)
                        .build())
                .build();
        OrderPlacementResult result = orderLifecycleService.placeOrder(command);
        PlayOrderInfoEntity order = result.getOrder();
        BigDecimal netAmount = result.getAmountBreakdown().getNetAmount();
        // 给全部店员发送通知
        List<PlayClerkUserInfoEntity> clerkList = clerkUserInfoService.list(Wrappers.lambdaQuery(PlayClerkUserInfoEntity.class)
                .isNotNull(PlayClerkUserInfoEntity::getOpenid)
                .eq(PlayClerkUserInfoEntity::getClerkState, ClerkRoleStatus.CLERK.getCode())
                .eq(PlayClerkUserInfoEntity::getOnboardingState, OnboardingStatus.ACTIVE.getCode())
                .eq(PlayClerkUserInfoEntity::getListingState, ListingStatus.LISTED.getCode())
                .eq(PlayClerkUserInfoEntity::getOnlineState, "1")
                .eq(PlayClerkUserInfoEntity::getSex, vo.getSex()));
        wxCustomMpService.sendCreateOrderMessageBatch(
                clerkList,
                orderNo,
                netAmount.toString(),
                commodityInfo.getCommodityName(),
                order.getId(),
                order.getPlaceType(),
                order.getRewardType());
        // 记录订单，指定指定未接单后，进行退款处理
        overdueOrderHandlerTask.enqueue(orderId + "_" + SecurityUtils.getTenantId());
        // 下单成功后，先根据用户条件进行随机分配
        return R.ok("下单成功");
    }

    /**
     * 顾客分页查询本人订单列表
     *
     * @param vo 订单列表分页查询对象
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/order/queryByPage")
    public R queryOrderByPage(@Validated @RequestBody PlayCustomOrderInfoQueryVo vo) {
        vo.setPurchaserBy(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        IPage<PlayCustomOrderListReturnVo> iPage = playOrderInfoService.customSelectOrderInfoByPage(vo);
        return R.ok(iPage);
    }

    /**
     * 顾客分页查询本人订单详细信息
     *
     * @param id 订单ID
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @GetMapping("/order/queryById")
    public R queryById(@RequestParam("id") String id) {
        PlayCustomOrderDetailsReturnVo vo = playOrderInfoService.customSelectOrderDetails(ThreadLocalRequestDetail.getCustomUserInfo().getId(), id);
        return R.ok(vo);
    }

    /**
     * 顾客-完成订单
     *
     * @param id 订单ID
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @GetMapping("/order/end")
    public R endOrder(@RequestParam("id") String id) {
        playOrderInfoService.updateStateTo23("0", ThreadLocalRequestDetail.getCustomUserInfo().getId(), "3", id);
        return R.ok("成功");
    }

    /**
     * 顾客取消订单
     *
     * @param vo 订单取消对象
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/order/cancellation")
    public R cancellationOrder(@Validated @RequestBody PlayOrderCancellationVo vo) {
        playOrderInfoService.updateStateTo4("0", ThreadLocalRequestDetail.getCustomUserInfo().getId(), vo.getOrderId(), vo.getRefundReason(), vo.getImages());
        return R.ok("取消成功");
    }

    /**
     * 新增订单评价信息
     *
     * @param vo 订单评价信息实体
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/order/evaluate/add")
    public R addOrderEvaluate(@Validated @RequestBody PlayOrderEvaluateAddVo vo) {
        vo.setCustomId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        PlayOrderInfoEntity orderInfo = playOrderInfoService.selectOrderInfoById(vo.getOrderId());
        if (!orderInfo.getPurchaserBy().equals(vo.getCustomId())) {
            throw new CustomException("只有下单人才能评价");
        }
        PlayOrderEvaluateInfoEntity entity = ConvertUtil.entityToVo(vo, PlayOrderEvaluateInfoEntity.class);
        playOrderEvaluateInfoService.create(entity);
        return R.ok("评价成功");
    }

    /**
     * 根据订单ID查询当前顾客对当前人的评价
     *
     * @param orderId 订单ID
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @GetMapping("/order/evaluate/queryByOrderId")
    public R addOrderEvaluateByOrderId(@RequestParam("id") String orderId) {
        PlayOrderEvaluateInfoEntity orderEvaluateInfo = playOrderEvaluateInfoService.queryCustomToOrderEvaluateInfo(ThreadLocalRequestDetail.getCustomUserInfo().getId(), orderId);
        if (orderEvaluateInfo == null) {
            throw new CustomException("当前订单未评价");
        }
        return R.ok(ConvertUtil.entityToVo(orderEvaluateInfo, PlayCustomOrderEvaluateReturnVo.class));
    }

    /**
     * 新增订单投诉信息
     *
     * @param vo 订单评价信息实体
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/order/complaint/add")
    public R addOrderComplaint(@Validated @RequestBody PlayOrderComplaintAddVo vo) {
        vo.setCustomId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        PlayOrderInfoEntity orderInfo = playOrderInfoService.selectOrderInfoById(vo.getOrderId());
        if (!orderInfo.getPurchaserBy().equals(vo.getCustomId())) {
            throw new CustomException("只有下单人才能投诉");
        }
        PlayOrderComplaintInfoEntity entity = ConvertUtil.entityToVo(vo, PlayOrderComplaintInfoEntity.class);
        playOrderComplaintInfoService.create(entity);
        return R.ok("新增成功");
    }

    /**
     * 顾客新增留言
     *
     * @param vo 顾客新增留言对象
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/leave/add")
    public R cancellationOrder(@Validated @RequestBody PlayCustomLeaveAddVo vo) {
        vo.setCustomId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        PlayCustomLeaveMsgEntity entity = ConvertUtil.entityToVo(vo, PlayCustomLeaveMsgEntity.class);
        entity.setMsgTime(new Date());
        playCustomLeaveMsgService.create(entity);
        return R.ok("取消成功");
    }

    /**
     * 查询当前顾客是否允许留言
     *
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @GetMapping("/leave/queryPermission")
    public R queryLeavePermission() {
        // 不允许留言的原因，如果原因为空，说明允许留言
        String noMessagesAllowedReason = playCustomLeaveMsgService.queryNoMessagesAllowedReason(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        if (StringUtils.isEmpty(noMessagesAllowedReason)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("permission", true);
            jsonObject.put("msg", "");
            return R.ok(jsonObject);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("permission", false);
            jsonObject.put("msg", noMessagesAllowedReason);
            return R.ok(jsonObject);
        }
    }

    /**
     * 顾客修改对陪玩的关注状态
     *
     * @param vo 陪玩的关注状态对象
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/followState/update")
    public R followStateUpdate(@Validated @RequestBody PlayClerkFollowStateUpdate vo) {
        PlayClerkUserInfoEntity clerkUserInfo = clerkUserInfoService.selectById(vo.getClerkId());
        playCustomFollowInfoService.updateFollowState(ThreadLocalRequestDetail.getCustomUserInfo().getId(), clerkUserInfo.getId(), vo.getFollowState());
        return R.ok("修改成功");
    }

    /**
     * 顾客查询已关注陪聊列表
     *
     * @param vo 陪玩的关注状态对象
     * @return com.starry.common.result.R
     * @author admin
     * @since 2024/5/8 15:57
     **/
    @CustomUserLogin
    @PostMapping("/follow/queryByPage")
    public R followQueryByPage(@Validated @RequestBody PlayClerkFollowQueryVo vo) {
        vo.setCustomId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        IPage<PlayClerkFollowReturnVo> iPage = playCustomFollowInfoService.selectByPage(vo);
        return R.ok(iPage);
    }

}
