package cn.freemud.service;

import cn.freemud.amp.body.OrderBody;
import cn.freemud.central.service.constant.FmStatusCode;
import cn.freemud.central.service.request.OpenPlatformHualalaAccountConfigRequest;
import cn.freemud.central.service.response.BaseResponse;
import cn.freemud.central.service.response.OpenPlatformHualalaAccountConfigResponse;
import cn.freemud.central.service.service.OpenPlatformHualalaAccountConfigService;
import cn.freemud.platform.sdk.common.log.DateUtil;
import cn.freemud.platform.sdk.hualala.HualalaSdkService;
import cn.freemud.platform.sdk.hualala.request.HuaLaLaCommonRequest;
import cn.freemud.platform.sdk.hualala.request.HualalaBaseConfig;
import cn.freemud.platform.sdk.hualala.request.SubmitOrderNewRequest;
import cn.freemud.platform.sdk.hualala.response.SubmitOrderNewResponse;
import cn.freemud.platform.sdk.hualala.vo.*;
import cn.freemud.resposne.SynchronizationOrderResponse;
import cn.freemud.util.ISASSOrderStatusConvertUtil;
import cn.freemud.util.OrderSubTypeConvertUtil;
import com.alibaba.fastjson.JSON;
import com.freemud.sdk.api.assortment.order.request.order.AssortmentSdkUpdateThirdOrderCodeRequest;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: ${FILE_NAME}
 * @Package com.freemud.mail.core
 * @Description: ${TODO}(用一句话描述该文件做什么)
 * @author: aiqi.gong
 * @date: 2019/3/21 18:37
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service("synchronizedOrderHualalaServiceImpl")
public class SynchronizedOrderHualalaServiceImpl implements SynchronizedOrderService {
    @Autowired
    private HualalaSdkService hualalaSdkService;
    /**
     * 是否推送订单消息到saas（0、不推，1、推）
     */
    private final int defaultIsSentMsg = 1;
    /**
     * 0 默认 不需要收银台数据， 1 需要收银台数据
     */
    private final int defaultIsCheackOut = 0;
    @Autowired
    private OpenPlatformHualalaAccountConfigService hualalaAccountConfigService;
    @Autowired
    private OrderCenterSdkService orderCenterSdkService;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public SynchronizationOrderResponse synchronizationOrder(String uuid, OrderBody orderBody,String mtchId,String subMchId,String serialNo,String privateKey,Integer type) {
        SynchronizationOrderResponse synchronizationOrderResponse = null;
        BaseResponse<OpenPlatformHualalaAccountConfigResponse> baseResponse = hualalaAccountConfigService.getHualalaAccountConfig(convertOrderBodyToHualalaAccountConfigRequest(uuid, orderBody));
        if (baseResponse == null || baseResponse.getData() == null || FmStatusCode.SUCCESS.getStatusCode() != baseResponse.getStatusCode()) {
            return new SynchronizationOrderResponse(false, baseResponse == null ? "" : JSON.toJSONString(baseResponse));
        }
        OpenPlatformHualalaAccountConfigResponse accountConfigResponse = baseResponse.getData();
        HuaLaLaCommonRequest huaLaLaCommonRequest = new HuaLaLaCommonRequest();
        huaLaLaCommonRequest.setDevID(accountConfigResponse.getDevId());
        huaLaLaCommonRequest.setGroupID(accountConfigResponse.getGroupId());
        huaLaLaCommonRequest.setMerchantsID(accountConfigResponse.getMerchantsId());
        huaLaLaCommonRequest.setShopID(Long.valueOf(orderBody.getOrderBean().getShopId()));
        huaLaLaCommonRequest.setVersion(accountConfigResponse.getVersion());
        huaLaLaCommonRequest.setTimestamp(System.currentTimeMillis());
        SubmitOrderNewRequest requestBody = convertOrderBodyToHualalaOrder(uuid, orderBody);
        HualalaBaseConfig hualalaBaseConfig = new HualalaBaseConfig();
        hualalaBaseConfig.setDevPwd(accountConfigResponse.getDevPwd());
        hualalaBaseConfig.setMerchantSecret(accountConfigResponse.getMerchantSecret());
        SubmitOrderNewResponse submitOrderNewResponse = hualalaSdkService.submitOrder(uuid, hualalaBaseConfig, huaLaLaCommonRequest, requestBody);
        if ("000".equals(submitOrderNewResponse.getCode())) {
            synchronizationOrderResponse = new SynchronizationOrderResponse(true, "");
            updateThirdOrderCode(orderBody.getOrderBean().getOid(), submitOrderNewResponse.getData().getOrderKey());
        } else {
            synchronizationOrderResponse = new SynchronizationOrderResponse(false, JSON.toJSONString(submitOrderNewResponse));
        }
        return synchronizationOrderResponse;
    }

