package com.yc.ship.module.trade.service.ota.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.util.object.ObjectUtils;
import com.yc.ship.framework.tenant.core.util.TenantUtils;
import com.yc.ship.module.ota.api.OtaDistributorApi;
import com.yc.ship.module.ota.api.dto.DistributorRespDTO;
import com.yc.ship.module.trade.controller.admin.order.vo.rule.RefundAuditNotifyReqVO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeOrderDO;
import com.yc.ship.module.trade.dal.dataobject.refund.RefundAuditDO;
import com.yc.ship.module.trade.dal.dataobject.refund.RefundDO;
import com.yc.ship.module.trade.dal.dataobject.refund.RefundDetailDO;
import com.yc.ship.module.trade.enums.SellMethodEnum;
import com.yc.ship.module.trade.service.order.TradeOrderRepositoryService;
import com.yc.ship.module.trade.service.ota.MeiTuanService;
import com.yc.ship.module.trade.service.ota.OtaService;
import com.yc.ship.module.trade.service.ota.OtaStandardService;
import com.yc.ship.module.trade.service.ota.TiktokLifeService;
import com.yc.ship.module.trade.service.refund.TradeRefundRepositoryService;
import com.yc.ship.module.trade.service.supplier.TradeStandardSupplierService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * &#064;Description ：ota标准接口实现
 * &#064;Author ：qsl
 * &#064;Date ：2025/6/17 20:50
 */
@Service
@Slf4j
public class OtaStandardServiceImpl implements OtaStandardService {
    @Resource
    private TradeRefundRepositoryService tradeRefundRepositoryService;
    @Resource
    private TradeOrderRepositoryService tradeOrderRepositoryService;
    @Resource
    private OtaDistributorApi otaDistributorApi;
    @Resource
    private TradeStandardSupplierService tradeStandardSupplierService;

    @Autowired
    private TiktokLifeService tiktokLifeService;
    @Resource
    private Map<String, OtaService> otaServiceMap;
    @Resource
    private MeiTuanService meiTuanService;

    String OTA_SERVICE = "%sService";

    @Override
    public CommonResult<?> notifyRefundAuditResult(Long auditId) {
        RefundAuditDO refundAuditDO = tradeRefundRepositoryService.getRefundAuditById(auditId);
        RefundDO refundDO = tradeRefundRepositoryService.getById(refundAuditDO.getRefundId());
        TradeOrderDO tradeOrderDO = tradeOrderRepositoryService.getById(refundDO.getOrderId());
        if (ObjectUtil.equal(tradeOrderDO.getSellMethod(), SellMethodEnum.OTA.getType())) {
            //分销商
            DistributorRespDTO distributorRespDTO = otaDistributorApi.getDistributorById(Long.parseLong(tradeOrderDO.getSourceId()));

            Map<String, Object> map = handleParams(tradeOrderDO, refundDO, refundAuditDO);
            if (distributorRespDTO != null) {
                log.debug("开始发送分销退票审核通知：" + refundDO.getId());
                String otaCode = distributorRespDTO.getTypeCode();
                OtaService otaService = otaServiceMap.get(String.format(OTA_SERVICE, otaCode));
                otaService.refundNotice(distributorRespDTO, map);
            }

        } else if (ObjectUtils.equalsAny(tradeOrderDO.getSellMethod(), SellMethodEnum.OTC.getType(), SellMethodEnum.OTA_SYSTEM.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType())) {

            DistributorRespDTO distributorRespDTO = otaDistributorApi.getDistributorById(Long.parseLong(tradeOrderDO.getSourceId()));
            RefundAuditNotifyReqVO refundAuditNotifyReqVO = new RefundAuditNotifyReqVO();
            refundAuditNotifyReqVO.setAuditResult(refundAuditDO.getAuditStatus());
            refundAuditNotifyReqVO.setRefundId(Long.parseLong(refundDO.getOtaRefundNo()));
            refundAuditNotifyReqVO.setSupplierRefundNo(refundDO.getId().toString());
            TenantUtils.execute(distributorRespDTO.getAccountTenantId(), () -> {
                tradeStandardSupplierService.handleSupplierRefundAuditNotify(refundAuditNotifyReqVO);
            });

        }
        return CommonResult.success(null);
    }


