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

import cn.hutool.core.bean.BeanUtil;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.constant.msg.SaOrderMsgConstants;
import com.hzs.common.core.enums.EDelivery;
import com.hzs.common.core.enums.EOrderType;
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.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.util.TransactionUtils;
import com.hzs.sale.order.controller.ParentOrderController;
import com.hzs.sale.order.param.CuMemberAccountParam;
import com.hzs.sale.order.param.OrderParam;
import com.hzs.sale.order.param.OrderReturn;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制类
 */
@RestController
@RequestMapping("/api/order")
@Slf4j
public class ApiRegSaOrderController extends ParentOrderController {

    @DubboReference
    IGradeServiceApi iGradeServiceApi;

    /**
     * 查询订单
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/query-order")
    public AjaxResult queryOrder(@RequestBody OrderParam orderParam) {
        log.info(orderParam.getOrderCode());
        initPkCountry(orderParam);
        // 直接支付，从redis中获取
        AjaxResult result = validateOrderParam(orderParam);
        if (result != null) {
            return result;
        }
        SaOrder saOrder;
        boolean isToBePay = getOrderService().getIsToBePayByOrderType(orderParam.getPkSettleCountry(), orderParam.getSpecialArea());
        if (isToBePay) {
            // 从数据库中获取
            saOrder = getOrderService().querySaleOrderByOrderCode(getSaOrderQueryParam(orderParam));
            if (saOrder == null) {
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
            }
        } else {
            SaOrderExt saOrderExt = redisService.getCacheObject(CacheConstants.TEMP_ORDER + SecurityUtils.getUserId() + orderParam.getOrderCode());
            if (saOrderExt == null) {
                return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_EMPTY));
            }
            saOrder = BeanUtil.copyProperties(saOrderExt, SaOrder.class);
        }

        OrderReturn orderReturn = getOrderReturn(saOrder, orderParam);
        if (isToBePay) {
            CuMember cuMember = getOrderService().getCuMemberByKey(saOrder.getPkMember());
            if (cuMember != null) {
                if (SecurityUtils.getUserId().equals(cuMember.getPkId())) {
                    orderReturn.setMemberName(cuMember.getMemberName());
                } else {
                    orderReturn.setMemberName(cuMember.getMemberName());
                }
                orderReturn.setMemberCode(cuMember.getMemberCode());

                if (EOrderType.REGISTER_ORDER.getValue() == saOrder.getOrderType()) {
                    CuMember parentCuMember = getOrderService().getCuMemberByKey(cuMember.getPkParent());
                    CuMember placeCuMember = getOrderService().getCuMemberByKey(cuMember.getPkPlaceParent());
                    GradeDTO gradeDTO = iGradeServiceApi.getGrade(cuMember.getPkSettleGrade()).getData();
                    orderReturn.setPkGrade(gradeDTO.getPkTransaction());
                    orderReturn.setPhone(cuMember.getPhone());
                    orderReturn.setParent(parentCuMember.getMemberCode());
                    orderReturn.setPlaceParent(placeCuMember.getMemberCode());
                    if (SecurityUtils.getUserId().equals(cuMember.getPkId())) {
                        orderReturn.setParentName(parentCuMember.getMemberName());
                        orderReturn.setPlaceParentName(placeCuMember.getMemberName());
                    } else {
                        orderReturn.setParentName(parentCuMember.getMemberName());
                        orderReturn.setPlaceParentName(placeCuMember.getMemberName());
                    }
                    orderReturn.setPlaceDept(cuMember.getPlaceDept());
                    orderReturn.setSource(cuMember.getSource());
                }
            }
        } else {
            orderParam = redisService.getCacheObject(CacheConstants.TEMP_PARAM + SecurityUtils.getUserId() + orderParam.getOrderCode());
            if (orderParam.getPkGrade() != null) {
                GradeDTO gradeDTO = iGradeServiceApi.getGrade(orderParam.getPkGrade()).getData();
                orderReturn.setPkGrade(gradeDTO.getPkTransaction());
            }
            orderReturn.setMemberCode(orderParam.getMemberCode());
            orderReturn.setMemberName(orderParam.getMemberName());
            orderReturn.setPhone(orderParam.getPhone());
            orderReturn.setParent(orderParam.getParent());
            orderReturn.setParentName(orderParam.getParentName());
            orderReturn.setPlaceParent(orderParam.getPlaceParent());
            orderReturn.setPlaceParentName(orderParam.getPlaceParentName());
            orderReturn.setPlaceDept(orderParam.getPlaceDept());
            orderReturn.setSource(orderParam.getSource());
        }
        return AjaxResult.success(orderReturn);
    }

    /**
     * 查询订单邮费
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/query-order-postage")
    public AjaxResult queryOrderPostage(@RequestBody OrderParam orderParam) {
        if (orderParam.getDeleteList() == null || orderParam.getDeleteList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SPECIAL_AREA_NOT_EMPTY));
        }

        if ((checkRecPostageMsgBoolean(orderParam) && orderParam.getDeliveryWay() == EDelivery.FAST_MAIL.getValue())) {
            // 验证必输项，一个条件未填写都不计算邮费
            initSecurityOrderParam(orderParam);
            convertShoppingCarToSku(orderParam);
            getOrderService().queryPostageByParam(orderParam);
        }
        return AjaxResult.success(OrderReturn.builder().postage(orderParam.getPostage()).build());
    }

    /**
     * 自助服务-修改收货地址邮费计算
     **/
    @PostMapping("/self-order-postage")
    public AjaxResult selfOrderPostage(@RequestBody OrderParam orderParam) {
        // 验证必输项，一个条件未填写都不计算邮费
        orderParam.setTransType(orderParam.getTranType());
        if (checkRecPostageMsgBoolean(orderParam) && orderParam.getDeliveryWay() == EDelivery.FAST_MAIL.getValue()) {
            initSecurityOrderParam(orderParam);
            getOrderService().queryPostageByParam(orderParam);
        }
        return AjaxResult.success(OrderReturn.builder().postage(orderParam.getPostage()).build());
    }


