package cn.iocoder.yudao.module.member.controller.app.storeorder;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.member.controller.admin.storegoodsinventory.vo.AddReqVO;
import cn.iocoder.yudao.module.member.controller.admin.storeorder.vo.StoreOrderPageReqVO;
import cn.iocoder.yudao.module.member.controller.admin.storeorder.vo.StoreOrderRespVO;
import cn.iocoder.yudao.module.member.controller.app.storeorder.dto.completeListDto;
import cn.iocoder.yudao.module.member.controller.app.storeorder.vo.AppStoreOrderDetailVo;
import cn.iocoder.yudao.module.member.controller.app.storeorder.vo.AppStoreOrderVO;
import cn.iocoder.yudao.module.member.controller.app.storeorder.vo.CardDto;
import cn.iocoder.yudao.module.member.dal.dataobject.storediscount.StoreDiscountDO;
import cn.iocoder.yudao.module.member.dal.dataobject.storeorder.StoreOrderDO;
import cn.iocoder.yudao.module.member.enums.StoreOrderStatusEnum;
import cn.iocoder.yudao.module.member.service.async.MemberAsyncService;
import cn.iocoder.yudao.module.member.service.configdata.ConfigDataService;
import cn.iocoder.yudao.module.member.service.storediscount.StoreDiscountService;
import cn.iocoder.yudao.module.member.service.storeorder.StoreOrderService;
import cn.iocoder.yudao.module.member.service.storeorderdetail.StoreOrderDetailService;
import cn.iocoder.yudao.module.member.util.ConfigConstants;
import cn.iocoder.yudao.module.system.api.carteen.CarteenApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "APP超市 - 商品订单")
@RestController
@RequestMapping("/member/store-order")
@Validated
public class AppStoreOrderController {

    @Resource
    private StoreOrderService storeOrderService;
    @Resource
    private StoreOrderDetailService orderDetailService;
    @Resource
    private CarteenApi carteenApi;
    @Resource
    private MemberAsyncService memberAsyncService;
    @Resource
    private ConfigDataService configDataService;
    @Resource
    private StoreDiscountService storeDiscountService;

    @GetMapping("/page")
    @Operation(summary = "获得商品订单分页")
    public CommonResult<PageResult<StoreOrderRespVO>> getStoreOrderPage(@Valid StoreOrderPageReqVO pageReqVO) {
        if (pageReqVO.getUserId() == null) {
            pageReqVO.setStatus(StoreOrderStatusEnum.COMPLETE.getCode());
        }
        PageResult<StoreOrderDO> pageResult = storeOrderService.getStoreOrderPage(pageReqVO);
        PageResult<StoreOrderRespVO> bean = BeanUtils.toBean(pageResult, StoreOrderRespVO.class);

        //处理订单详情
        if(CollectionUtil.isNotEmpty(bean.getList())){
            for (StoreOrderRespVO vo : bean.getList()) {
                List<AppStoreOrderDetailVo> listByOrderNo = orderDetailService.getListByOrderNo(vo.getOrderId());
                vo.setDetailDOS(listByOrderNo);
                vo.setStoresName(carteenApi.getCarteenById(vo.getCarteenId()).getStoresName());
            }
        }
        return success(bean);
    }

    @PostMapping("/appCreate")
    @Operation(summary = "创建购物车订单")
    public CommonResult<Boolean> appCreate(@RequestBody CardDto dto) {
        checkTime();
        AddReqVO addReqVO = storeOrderService.appCreate(dto);
        //记录
        memberAsyncService.batchRecord(addReqVO);

        return success(true);
    }

    @GetMapping("/code")
    @Operation(summary = "二维码")
    public CommonResult<String> code(Integer orderId) {
        return success(storeOrderService.code(orderId));
    }

    @GetMapping("/info")
    @Operation(summary = "二维码商品信息")
    public CommonResult<AppStoreOrderVO> info(String code) {
        return success(storeOrderService.info(code));
    }

    @GetMapping("/complete")
    @Operation(summary = "核销")
    public CommonResult<Boolean> complete(Integer orderId) {
        return success(storeOrderService.complete(orderId));
    }

    @GetMapping("/cancel")
    @Operation(summary = "取消订单")
    public synchronized CommonResult<Boolean> cancel(Integer orderId) {

        AddReqVO cancel = storeOrderService.cancel(orderId);
        //记录
        memberAsyncService.batchRecord(cancel);

        return success(true);
    }

    @GetMapping("/refund")
    @Operation(summary = "用户退款申请")
    public CommonResult<Long> refund(Integer orderId) {
        return success(storeOrderService.refund(orderId));
    }

    @GetMapping("/reduction")
    @Operation(summary = "减免")
    public CommonResult<Boolean> reduction(Long orderId, BigDecimal money) {
        storeOrderService.reduction(orderId, money);
        return CommonResult.success(true);
    }

    @GetMapping("/refundAdmin")
    @Operation(summary = "管理员执行退款")
    public CommonResult<Boolean> refundAdmin(Integer orderId) {
        AddReqVO addReqVO = storeOrderService.refundAdmin(orderId);
        //记录
        memberAsyncService.batchRecord(addReqVO);
        return success(true);
    }

    @GetMapping("/discount")
    @Operation(summary = "获取折扣")
    public CommonResult<BigDecimal> discount(Long storeId) {
        StoreDiscountDO storeDiscount = storeDiscountService.getStoreDiscountByStoreId(storeId);
        if(storeDiscount == null){
            return success(null);
        }
        return success(storeDiscount.getDiscountNum().divide(BigDecimal.valueOf(10), 2, RoundingMode.HALF_UP));
    }

    public void checkTime(){
        String start = configDataService.getConfigData(ConfigConstants.START_TIME, ConfigConstants.BUY_PROHIBIT).getValue();
        String end = configDataService.getConfigData(ConfigConstants.END_TIME, ConfigConstants.BUY_PROHIBIT).getValue();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime startTime = LocalTime.parse(start, formatter);
        LocalTime endTime = LocalTime.parse(end, formatter);
        LocalTime now = LocalTime.now();

        Duration startToNow = Duration.between(startTime, now);
        Duration startToEnd = Duration.between(startTime, endTime);

        boolean isInRange = startToNow.isZero() ||!startToNow.isNegative() && startToNow.compareTo(startToEnd) <= 0;
        if(isInRange){
            throw exception(new ErrorCode(1_007_904_009, "请明天购买"));
        }

        LocalTime currentTime = LocalTime.now();
        // 定义开始时间和结束时间
        LocalTime dsStartTime = LocalTime.of(0, 0);
        LocalTime dsEndTime = LocalTime.of(1, 0);

        // 判断当前时间是否在指定区间内
        boolean isDsInRange = currentTime.isAfter(startTime) && currentTime.isBefore(endTime);
        // 考虑边界情况，即当前时间是否等于开始时间
        isDsInRange = isDsInRange || currentTime.equals(startTime);

        if(isDsInRange){
            throw exception(new ErrorCode(1_007_904_009, "当前时间不允许购买"));
        }
    }


    @PostMapping("/completeList")
    @Operation(summary = "离线核销")
    public CommonResult<Boolean> completeList(@RequestBody completeListDto dto) {
        storeOrderService.completeList(dto.getOrderIds());
        return success(true);
    }

}