    private void updateThirdOrderCode(String orderCode, String thirdOrderCode) {
        try {
            AssortmentSdkUpdateThirdOrderCodeRequest assortmentSdkUpdateThirdOrderCodeRequest = new AssortmentSdkUpdateThirdOrderCodeRequest();
            assortmentSdkUpdateThirdOrderCodeRequest.setOrderCode(orderCode);
            assortmentSdkUpdateThirdOrderCodeRequest.setThirdOrderCode(thirdOrderCode);
            orderCenterSdkService.updateThirdOrderCode(assortmentSdkUpdateThirdOrderCodeRequest);
        } catch (Exception ex) {
            logger.error("updateThirdOrderCode_errorm,orderCode:{},thirdOrderCode{},error:{}", orderCode, thirdOrderCode, ExceptionUtils.getStackTrace(ex));
        }
    }

    private OpenPlatformHualalaAccountConfigRequest convertOrderBodyToHualalaAccountConfigRequest(String uuid, OrderBody orderBody) {
        OpenPlatformHualalaAccountConfigRequest openPlatformHualalaAccountConfigRequest = new OpenPlatformHualalaAccountConfigRequest();
        openPlatformHualalaAccountConfigRequest.setRequestId(uuid);
        openPlatformHualalaAccountConfigRequest.setPartnerId(orderBody.getOrderBean().getCompanyId());
        return openPlatformHualalaAccountConfigRequest;
    }

    private SubmitOrderNewRequest convertOrderBodyToHualalaOrder(String uuid, OrderBody orderBody) {
        OrderBody.OrderBean orderBean = orderBody.getOrderBean();
        SubmitOrderNewRequest requestBody = new SubmitOrderNewRequest();
        requestBody.setHeader(convertOrderBodyToHualalaOrderCommonVo(uuid));
        requestBody.setIsSentMsg(defaultIsSentMsg);
        requestBody.setIsCheackOut(defaultIsCheackOut);
        requestBody.setMsgType(121);
        requestBody.setThirdOrderID(orderBean.getOid());
        requestBody.setOrderStatus(20);
        //requestBody.setPaidTotalAmount(orderBean.getPaidTotalAmount().intValue());
        WechatOrderMasterVo wechatOrderMasterVo = convertOrderBodyToHualalaWechatOrderMaster(uuid, orderBody);
        requestBody.setOrder(wechatOrderMasterVo);
        return requestBody;
    }

    private OrderCommonVo convertOrderBodyToHualalaOrderCommonVo(String uuid) {
        OrderCommonVo orderCommonVo = new OrderCommonVo();
        orderCommonVo.setTraceID(uuid);
        return orderCommonVo;
    }

