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

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.RepeatSubmit;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.constant.msg.SaOrderMsgConstants;
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.CuMember;
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.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.retail.sale.param.RetailOrderParam;
import com.hzs.retail.sale.param.RetailOrderRegisterParam;
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.shopping.vo.ShoppingCartVO;
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.validation.annotation.Validated;
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 orderParam 订单参数
     */
    @PostMapping("/confirm-fun-order")
    @RepeatSubmit
    public AjaxResult confirmHaiFunOrder(@Validated @RequestBody OrderParam orderParam) {
        if (orderParam.getDeleteList() == null || orderParam.getDeleteList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SPECIAL_AREA_NOT_EMPTY));
        }
        initSecurityOrderParam(orderParam);
        // 验证必输项
        if (validateFieldNotNull(orderParam, orderParam.getValidConfirmField()) ||
                !checkRecMsgBoolean(orderParam)) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        orderParam.setIsHaiFun(true);
        AjaxResult result = validateSaveMember(orderParam);
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return result;
        }
        convertShoppingCarToSku(orderParam);
        if (getOrderService().confirmRegSaOrderByOrderParam(orderParam)) {
            //删除购物车下单的数据
            if (CollectionUtil.isNotEmpty(orderParam.getDeleteList())) {
                ShoppingCartVO sop = new ShoppingCartVO();
                sop.setDeleteList(orderParam.getDeleteList());
                shoppingCartService.batchDelShopping(SecurityUtils.getUserId(), sop);
            }
            return AjaxResult.success(orderParam);
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 报单中心确认嗨粉订单，生成待支付订单,只有注册订单有待支付订单
     *
     * @param orderParam 订单参数 自注册
     */
    @PostMapping("/confirm-self-fun-order")
    @RepeatSubmit
    public AjaxResult confirmSelfFunOrder(@Validated @RequestBody OrderParam orderParam) {
        initSecurityOrderParam(orderParam);
        // 验证必输项
        if (!checkRecMsgBoolean(orderParam)) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        orderParam.setIsHaiFun(true);

        CuMember cuMember = iMemberServiceApi.queryMember(orderParam.getCenterCodeId()).getData();
        if (cuMember == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_EXISTS));
        }

        if (getOrderService().confirmSelfFunOrderByOrderParam(orderParam, cuMember)) {
            return AjaxResult.success(orderParam);
        } else {
            return AjaxResult.error();
        }
    }


//    /**
//     * 海粉确认订单
//     *
//     * @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("推荐人不存在");
//        }
//
//        // 封装缓存数据
//        RetailOrderRegisterParam orderParam = RetailOrderRegisterParam.builder()
//                .memberName(param.getMemberName())
//                .phone(param.getPhone())
//                .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.RETAIL_TEMP_ORDER + userId + orderCode, saOrder, 24L, TimeUnit.HOURS);
//            // 临时会员直接放入缓存（24小时有效）
//            redisService.setCacheObject(CacheConstants.RETAIL_TEMP_REG_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();
//    }
}
