package com.hzs.sale.order.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMemberShare;
import com.hzs.common.domain.sale.ext.BdWaresSpecsSkuExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.order.SaOrderShareTmp;
import com.hzs.common.domain.sale.wares.BdWares;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.order.controller.ParentOrderController;
import com.hzs.sale.order.param.*;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.order.service.ISaOrderShareTmpService;
import com.hzs.sale.order.vo.FansConfirmOrderVO;
import com.hzs.sale.wares.service.IBdWaresService;
import com.hzs.sale.wares.service.IBdWaresSpecsSkuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 分享订单
 */
@RestController
@RequestMapping("/api/order")
@Slf4j
public class ApiFanSaOrderController extends ParentOrderController {

    @Autowired
    private IBdWaresService iBdWaresService;
    @Autowired
    private IBdWaresSpecsSkuService iBdWaresSpecsSkuService;
    @Autowired
    private ISaOrderShareTmpService iSaOrderShareTmpService;
    @Autowired
    private ISaOrderService iSaOrderService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    /**
     * 海粉确认订单
     *
     * @param param 确认订单入参
     * @return
     */
    @PostMapping("/fans-confirm-order")
    public AjaxResult fansConfirmOrder(@RequestBody FansConfirmOrderParam param) {
        // 校验参数
        if (StringUtils.isAnyEmpty(param.getMemberName(), param.getPhone(), param.getRecName(), param.getRecPhone(), param.getRecAddress())
                || null == param.getPkCountry() || null == param.getRecProvince() || null == param.getRecCity()
                || CollectionUtil.isEmpty(param.getWaresList())
        ) {
            // 缺少参数
            return AjaxResult.error("缺少参数");
        }
        // 校验商品数据
        for (FansConfirmOrderWaresParam waresParam : param.getWaresList()) {
            if (null == waresParam.getPkWares() || null == waresParam.getQuantity()
                    || CollectionUtil.isEmpty(waresParam.getSkuList())) {
                // 缺少参数
                return AjaxResult.error("缺少参数");
            }
            // 校验产品数据
            for (FansConfirmOrderSkuParam skuParam : waresParam.getSkuList()) {
                if (null == skuParam.getPkWaresSku() || null == skuParam.getQuantity()) {
                    // 缺少参数
                    return AjaxResult.error("缺少参数");
                }
            }
        }

        // 会员ID
        Long userId = SecurityUtils.getUserId();
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();

        // 查询临时会员
        CuMemberShare cuMemberShare = iMemberServiceApi.queryCuMemberShare(userId).getData();
        if (null == cuMemberShare) {
            // 会员不存在
            return AjaxResult.error("推荐人不存在");
        }

        // 封装缓存数据
        OrderParam orderParam = OrderParam.builder()
                .memberName(param.getMemberName())
                .phone(param.getPhone())
                .centerCodeId(cuMemberShare.getPkParent())
                .pkParent(cuMemberShare.getPkParent())
                .pkMemberId(userId)
                .pkCountry(param.getPkCountry())
                .pkSettleCountry(pkCountry)
                .source(EDataSource.H5.getValue())
                .isHaiFun(true)
                .build();

        // 手机号注册次数校验
        AjaxResult ajaxResult = super.validatePhone(orderParam);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }

        // 订单金额
        BigDecimal orderAmount = BigDecimal.ZERO;

        // 生成订单编号
        String orderCode = CommonUtil.createSerialNumber(EOrderPrefix.ORDER_CODE);