    /**
     * 转哗啦啦（订单信息）
     *
     * @param uuid
     * @param orderBody
     * @return
     */
    private WechatOrderMasterVo convertOrderBodyToHualalaWechatOrderMaster(String uuid, OrderBody orderBody) {
        OrderBody.OrderBean orderBean = orderBody.getOrderBean();
        WechatOrderMasterVo wechatOrderMasterVo = new WechatOrderMasterVo();
        wechatOrderMasterVo.setOrderSubType(OrderSubTypeConvertUtil.iOrderSubTypeConvertToHualalaOrderSubType(orderBody.getOrderBean().getType()));
        wechatOrderMasterVo.setOrderStatus(ISASSOrderStatusConvertUtil.iOrderStatusConvertToHualalaOrderStatus(orderBean.getStatus()));
        wechatOrderMasterVo.setDiscountTotalAmount(getPointsConvertToYuan(orderBean.getDiscountTotalAmount()));
        wechatOrderMasterVo.setOrderRemark(orderBean.getRemark());
        if (wechatOrderMasterVo.getOrderSubType() != null && wechatOrderMasterVo.getOrderSubType().equals("120")) {
            wechatOrderMasterVo.setLongitude(orderBean.getLongitude() != null ? orderBean.getLongitude().toString() : "");
            wechatOrderMasterVo.setLatitude(orderBean.getLatitude() != null ? orderBean.getLatitude().toString() : "");
        }

        if (orderBean.getInvoiceInfo() != null) {
            wechatOrderMasterVo.setTaxNo(orderBean.getInvoiceInfo().getTaxNo());
            wechatOrderMasterVo.setInvoiceTitle(orderBean.getInvoiceInfo().getInvoiceTitle());
        }
        wechatOrderMasterVo.setDinners(1);
        wechatOrderMasterVo.setOrderTime(DateUtil.convert2String(new Date(), DateUtil.FORMAT_yyyyMMddHHmm));
        wechatOrderMasterVo.setTakeoutRemark(orderBean.getTakeoutRemark());
        wechatOrderMasterVo.setTakeoutAddress(orderBean.getTakeAddress());
        wechatOrderMasterVo.setOrderItem(this.convertOrderBodyToHualalaOrderItem(orderBody));
        wechatOrderMasterVo.setPayment(this.convertOrderBodyToHualalaOrderPayment(orderBody));
        if (orderBean.getAddInfo() != null) {
            wechatOrderMasterVo.setDeliveryAmount(getPointsConvertToYuan(orderBean.getAddInfo().getDeliveryAmount()));
        } else {
            wechatOrderMasterVo.setDeliveryAmount("0.0");
        }
        wechatOrderMasterVo.setServiceAmount("0");
        wechatOrderMasterVo.setChannelKey("310_wechat000");
        /**
         * 是否支付（0、未支付；1已支付），三方支付必传已支付 ：1
         */
        wechatOrderMasterVo.setIsAlreadyPaid("1");
        WechatUserInfoVo wechatUserInfoVo = new WechatUserInfoVo();
        /**
         * 临时解决哗啦啦重复出票的问题，将哗啦啦小票显示开个店的序号以及取餐码来关联开个店的小票
         */
        wechatUserInfoVo.setUserName(orderBody.getOrderBean().getDaySeq() + "-" + orderBody.getOrderBean().getOtherCode() + "-" + orderBody.getOrderBean().getUserName());
        wechatOrderMasterVo.setUserInfo(wechatUserInfoVo);
        return wechatOrderMasterVo;
    }

    private Integer getProductCountTotal(OrderBody.OrderBean orderBean) {
        Integer productCount = 0;
        List<OrderBody.OrderBean.ProductBean> productBeans = orderBean.getProductList();
        if (productBeans == null || productBeans.isEmpty()) {
            return productCount;
        }
        for (OrderBody.OrderBean.ProductBean productBean : productBeans) {
            productCount += productBean.getNumber();
        }
        return productCount;
    }

