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.EOrderType;
import com.hzs.common.core.enums.ESpecialArea;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.ext.CuMemberAccountExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.sale.order.controller.ParentOrderController;
import com.hzs.sale.order.param.OrderParam;
import com.hzs.sale.order.service.ISaOrderItemsService;
import com.hzs.sale.shopping.vo.ShoppingCartVO;
import lombok.extern.slf4j.Slf4j;
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;

/**
 * 其他订单（升级、复购）订单
 */
@RestController
@RequestMapping("/api/order")
@Slf4j
public class ApiOthSaOrderController extends ParentOrderController {

    @Autowired
    private ISaOrderItemsService saOrderItemsService;

    /**
     * 提供确认订单的方法
     *
     * @param orderParam 前台传递的参数
     */
    @PostMapping("/confirm-oth-order")
    @RepeatSubmit
    public AjaxResult confirmOtherOrder(@RequestBody OrderParam orderParam) {
        if (orderParam.getDeleteList() == null || orderParam.getDeleteList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SPECIAL_AREA_NOT_EMPTY));
        }
        initSecurityOrderParam(orderParam);
        // 验证必输项
        if (!checkRecMsgBoolean(orderParam)) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        // 转区到订单类型的转换
        int tmpSpecialArea = ESpecialArea.getOrderTypeValue(orderParam.getSpecialArea());
        if (tmpSpecialArea != EOrderType.REGISTER_ORDER.getValue()) {
            convertShoppingCarToSku(orderParam);

            if (EOrderType.UPGRADE_ORDER.getValue() == tmpSpecialArea
                    || EOrderType.REPURCHASE_ORDER.getValue() == tmpSpecialArea
                    || EOrderType.RESALE_ORDER.getValue() == tmpSpecialArea
            ) {
                if (StringUtils.isEmpty(orderParam.getUpgradeMemberCode())) {
                    orderParam.setUpgradeMemberCode(SecurityUtils.getMemberCode());
                }
                // 验证复购的人是否在推荐人伞下
                AjaxResult result = validateUpgradeRelation(orderParam);
                if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
                    return result;
                }
            }
            if (!getOrderService().confirmRepurchaseSaOrder(orderParam)) {
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_MEMBER_CACHE));
            }
            //删除购物车下单的数据
            if (CollectionUtil.isNotEmpty(orderParam.getDeleteList())) {
                ShoppingCartVO sop = new ShoppingCartVO();
                sop.setDeleteList(orderParam.getDeleteList());
                shoppingCartService.batchDelShopping(SecurityUtils.getUserId(), sop);
            }
        }
        return AjaxResult.success(orderParam);
    }

    /**
     * @param orderParam 订单参数
     */
    @PostMapping("/validate-upg-rel")
    public AjaxResult validateUpgradeMemberCodeRelation(@RequestBody OrderParam orderParam) {
        initSecurityOrderParam(orderParam);
        return validateUpgradeRelation(orderParam);
    }

    /**
     * @param orderParam 订单参数
     */
    @PostMapping("/query-special-deduct")
    public AjaxResult querySpecialDeduct(@RequestBody OrderParam orderParam) {
        initSecurityOrderParam(orderParam);
        if (orderParam.getSpecialArea() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_TYPE_EMPTY));
        }
        return validateUpgradeRelation(orderParam);
    }


    /**
     * 支付升级订单，生成支付订单或者更新待支付订单
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/pay-oth-order")
    @RepeatSubmit
    public AjaxResult payOtherOrder(@RequestBody OrderParam orderParam) {
        initSecurityOrderParam(orderParam);
        if (orderParam.getOrderCode() == null || orderParam.getSpecialArea() == null ||
                StringUtils.isEmpty(orderParam.getPayPwd())) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }

        // 转区到订单类型的转换
        int tmpSpecialArea = ESpecialArea.getOrderTypeValue(orderParam.getSpecialArea());
        if (EOrderType.REGISTER_ORDER.getValue() == tmpSpecialArea) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        }
        // 验证账户余额
        // 查询报单会员账户信息
        AjaxResult result = validateMemberAccount(orderParam);
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.ERROR) {
            return result;
        }
        CuMemberAccountExt cuMemberAccountExt = (CuMemberAccountExt) result.get(AjaxResult.DATA_TAG);
        SaOrder saOrderQueryParam = getSaOrderQueryParam(orderParam);
        SaOrderExt saOrderExt;
        if (EOrderType.PICK_ORDER.getValue() == tmpSpecialArea) {
            // 提货订单，没有待支付，需要从缓存取
            saOrderExt = redisService.getCacheObject(CacheConstants.TEMP_ORDER + SecurityUtils.getUserId() + orderParam.getOrderCode());
        } else {
            saOrderExt = getOrderService().querySaleOrderExtByOrderCode(saOrderQueryParam, null);
        }
        if (saOrderExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
        }
        OrderParam oldOrderParam = redisService.getCacheObject(CacheConstants.TEMP_PARAM + SecurityUtils.getUserId() + orderParam.getOrderCode());
        if (oldOrderParam == null) {
            if (CollectionUtil.isEmpty(orderParam.getOrderItemsParams())) {
                orderParam.setOrderItemsParams(saOrderItemsService.listPayOrderData(orderParam.getOrderCode()));
            }
            saOrderItemsService.listPayOrderData(orderParam.getOrderCode());
            oldOrderParam = orderParam;
            oldOrderParam.setRecProvince(saOrderExt.getRecProvince());
        }

        if (EOrderType.RENEWAL_ORDER.getValue() == tmpSpecialArea) {
            // 年包订单，订单价格需要大于等于会员等级年包价格，不然不能下单
            // 校验年包价格
            if (!this.getOrderService().checkRenewalAmount(null, saOrderExt)) {
                // 订单价格 小于 年包价格
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.RENEWAL_ORDER_PRICE_NOT_ENOUGH));
            }
        }

        // 验证会员账户余额是否足够支付
        getOrderService().queryOrderSpendDetails(cuMemberAccountExt, saOrderExt, saOrderExt.getOrderItemsList());
        if (cuMemberAccountExt.getIsPayment()) {
            // 开始支付 扣款
            // 升级订单
            if (EOrderType.UPGRADE_ORDER.getValue() == tmpSpecialArea) {
                if (getOrderService().payUpgradeSaOrder(saOrderExt, cuMemberAccountExt)) {
                    return AjaxResult.success(saOrderExt);
                } else {
                    return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.LEVEL_NOT_ENOUGH));
                }
            } else {
                // 其它订单
                if (getOrderService().payRepurchaseSaOrder(saOrderExt, cuMemberAccountExt)) {
                    return AjaxResult.success(saOrderExt);
                }
            }
        }
        if (cuMemberAccountExt.getErrorMsg() == null) {
            cuMemberAccountExt.setErrorMsg(TransactionUtils.getContent(MemberMsgConstants.MEMBER_ACCOUNT_BALANCE_NOT_ENOUGH));
        }
        return AjaxResult.error(cuMemberAccountExt.getErrorMsg());
    }

}