    @Override
    public void otaCheckNotice(Map<String, Object> params) {
        //根据检票号查询所需要的信息
        try {
            List<Map<String, Object>> mapList = tradeOrderRepositoryService.getDetailInfoByDetailId(params);
            if (CollUtil.isNotEmpty(mapList)) {
                Integer sellMethod = MapUtil.getInt(mapList.get(0), "sell_method");
                if (ObjectUtil.equals(sellMethod, SellMethodEnum.OTA.getType())) {
                    DistributorRespDTO distributor = otaDistributorApi.getDistributorById(MapUtil.getLong(mapList.get(0), "source_id"));
                    if (distributor!=null) {
                        String otaCode = distributor.getTypeCode();
                        OtaService otaService = otaServiceMap.get(String.format(OTA_SERVICE, otaCode));
                        mapList.forEach(map -> {
                            log.debug("开始发送核销消息通知：orderNo=" + MapUtil.getStr(map, "orderNo"));
                            otaService.consumeNotice(distributor, map);
                        });
                    }
                }
            }
        } catch (Exception e) {
            log.error("OTA核销通知失败：" + e);
        }

    }


    @Override
    public boolean notifyFailedVoucherInfoOtaPush(String voucherCode) {

        log.error("核销通知失败门票重新推送：voucherCode=" + voucherCode);
        // 核销通知失败的门票信息
        Map<String, Object> param = new HashMap<>(16);
        param.put("voucherCode", voucherCode);
        List<Map<String, Object>> notifyFailedTicketList = tradeOrderRepositoryService.queryNotifyFailedVoucherInfo(param);
        for (Map<String, Object> map : notifyFailedTicketList) {
            DistributorRespDTO distributor = otaDistributorApi.getDistributorById(MapUtil.getLong(map, "source_id"));
            if (distributor!=null) {
                String otaCode = distributor.getTypeCode();
                OtaService otaService = otaServiceMap.get(String.format(OTA_SERVICE, otaCode));
                log.info("开始发送核销消息通知：orderNo=" + MapUtil.getStr(map, "orderNo"));
                otaService.consumeNotice(distributor, map);
            }
        }

        return true;
    }

    @NotNull
    private Map<String, Object> handleParams(TradeOrderDO tradeOrderDO, RefundDO refundDO, RefundAuditDO refundAuditDO) {
        // 订单退票数
        List<RefundDetailDO> refundDetailList = tradeRefundRepositoryService.getRefundDetailList(refundDO.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("order_no", tradeOrderDO.getOrderNo());
        map.put("refund_id", refundDO.getId());
        map.put("external_order_no", tradeOrderDO.getExternalOrderNo());
        map.put("item_id", StrUtil.isBlank(tradeOrderDO.getItemId()) ? "" : tradeOrderDO.getItemId());
        map.put("audit_status", refundAuditDO.getAuditStatus());
        map.put("remark", refundAuditDO.getAuditAdvice());
        map.put("create_time", refundDO.getCreateTime());
        map.put("refund_tickets", refundDetailList.size());
        return map;
    }

    /**
     * OTA产品价格库存通知
     *
     * @param data
     */
    @Override
    public void otaProductPriceStockNotify(String data) {
        String[] msg = data.split("_");
        String distributorId = msg[0];
        String distributorProductId = msg[1];
        String startTime = msg[2];
        String endTime = msg[3];
        DistributorRespDTO distributorResult = otaDistributorApi.getDistributorById(Long.parseLong(distributorId));
        if (distributorResult==null) {
            return;
        }
        meiTuanService.asynOtaProductPriceStockNotice(distributorResult, Long.parseLong(distributorProductId), startTime, endTime);
    }
}
