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

import com.yc.ship.framework.common.lang.Asserts;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.tenant.core.context.TenantContextHolder;
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.system.api.dict.DictDataApi;
import com.yc.ship.module.system.api.dict.dto.DictDataRespDTO;
import com.yc.ship.module.trade.controller.admin.order.vo.order.TradeDetailRespVO;
import com.yc.ship.module.trade.controller.admin.order.vo.order.TradeOrderRespVO;
import com.yc.ship.module.trade.controller.app.otc.vo.AppTradeOrderReqVO;
import com.yc.ship.module.trade.controller.app.otc.vo.AppTradeOrderRespVO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeOrderLogDO;
import com.yc.ship.module.trade.dal.mysql.order.TradeDetailMapper;
import com.yc.ship.module.trade.dal.mysql.order.TradeOrderLogMapper;
import com.yc.ship.module.trade.enums.TradeOrderOperateTypeEnum;
import com.yc.ship.module.trade.service.order.TradeOrderQueryService;
import com.yc.ship.module.trade.service.otc.AppTradeOrderService;
import com.yc.ship.module.trade.service.otc.OtcTradeOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.stream.Collectors;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception0;


/**
 * &#064;Description 旅行社订单交易service实现
 * &#064;Date 2025/8/12 08:34
 * @author qsl
 */
@Service
@Slf4j
public class AppTradeOrderServiceImpl implements AppTradeOrderService {

    @Resource
    private OtaDistributorApi otaDistributorApi;
    @Resource
    private OtcTradeOrderService otcTradeOrderService;
    @Resource
    private TradeOrderQueryService tradeOrderQueryService;
    @Resource
    private TradeDetailMapper tradeDetailMapper;
    @Resource
    private TradeOrderLogMapper tradeOrderLogMapper;
    @Resource
    private DictDataApi dictDataApi;

    @Override
    public CommonResult<List<AppTradeOrderRespVO>> miniTradeOrderPage(AppTradeOrderReqVO.TradeOrderQueryReqVO reqVO) {
        DistributorRespDTO distributorRespDTO = otaDistributorApi.getDistributorByAccountTenantId(TenantContextHolder.getTenantId()).getCheckedData();
        if (distributorRespDTO != null) {
            Long tenantId = distributorRespDTO.getTenantId();
            if (StringUtils.isBlank(reqVO.getTravelDate())) {
                throw exception0(30_100, "游玩日期不能为空");
            }
            if (StringUtils.isBlank(reqVO.getCredentialNo()) && StringUtils.isBlank(reqVO.getMobile())) {
                throw exception0(30_100, "游客证件号码/联系人手机号不能同时为空");
            }
            List<Integer> orderStatus = reqVO.getOrderStatus();
            orderStatus.add(7);
            orderStatus.add(10);
            orderStatus.add(13);
            CommonResult<List<TradeOrderRespVO>> result = tradeOrderQueryService.orderList(tenantId, reqVO.getOrderStatus(), reqVO.getTravelDate(), reqVO.getCredentialNo(), reqVO.getMobile());
            List<AppTradeOrderRespVO> respList = BeanUtils.toBean(result.getCheckedData(), AppTradeOrderRespVO.class);
            respList.forEach(spu -> {
                TenantUtils.execute(tenantId, () -> {
                    //获取规格数量
                    List<TradeDetailRespVO> list = tradeDetailMapper.getOrderDetail(spu.getId());
                    List<DictDataRespDTO> dictList = dictDataApi.getDictDataList("project_specification_type");
                    StringJoiner joiner = new StringJoiner("、");
                    int totalNum = 0;
                    for (DictDataRespDTO dict : dictList) {
                        long count = list.stream().filter(item -> dict.getValue().equals(item.getSpecType()) && (item.getVoucherStatus()==1||item.getVoucherStatus()==2||item.getVoucherStatus()==3||item.getVoucherStatus()==6)).count();
                        if (count > 0) {
                            joiner.add(dict.getLabel() + "*" + count);
                        }
                        totalNum+= (int) count;
                    }
                    spu.setSpecNumber(joiner.toString());
                    spu.setNum(totalNum);

                    spu.setIsPerfect(0);
                    // 获取订单操作记录
                    List<TradeOrderLogDO> tradeOrderLogList = tradeOrderLogMapper.selectList(TradeOrderLogDO::getOrderId, spu.getId());
                    tradeOrderLogList = tradeOrderLogList.stream().filter(tradeOrderLogDO -> Objects.equals(tradeOrderLogDO.getOperateType(), TradeOrderOperateTypeEnum.ORDER_PERFECT.getType())).collect(Collectors.toList());
                    if (!tradeOrderLogList.isEmpty()) {
                        spu.setIsPerfect(1);
                    }
                    if (!list.isEmpty()) {
                        spu.setProductName(list.get(0).getProductName());
                    }
                });
            });
            return CommonResult.success(respList);
        }
        return CommonResult.error(30_100, "未找到平台信息");
    }

    @Override
    public CommonResult<AppTradeOrderRespVO> miniOrderInfoById(Long id) {
        TradeOrderRespVO tradeOrderRespVO = otcTradeOrderService.getOrderInfo(id);
        AppTradeOrderRespVO appTradeOrderRespVO = BeanUtils.toBean(tradeOrderRespVO, AppTradeOrderRespVO.class);
        DistributorRespDTO distributorRespDTO = otaDistributorApi.getDistributorByAccountTenantId(TenantContextHolder.getTenantId()).getCheckedData();
        if (distributorRespDTO != null) {
            List<TradeDetailRespVO> detailList = appTradeOrderRespVO.getTradeDetailList();
            if (!detailList.isEmpty()) {
                appTradeOrderRespVO.setTradeDetailList(detailList);
            }
        }
        return CommonResult.success(appTradeOrderRespVO);
    }

    @Override
    public CommonResult<List<TradeDetailRespVO>> miniTradeOrderDetailList(Long orderId) {
        Asserts.isTrue(orderId!=null,"订单ID不能为空");
        DistributorRespDTO distributorRespDTO = otaDistributorApi.getDistributorByAccountTenantId(TenantContextHolder.getTenantId()).getCheckedData();
        if (distributorRespDTO != null) {
            Long tenantId = distributorRespDTO.getTenantId();
            Long oldTenantId = TenantContextHolder.getTenantId();
            try {
                TenantContextHolder.setTenantId(tenantId);
                List<TradeDetailRespVO> list = tradeDetailMapper.getOrderIdDetailV2(orderId);
                return CommonResult.success(list);
            }finally {
                TenantContextHolder.setTenantId(oldTenantId);
            }
        }
        return CommonResult.error(30_100, "未找到平台信息");
    }


}
