package com.kxs.product.biz.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.util.R;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.product.api.model.KxsShopGoods;
import com.kxs.product.api.model.KxsShopOrderInfo;
import com.kxs.product.api.dto.kxsapp.shop.GoodsSubmitDTO;
import com.kxs.product.api.vo.kxsapp.shop.ShopOrderCountVO;
import com.kxs.product.api.vo.kxsapp.shop.ShopOrderInfoListVO;
import com.kxs.product.api.vo.kxsapp.shop.ShopOrderDetailVO;
import com.kxs.product.api.vo.kxsapp.shop.ShopOrderListVO;
import com.kxs.product.biz.constant.enums.KxsShopEnum;
import com.kxs.product.biz.constant.enums.ProductErrorTypeEnum;
import com.kxs.product.biz.mapper.KxsShopGoodsMapper;
import com.kxs.product.biz.mapper.KxsShopOrderInfoMapper;
import com.kxs.product.biz.mapper.KxsShopOrderMapper;
import com.kxs.product.api.model.KxsShopOrder;
import com.kxs.product.biz.service.KxsShopOrderService;
import com.kxs.user.api.feign.RemoteKxsUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商城订单表(KxsShopOrder)表服务实现类
 *
 * @author 系统
 * @since 2023-12-20 10:09:35
 */
@Service("kxsShopOrderService")
@RequiredArgsConstructor
public class KxsShopOrderServiceImpl extends ServiceImpl<KxsShopOrderMapper, KxsShopOrder> implements KxsShopOrderService {

    private final KxsShopGoodsMapper goodsMapper;

    private final KxsShopOrderInfoMapper orderInfoMapper;

    private final RemoteKxsUserService remoteKxsUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R submitOrder(GoodsSubmitDTO param) {

        Long userId = SecurityUtils.getUser().getId();

        //订单号
        Snowflake snowflake = IdUtil.getSnowflake(1, userId);
        long orderSn = snowflake.nextId();

        KxsShopOrder order = new KxsShopOrder();
        //参数赋值
        BeanUtils.copyProperties(param, order);
        order.setUserId(userId);
        order.setOrderSn(String.valueOf(orderSn));
        //支付金额
        order.setPayPrice(order.getTotalPrice());
        baseMapper.insert(order);

        //查询商品
        KxsShopGoods goods = goodsMapper.selectById(param.getGoodsId());
        //订单详情
        KxsShopOrderInfo orderInfo = new KxsShopOrderInfo();
        orderInfo.setNumber(param.getNumber());
        orderInfo.setGoodsId(param.getGoodsId());
        orderInfo.setSkuId(param.getSkuId());
        orderInfo.setSpecifications(param.getSpecifications());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getPrice());
        orderInfo.setPicUrl(goods.getPicUrl());
        orderInfo.setOrderId(order.getId());
        orderInfoMapper.insert(orderInfo);

        return R.ok(Boolean.TRUE);

    }

    @Override
    public ShopOrderDetailVO getByOrderId(Integer orderId) {

        KxsShopOrder order = baseMapper.selectById(orderId);
        if(order == null){
            return null;
        }
        ShopOrderDetailVO shopOrderDetailVO = new ShopOrderDetailVO();
        BeanUtils.copyProperties(order, shopOrderDetailVO);

        List<KxsShopOrderInfo> orderInfos = orderInfoMapper.selectList(Wrappers.<KxsShopOrderInfo>lambdaQuery()
                .eq(KxsShopOrderInfo::getOrderId, orderId));

        orderInfos.forEach(item -> {
            ShopOrderInfoListVO infoListVO = new ShopOrderInfoListVO();
            BeanUtils.copyProperties(item, infoListVO);
            shopOrderDetailVO.getGoodsList().add(infoListVO);
        });

        return shopOrderDetailVO;
    }

    @Override
    public R payOrder(KxsShopOrder param) {

        KxsShopOrder order = baseMapper.selectById(param.getId());
        if(order == null){
            return R.failed(ProductErrorTypeEnum.ORDER_EMPTY.getDescription());
        }

        //余额支付
        if(param.getPayType().equals(KxsShopEnum.YUE_PAY.getType())){
            return this.yuePay(param);
        }

        //支付宝支付
        if(param.getPayType().equals(KxsShopEnum.ALI_PAY.getType())){
            return this.aliPay(param);
        }

        return R.failed();
    }

    @Override
    public R cancelOrder(KxsShopOrder param) {

        KxsShopOrder order = baseMapper.selectById(param.getId());
        if(order == null){
            return R.failed(ProductErrorTypeEnum.ORDER_EMPTY.getDescription());
        }
        if(!order.getStatus().equals(KxsShopEnum.ORDER_NO_PAY.getType())){
            return R.failed(ProductErrorTypeEnum.ORDER_NO_CANCEL.getDescription());
        }
        order.setStatus(KxsShopEnum.ORDER_CANCEL.getType());
        baseMapper.updateById(order);

        return R.ok();
    }

    @Override
    public R confirmOrder(KxsShopOrder param) {

        KxsShopOrder order = baseMapper.selectById(param.getId());
        if(order == null){
            return R.failed(ProductErrorTypeEnum.ORDER_EMPTY.getDescription());
        }
        if(!order.getStatus().equals(KxsShopEnum.ORDER_NO_TAKE.getType())){
            return R.failed(ProductErrorTypeEnum.ORDER_NO_CONFIRM.getDescription());
        }
        order.setStatus(KxsShopEnum.ORDER_CONFIRM.getType());
        baseMapper.updateById(order);

        return R.ok();
    }

    @Override
    public IPage<ShopOrderListVO> getByPage(Page<ShopOrderListVO> page, KxsShopOrder param) {
        //自定义分页
        long start = (page.getCurrent() - 1) * page.getSize();
        start = start < 0 ? 0L : start;

        Long count = baseMapper.selectCount(Wrappers.query(param));
        List<ShopOrderListVO> orderListVos = baseMapper.getByPage(start, page.getSize(), param);
        page.setRecords(orderListVos);
        page.setTotal(count);

        return page;
    }

    @Override
    public ShopOrderCountVO orderUnCount() {

        Long userId = SecurityUtils.getUser().getId();

        Long noPayCount = baseMapper.selectCount(Wrappers.<KxsShopOrder>lambdaQuery()
                .eq(KxsShopOrder::getUserId, userId)
                .eq(KxsShopOrder::getStatus, KxsShopEnum.ORDER_NO_PAY.getType()));
        Long noSendCount = baseMapper.selectCount(Wrappers.<KxsShopOrder>lambdaQuery()
                .eq(KxsShopOrder::getUserId, userId)
                .eq(KxsShopOrder::getStatus, KxsShopEnum.ORDER_NO_SEND.getType()));

        return ShopOrderCountVO.builder().needPayCount(noPayCount).needSendCount(noSendCount).build();
    }

    /**
     * 余额支付
     *
     * @param param 参数
     * @return {@link R}
     */
    private R yuePay(KxsShopOrder param){
        return R.ok();
    }

    /**
     * 支付宝支付
     *
     * @param param 参数
     * @return {@link R}
     */
    private R aliPay(KxsShopOrder param){
        return R.ok();
    }


}