    /**
     * 查询订单消费明细
     *
     * @param orderParam 订单参数
     */
    @PostMapping("/query-spend-details")
    public AjaxResult queryOrderSpendDetails(@RequestBody OrderParam orderParam) {
        log.info(orderParam.getOrderCode());
        initPkCountry(orderParam);
        AjaxResult result = validateOrderParam(orderParam);
        if (result != null) {
            return result;
        }
        boolean isToBePay = getOrderService().getIsToBePayByOrderType(orderParam.getPkSettleCountry(), orderParam.getSpecialArea());
        SaOrderExt saOrder;

        if (isToBePay) {
            saOrder = getOrderService().querySaleOrderExtByOrderCode(getSaOrderQueryParam(orderParam), null);
        } else {
            // 直接支付，从redis中获取
            SaOrderExt saOrderExt = redisService.getCacheObject(CacheConstants.TEMP_ORDER + SecurityUtils.getUserId() + orderParam.getOrderCode());
            saOrder = BeanUtil.copyProperties(saOrderExt, SaOrderExt.class);
        }
        if (saOrder == null || StringUtils.isEmpty(saOrder.getOrderCode())) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_MEMBER_CACHE));
        }

        // 获取账户，验证账户
        List<CuMemberAccountExt> cuMemberAccountExtList = getOrderService().queryMemberAccountByCondition(getCuMemberAccount(orderParam));
        if (cuMemberAccountExtList == null || cuMemberAccountExtList.size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.CENTER_NOT_EXISTS));
        }
        CuMemberAccountExt cuMemberAccountExt = cuMemberAccountExtList.get(0);
        // 验证会员账户余额是否足够支付
        getOrderService().queryOrderSpendDetails(cuMemberAccountExt, saOrder, saOrder.getOrderItemsList());
        CuMemberAccountParam cuMemberAccountParam = BeanUtil.copyProperties(cuMemberAccountExt, CuMemberAccountParam.class);
        return AjaxResult.success(cuMemberAccountParam);
    }

    private AjaxResult validateOrderParam(@RequestBody OrderParam orderParam) {
        initSecurityOrderParam(orderParam);
        if (orderParam.getSpecialArea() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_TYPE_EMPTY));
        }
        if (StringUtils.isEmpty(orderParam.getOrderCode())) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.ORDER_CODE_EMPTY));
        }
        return null;
    }

}
