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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starry.admin.common.aspect.ClerkUserLogin;
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.modules.order.module.constant.OrderConstant;
import com.starry.admin.modules.order.module.entity.PlayOrderContinueInfoEntity;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.module.vo.PlayOrderContinueQueryVo;
import com.starry.admin.modules.order.module.vo.PlayOrderContinueReturnVo;
import com.starry.admin.modules.order.module.vo.PlayOrderDetailsReturnVo;
import com.starry.admin.modules.order.module.vo.PlayOrderReviewStateEditVo;
import com.starry.admin.modules.order.service.IPlayOrderContinueInfoService;
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
import com.starry.admin.modules.weichat.entity.order.PlayOrderInfoContinueAdd;
import com.starry.admin.modules.weichat.entity.order.PlayOrderInfoContinueQueryVo;
import com.starry.admin.modules.weichat.entity.order.PlayOrderInfoRandomQueryVo;
import com.starry.admin.modules.weichat.entity.order.PlayRewardOrderQueryVo;
import com.starry.common.result.R;
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.time.LocalDateTime;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 订单处理
 *
 * @author admin
 * @since 2024/5/25 下午2:45
 **/
@Api(tags = "微信订单接口", description = "微信端订单相关接口")
@Slf4j
@RestController
@RequestMapping("/wx/order")
public class WxOrderInfoController {

    @Resource
    private IPlayOrderInfoService playOrderInfoService;

    @Resource
    private IPlayOrderContinueInfoService playOrderContinueInfoService;