    /**
     * 转哗啦啦(菜品信息)
     *
     * @param orderBody
     * @return
     */
    private List<WechatOrderItemVo> convertOrderBodyToHualalaOrderItem(OrderBody orderBody) {
        OrderBody.OrderBean orderBean = orderBody.getOrderBean();
        List<WechatOrderItemVo> wechatOrderItemVos = new ArrayList<>();
        List<OrderBody.OrderBean.ProductBean> productBeans = orderBean.getProductList();
        if (productBeans == null || productBeans.isEmpty()) {
            return wechatOrderItemVos;
        }
        if (orderBean.getTakeoutPackagingFee() == null) {
            orderBean.setTakeoutPackagingFee(0);
        }
        Integer productCountTotal = getProductCountTotal(orderBean);
        BigDecimal nowTakeoutPackagingFee = BigDecimal.ZERO;
        BigDecimal orgTakeoutPackagingFee = new BigDecimal(orderBean.getTakeoutPackagingFee() / 100);
        int size = productBeans.size();
        for (int i = 0; i < size; i++) {
            OrderBody.OrderBean.ProductBean productBean = productBeans.get(i);
            WechatOrderItemVo wechatOrderItemVo = new WechatOrderItemVo();
            wechatOrderItemVo.setFoodID(productBean.getCustomerCode());
            wechatOrderItemVo.setFoodName(productBean.getProductName());
            wechatOrderItemVo.setFoodUnit(productBean.getSpecificationName());
            wechatOrderItemVo.setFoodUnitID(productBean.getCustomerCode());
            wechatOrderItemVo.setIsSetFood("0");
            /**
             * 菜品属性，0：正常菜，1：主菜，2：配菜，3：加价做法
             */
            wechatOrderItemVo.setIsBatching(0);
            wechatOrderItemVo.setIsGift(0);
            wechatOrderItemVo.setIsDiscount(0);
            /*if (productBean.getSalePrice() != null && productBean.getSalePrice().compareTo(0l) == 0) {
             *//**
             * 是否赠菜，0：不是，1：是
             *//*
                wechatOrderItemVo.setIsGift(1);
            }*/
            if (productBean.getSalePrice() != null && productBean.getSalePrice().compareTo(productBean.getPrice()) == -1) {
                wechatOrderItemVo.setIsDiscount(1);
            }
            wechatOrderItemVo.setFoodCount(productBean.getNumber());
            wechatOrderItemVo.setOriginPrice(getPointsConvertToYuan(productBean.getPrice()));
            if (i == size - 1) {
                wechatOrderItemVo.setTakeoutPackagingFee(orgTakeoutPackagingFee.subtract(nowTakeoutPackagingFee).toString());
            } else {
                BigDecimal currentProductTakeoutPackagingFee = this.calcProductTakeoutPackagingFee(productCountTotal, productBean.getNumber(), orgTakeoutPackagingFee);
                nowTakeoutPackagingFee = nowTakeoutPackagingFee.add(currentProductTakeoutPackagingFee);
                wechatOrderItemVo.setTakeoutPackagingFee(currentProductTakeoutPackagingFee.toString());
            }
            wechatOrderItemVo.setDuePrice(getPointsConvertToYuan(productBean.getPrice()));
            wechatOrderItemVos.add(wechatOrderItemVo);
        }
        return wechatOrderItemVos;
    }

    private static BigDecimal calcProductTakeoutPackagingFee(int totalProductCount, int currentProductCount, BigDecimal orgTakeoutPackagingFee) {
        BigDecimal currentProductTakeoutPackagingFee = new BigDecimal(currentProductCount).multiply(orgTakeoutPackagingFee.divide(new BigDecimal(totalProductCount), 2, BigDecimal.ROUND_HALF_UP));
        return currentProductTakeoutPackagingFee;
    }

    /**
     * 转哗啦啦(支付信息)
     * orderItem中所有菜品 成售价duePrice和打包费takeoutPackagingFee的计算和 + order中配送费deliveryAmount+服务费serviceAmount = payment中dueAmount之和 + order中优惠金额discountTotalAmount
     *
     * @param orderBody
     * @return
     */
    private List<PaymentDetailVo> convertOrderBodyToHualalaOrderPayment(OrderBody orderBody) {

        OrderBody.OrderBean orderBean = orderBody.getOrderBean();
        List<PaymentDetailVo> paymentDetailVos = new ArrayList<>();
        PaymentDetailVo paymentDetailVo = new PaymentDetailVo();
        /**
         * 高能预警，此处有坑，以后切到适配层的话，这里需要特殊处理
         */
        if (null != orderBean.getOriginalAmount()){
            paymentDetailVo.setDueAmount(orderBean.getOriginalAmount().toString());
        }
        /**
         * 参照OrderStatusEnum 会员卡支付需要回写支付状态 15未支付20已支付
         */
        paymentDetailVo.setPaymentStatus("20");
        paymentDetailVo.setPaymentSubjectID("11311010");
        paymentDetailVo.setPaymentSubjectName("微信支付");
        /**
         * 10：第三方支付，20：会员卡支付，30：积分支付，40：代金券支付，50：优惠券抵扣，60：储值（储值并消费），70：商家自定义科目，100：营销科目
         */
        paymentDetailVo.setPayWay("70");
        paymentDetailVos.add(paymentDetailVo);
        return paymentDetailVos;
    }

    private String getPointsConvertToYuan(Integer point) {
        return new BigDecimal(point == null ? 0 : point).divide(new BigDecimal(100)).toString();
    }

    private String getPointsConvertToYuan(Long point) {
        return getPointsConvertToYuan(point != null ? point.intValue() : 0);
    }


}
