package cn.freemud.service;

import cn.freemud.amp.body.OrderBody;
import cn.freemud.annotations.OrderReportType;
import cn.freemud.enums.OrderReportEnum;
import cn.freemud.enums.OrderStatus;
import cn.freemud.enums.WechatSyncStatus;
import cn.freemud.request.ProductRandomVo;
import cn.freemud.request.SaoBeiFoodUploadRequset;
import cn.freemud.resposne.SaoBeiFoodUploadResponse;
import cn.freemud.resposne.SynchronizationOrderResponse;
import cn.freemud.service.thirdparty.LCSWUploadClient;
import cn.freemud.util.ProductRandomUtil;
import cn.freemud.util.Rfc3339Util;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: SaoBeiOrderPushServiceImpl
 * @Package cn.freemud.service
 * @Description:
 * @author: yongchun.gu
 * @date: 2019/5/27 16:22
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Slf4j
@Service("saoBeiOrderFoodServiceImpl")
@OrderReportType(OrderReportEnum.SAOBEI)
public class SaoBeiOrderFoodServiceImpl implements  SynchronizedOrderService  {
    private static String ENTRYPAGE = "pages/storeListShop";


    @Autowired
    private LCSWUploadClient lcswUploadClient;

    @Override
    public SynchronizationOrderResponse synchronizationOrder(String uuid, OrderBody orderBody,String mtchId,String subMchId,String serialNo,String privateKey,Integer type) {
        SaoBeiFoodUploadRequset requset = new SaoBeiFoodUploadRequset();
        requset.setOut_shop_no(orderBody.getOrderBean().getShopId());
        requset.setAction_time(getRFC3339(orderBody.getOrderBean().getGmtCreate()));
        requset.setLogin_token(orderBody.getSyncStatusInfo().getSessionKey());
        requset.setOpenid(orderBody.getSyncStatusInfo().getOpenId());
        requset.setOrder_entry(ENTRYPAGE);
        requset.setMerchant_no(orderBody.getSyncStatusInfo().getMchId());
        if(Objects.equals(orderBody.getSyncStatusInfo().getTerminalId(), null)) {
            SynchronizationOrderResponse synchronizationOrderResponse = new SynchronizationOrderResponse(true, "不是扫呗支付订单");
            return synchronizationOrderResponse;
        }
        requset.setTerminal_id(orderBody.getSyncStatusInfo().getTerminalId());
        if (OrderStatus.TAKE_ORDER.getCode().equals(orderBody.getOrderBean().getStatus())) {
            //支付完成
            requset.setStatus(WechatSyncStatus.PAY_SUCCESS.getCode());
        } else if (OrderStatus.WAIT_PAY.getCode().equals(orderBody.getOrderBean().getStatus())) {
            //支付单创建
            requset.setStatus(WechatSyncStatus.CREATE_DEAL.getCode());
        } else {
            //不是下单也不是支付 不需要通知
            return null;
        }
        List<SaoBeiFoodUploadRequset.Dish> dishes = new ArrayList<>();
        for (OrderBody.OrderBean.ProductBean productBean : orderBody.getOrderBean().getProductList()) {
            SaoBeiFoodUploadRequset.Dish dish = new SaoBeiFoodUploadRequset.Dish();
            ProductRandomVo productRandomVo = ProductRandomUtil.getRandomProduct(productBean.getProductId());
            dish.setCount(productBean.getNumber());
            dish.setName(productRandomVo.getName());
            dish.setOut_dish_no(productRandomVo.getId());
            dish.setPrice(productBean.getSalePrice().intValue());
            dish.setUnit("BY_SHARE");
            dishes.add(dish);
        }
        // 计算优惠金额
        List<OrderBody.OrderBean.AccountBean> accountList = orderBody.getOrderBean().getAccountList();
        int discountAmount = 0;
        if(accountList != null && !CollectionUtils.isEmpty(accountList)) {
            for(OrderBody.OrderBean.AccountBean accountBean : accountList) {
                try {
                    Long price = accountBean.getPrice() == null ? 0 : accountBean.getPrice();
                    if(price < 0) {
                        discountAmount = discountAmount - price.intValue();
                    }
                } catch (Exception e) {
                }
            }
        }
        requset.setTransaction_id(orderBody.getSyncStatusInfo().getTransactionId());
        requset.setOut_trade_no(orderBody.getSyncStatusInfo().getEndTransId());
        requset.setOut_order_no(orderBody.getSyncStatusInfo().getEndTransId());
        requset.setPay_time(Rfc3339Util.dateToRfc3339(new Date()));
        requset.setUser_amount(orderBody.getOrderBean().getAmount().intValue());
        requset.setTotal_amount(discountAmount + orderBody.getOrderBean().getAmount().intValue());
        requset.setDiscount_amount(discountAmount);
        requset.setDish_list(dishes);
        SaoBeiFoodUploadResponse response = null;
        try {
            response = lcswUploadClient.orderFoodUpload(requset);
            log.info("saoBeiOrderFoodServiceImpl oid:{};request:{};response:{}", orderBody.getOrderBean().getOid(), JSON.toJSONString(requset), JSON.toJSONString(response));
        }catch (Exception e){
            log.info("saoBeiOrderFoodServiceImplEnd oid:{};request:{};response:{};exception:{}", orderBody.getOrderBean().getOid(), JSON.toJSONString(requset), response,JSON.toJSONString(e));
        }
        if(response == null){
            SynchronizationOrderResponse synchronizationOrderResponse = new SynchronizationOrderResponse(false, "");
            return synchronizationOrderResponse;
        }
        if (!response.getReturn_code().equals("01") || !response.getResult_code().equals("01")) {
            SynchronizationOrderResponse synchronizationOrderResponse = new SynchronizationOrderResponse(false, response.getReturn_msg());
            return synchronizationOrderResponse;
        } else {
            SynchronizationOrderResponse synchronizationOrderResponse = new SynchronizationOrderResponse(true, "");
            return synchronizationOrderResponse;
        }
    }



    public   String getRFC3339(long time) {
        String result = "";
        try {
            DateTime dt = new DateTime(time, DateTimeZone.UTC);
            result = dt.toString();
        } catch (Exception e) {

        }
        return result;
    }

    public  String orderStatus(int payStatus)
    {
        switch (payStatus)
        {
            case 1:
                 return  "CREATE_DEAL";
            case  2:
                return  "PAY_SUCCESS";
                default: return "";
        }
    }









}