    /**
     * 续单申请-店员发起
     *
     * @param vo 续单申请提交对象
     */
    @ApiOperation(value = "店员申请续单", notes = "店员为当前订单发起续单申请")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "非本人订单;无法续单"),
            @ApiResponse(code = 500, message = "同一场订单只能续单一次")})
    @ClerkUserLogin
    @PostMapping("/clerk/continue")
    public R continueToOrdder(
            @ApiParam(value = "续单信息", required = true) @Validated @RequestBody PlayOrderInfoContinueAdd vo) {
        PlayOrderInfoEntity entity = playOrderInfoService.selectOrderInfoById(vo.getOrderId());
        if (!entity.getAcceptBy().equals(ThreadLocalRequestDetail.getClerkUserInfo().getId())) {
            throw new CustomException("非本人订单;无法续单");
        }

        PlayOrderContinueInfoEntity orderContinueInfo = playOrderContinueInfoService.selectPlayOrderId(vo.getOrderId());
        if (orderContinueInfo != null) {
            throw new CustomException("同一场订单只能续单一次");
        }
        PlayOrderContinueInfoEntity orderContinueInfoEntity = new PlayOrderContinueInfoEntity();
        orderContinueInfoEntity.setOrderId(entity.getId());
        orderContinueInfoEntity.setOrderNo(entity.getOrderNo());
        orderContinueInfoEntity.setCustomId(entity.getPurchaserBy());
        orderContinueInfoEntity.setClerkId(entity.getAcceptBy());
        orderContinueInfoEntity.setPlaceType(entity.getPlaceType());
        orderContinueInfoEntity.setOrderMoney(entity.getOrderMoney());
        orderContinueInfoEntity.setFinalAmount(entity.getFinalAmount());
        orderContinueInfoEntity.setContinueMsg(entity.getRemark());
        orderContinueInfoEntity.setReviewedRequired("1");
        orderContinueInfoEntity.setReviewedState("0");
        orderContinueInfoEntity.setImages(vo.getImages());
        orderContinueInfoEntity.setContinueTime(LocalDateTime.now());
        playOrderContinueInfoService.create(orderContinueInfoEntity);
        return R.ok("下单成功");
    }

    /**
     * 店员查询随机单列表
     *
     * @param vo 随机单列表查询对象
     * @return 订单列表
     */
    @ApiOperation(value = "查询随机单列表", notes = "店员查询可接的随机订单列表")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ClerkUserLogin
    @PostMapping("/clerk/selectRandomOrderByPage")
    public R selectUnacceptedOrderByPage(
            @ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayOrderInfoRandomQueryVo vo) {
        return R.ok(
                playOrderInfoService.selectRandomOrderByPage(vo, ThreadLocalRequestDetail.getClerkUserInfo().getId()));
    }

    /**
     * 店员查询随机单详情
     *
     * @param id 订单ID
     * @return 订单列表
     */
    @ApiOperation(value = "查询随机单详情", notes = "店员查询随机订单的详细信息")
    @ApiImplicitParam(name = "id", value = "订单ID", required = true, dataType = "String", paramType = "query")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = PlayOrderDetailsReturnVo.class),
            @ApiResponse(code = 500, message = "订单不存在")})
    @ClerkUserLogin
    @GetMapping("/clerk/selectRandomOrderById")
    public R selectUnacceptedOrderByPage(@RequestParam("id") String id) {
        PlayOrderDetailsReturnVo vo = playOrderInfoService.selectById(id);
        if (vo == null) {
            throw new CustomException("订单不存在");
        }
        // Privacy protection: Hide customer info for pending random orders that current clerk hasn't accepted
        String currentClerkId = ThreadLocalRequestDetail.getClerkUserInfo().getId();
        if (OrderConstant.PlaceType.RANDOM.getCode().equals(vo.getPlaceType()) && OrderConstant.OrderStatus.PENDING.getCode().equals(vo.getOrderStatus())) {
            // Random order pending - customer info already hidden by service layer
            vo.setWeiChatCode("");
        } else if (StringUtils.isNotEmpty(vo.getAcceptBy()) && !vo.getAcceptBy().equals(currentClerkId)) {
            // Order accepted by another clerk - hide WeChat and customer info
            vo.setWeiChatCode("");
            vo.setCustomNickname("匿名用户");
            vo.setCustomAvatar("");
            vo.setCustomId("");
        }

        if(vo.getOrderStatus().equals("4")){
            vo.setWeiChatCode("");
        }
        return R.ok(vo);
    }

    /**
     * 店员查询打赏动态
     *
     * @param vo 打赏动态查询列表
     * @return 打赏动态列表
     */
    @ApiOperation(value = "店员查询打赏动态", notes = "店员查询打赏订单动态")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PostMapping("/clerk/selectRewardByPage")
    public R clerkSelectRewardByPage(
            @ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayRewardOrderQueryVo vo) {
        return R.ok(playOrderInfoService.selectRewardByPage(vo));
    }

    /**
     * 顾客查询最新打赏动态
     *
     * @return 打赏动态列表
     */
    @ApiOperation(value = "顾客查询打赏动态", notes = "顾客查询最新打赏订单动态")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @GetMapping("/custom/selectRewardByPage")
    public R customSelectReward() {
        PlayRewardOrderQueryVo vo = new PlayRewardOrderQueryVo();
        return R.ok(playOrderInfoService.selectRewardByPage(vo));
    }

    /**
     * 顾客-分页查询续单列表
     *
     * @param vo PlayOrderInfoContinueQueryVo
     * @return 续单历史
     */
    @ApiOperation(value = "查询续单列表", notes = "顾客分页查询续单申请列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayOrderContinueReturnVo.class, responseContainer = "Page")})
    @CustomUserLogin
    @PostMapping("/custom/continueListByPage")
    public R continueListByPage(
            @ApiParam(value = "查询条件", required = true) @Validated @RequestBody PlayOrderInfoContinueQueryVo vo) {
        PlayOrderContinueQueryVo queryVo = new PlayOrderContinueQueryVo();
        BeanUtils.copyProperties(vo, queryVo);
        queryVo.setCustomId(ThreadLocalRequestDetail.getCustomUserInfo().getId());
        IPage<PlayOrderContinueReturnVo> page = playOrderContinueInfoService.selectPlayByPage(queryVo);
        return R.ok(page);
    }

    /**
     * 审批续单申申请
     */
    @ApiOperation(value = "审批续单申请", notes = "顾客审批店员发起的续单申请")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "续单已处理")})
    @CustomUserLogin
    @PostMapping("/custom/updateReviewState")
    public R updateReviewState(
            @ApiParam(value = "审批信息", required = true) @Validated @RequestBody PlayOrderReviewStateEditVo vo) {
        PlayOrderContinueInfoEntity entity = playOrderContinueInfoService.selectPlayOrderContinueInfoById(vo.getId());
        if (!"0".equals(entity.getReviewedState())) {
            throw new CustomException("续单已处理");
        }
        playOrderContinueInfoService.updateReviewState(vo);
        return R.ok("成功");
    }

}