        // 缓存数据
        List<OrderItemsParam> orderItemsParams = new ArrayList<>();
        // 遍历商品，封装订单明细
        for (FansConfirmOrderWaresParam waresParam : param.getWaresList()) {
            // 遍历sku
            // 产品价格等map
            Map<Long, BdWaresSpecsSkuExt> skuMap = iBdWaresSpecsSkuService.queryWaresSpecsSkuList(waresParam.getSkuList().stream().map(FansConfirmOrderSkuParam::getPkWaresSku).collect(Collectors.toList()));

            // 查询商品
            BdWares bdWares = iBdWaresService.getWares(waresParam.getPkWares());

            // 缓存数据
            List<WaresItemsParam> itemsParamList = new ArrayList<>(waresParam.getSkuList().size());
            // 遍历产品信息
            for (FansConfirmOrderSkuParam skuParam : waresParam.getSkuList()) {
                BdWaresSpecsSkuExt specsSku = skuMap.get(skuParam.getPkWaresSku());
                orderAmount = orderAmount.add(specsSku.getPrice().multiply(new BigDecimal(skuParam.getQuantity() * waresParam.getQuantity())));

                itemsParamList.add(WaresItemsParam.builder()
                        .pkWaresSpecsSku(skuParam.getPkWaresSku().intValue())
                        .quantity(skuParam.getQuantity())
                        .build());
            }
            orderItemsParams.add(OrderItemsParam.builder()
                    .waresCode(bdWares.getWaresCode())
                    .quantity(waresParam.getQuantity())
                    .waresItemsParamList(itemsParamList)
                    .build());
        }
        // 封装订单数据
        SaOrderExt saOrder = new SaOrderExt();
        saOrder.setOrderCode(orderCode);
        // 188注册订单实际按复购订单来算
        saOrder.setOrderType(EOrderType.REPURCHASE_ORDER.getValue());
        saOrder.setOrderTypeExtend(EOrderTypeExtend.REG_REP.getValue());
        saOrder.setOrderAmount(orderAmount);
        saOrder.setPostage(BigDecimal.ZERO);
        saOrder.setRecName(param.getRecName());
        saOrder.setRecPhone(param.getRecPhone());
        saOrder.setRecProvince(param.getRecProvince());
        saOrder.setRecCity(param.getRecCity());
        saOrder.setRecCounty(param.getRecCounty());
        saOrder.setRecAddress(param.getRecAddress());
        saOrder.setRemark(param.getRemark());
        saOrder.setPkMember(cuMemberShare.getPkId());
        saOrder.setPkReference(cuMemberShare.getPkParent());
        saOrder.setDeliveryWay(EDelivery.FAST_MAIL.getValue());
        saOrder.setTranType(ETransportType.LAND.getValue());
        saOrder.setPkCreator(cuMemberShare.getPkId());
        saOrder.setPkCountry(pkCountry);

        orderParam.setOrderCode(orderCode);
        orderParam.setSpecialArea(saOrder.getOrderType());
        orderParam.setPostage(saOrder.getPostage());
        orderParam.setDeliveryWay(saOrder.getDeliveryWay());
        orderParam.setTransType(saOrder.getTranType());
        orderParam.setRecName(saOrder.getRecName());
        orderParam.setRecPhone(saOrder.getRecPhone());
        orderParam.setRecProvince(saOrder.getRecProvince());
        orderParam.setRecCity(saOrder.getRecCity());
        orderParam.setRecCounty(saOrder.getRecCounty());
        orderParam.setRecAddress(saOrder.getRecAddress());
        orderParam.setOrderItemsParams(orderItemsParams);

        HashMap<String, Object> orderInfo = new HashMap<>();
        orderInfo.put("param", param);
        orderInfo.put("saOrder", saOrder);
        orderInfo.put("orderParam", orderParam);
        // 分享会员订单数据
        if (iSaOrderShareTmpService.save(SaOrderShareTmp.builder()
                .pkId(cuMemberShare.getPkId())
                .orderInfo(JSONUtil.toJsonStr(orderInfo))
                .build())) {

            // 临时订单直接放入缓存（24小时有效）
            redisService.setCacheObject(CacheConstants.TEMP_ORDER + userId + orderCode, saOrder, 24L, TimeUnit.HOURS);
            // 临时会员直接放入缓存（24小时有效）
            redisService.setCacheObject(CacheConstants.TEMP_PARAM + userId + orderCode, orderParam, 24L, TimeUnit.HOURS);

            return AjaxResult.success(FansConfirmOrderVO.builder()
                    .orderCode(orderCode)
                    .orderAmount(saOrder.getOrderAmount().add(saOrder.getPostage()))
                    .payTime(iSaOrderService.getIsToBePayTime(pkCountry, saOrder.getOrderType()))
                    .build());
        }
        return AjaxResult.error();
    }

}
