package cn.kk.spring_simple_operation.service.impl;

import cn.kk.spring_simple_operation.entity.APlusProduct;
import cn.kk.spring_simple_operation.entity.SyncProductPublish;
import cn.kk.spring_simple_operation.entity.VisualAPlusPlan;
import cn.kk.spring_simple_operation.entity.VisualDesigner;
import cn.kk.spring_simple_operation.mapper.APlusProductMapper;
import cn.kk.spring_simple_operation.mapper.SyncProductPublishMapper;
import cn.kk.spring_simple_operation.mapper.VisualDesignerMapper;
import cn.kk.spring_simple_operation.model.dto.SkuPeopleNameDto;
import cn.kk.spring_simple_operation.model.vo.APlusPlanNoHandlerVo;
import cn.kk.spring_simple_operation.model.vo.PublishInfoVo;
import cn.kk.spring_simple_operation.service.APlusProductService;
import cn.kk.spring_simple_operation.service.VisualAPlusPlanService;
import cn.kk.spring_simple_operation.service.VisualDesignLogService;
import cn.kk.spring_simple_operation.utils.CommonUtils;
import cn.kk.spring_simple_operation.utils.DateUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * <p>
 * A+产品 服务实现类
 * </p>
 *
 * @author guokunkun
 * @since 2025-03-18
 */
@Service
@Slf4j
public class APlusProductServiceImpl extends ServiceImpl<APlusProductMapper, APlusProduct> implements APlusProductService {

	@Resource
	private VisualDesignLogService visualDesignLogService;

	@Resource
	private SyncProductPublishMapper syncProductPublishMapper;

	@Resource
	private VisualDesignerMapper visualDesignerMapper;

	@Resource
	private VisualAPlusPlanService visualAPlusPlanService;



	@Override
	public List<APlusPlanNoHandlerVo> exportAPlusPlanNoHandlerData() {
		List<VisualAPlusPlan> list = visualAPlusPlanService.list(Wrappers.<VisualAPlusPlan>lambdaQuery()
				.eq(VisualAPlusPlan::getStatus, 3)
				.eq(VisualAPlusPlan::getNoHandleReason, 1)
				.in(VisualAPlusPlan::getExecutorNumber, "", "is_delete")
		);
		if (CollectionUtils.isEmpty(list)) {
			throw new RuntimeException("无数据！");
		}
		Integer startTime = DateUtils.getCurrentTimeSecond();
		List<APlusPlanNoHandlerVo> exportList = new LinkedList<>();
		CopyOnWriteArrayList<VisualAPlusPlan> myList = new CopyOnWriteArrayList<>(list);
		myList.forEach(t -> {
			HashSet<String> relationSkuSet = new HashSet<>(getRelatedProduct(CommonUtils.singletonList(t.getSku())));
			List<VisualAPlusPlan> collect = myList.stream().filter(s -> relationSkuSet.contains(s.getSku())).collect(Collectors.toList());
			if (collect.size() <= 1) {
				// 就一个，放过
				myList.remove(t);
				return;
			}
			APlusPlanNoHandlerVo vo = new APlusPlanNoHandlerVo();
			vo.setId(collect.stream().map(id -> String.valueOf(id.getId())).collect(Collectors.joining(",")));
			List<String> skuList = collect.stream().map(VisualAPlusPlan::getSku).collect(Collectors.toList());
			vo.setSku(String.join(",", skuList));
			vo.setSolarName(baseMapper.getSolarName(skuList));
			exportList.add(vo);
			myList.removeAll(collect);
		});

		Integer endTime = DateUtils.getCurrentTimeSecond();
		log.info("exportAPlusPlanNoHandlerData 耗时：{} 分钟", (endTime - startTime) / 60);
		return exportList;
	}

	@Override
	public List<String> getRelatedProduct(List<String> list) {
		if (Objects.isNull(list)) {
			return Collections.emptyList();
		}
		list = new ArrayList<>(list);
		list.removeIf(StringUtils::isEmpty);
		if (CollectionUtils.isEmpty(list)) {
			return Lists.newArrayList();
		}

		List<String> skuList = baseMapper.getSuperiorSkuList(list);
		Set<String> skus = new HashSet<>();
		skus.addAll(list);
		if (!CollectionUtils.isEmpty(skuList)) {
			skuList.stream().filter(t -> !StringUtils.isEmpty(t)).forEach(s -> {
				String[] split = s.split(",");
				skus.addAll(Arrays.asList(split));
			});
		}

		skuList = new LinkedList<>(skus);

		List<String> relatedProduct = baseMapper.getRelatedProduct(skuList);

		return org.apache.commons.collections4.CollectionUtils.union(relatedProduct, list)
				.stream().filter(t -> !StringUtils.isEmpty(t)).collect(Collectors.toList());
	}

	@Override
	public void setAPlusProductUploadInfo(List<SkuPeopleNameDto> list) {

		int count = 0;
		Integer currentTimeSecond = DateUtils.getCurrentTimeSecond();
		for (SkuPeopleNameDto skuPeopleNameDto : list) {
			List<APlusProduct> aPlusProducts = baseMapper.selectList(Wrappers.<APlusProduct>lambdaQuery()
					.eq(APlusProduct::getSku, skuPeopleNameDto.getSku())
					.eq(APlusProduct::getSite, "Amazon.com")
					.select(APlusProduct::getId, APlusProduct::getSku, APlusProduct::getSite, APlusProduct::getAPlusPlanId)
			);
			if (CollectionUtils.isEmpty(aPlusProducts)) {
				log.error("sku:{}, site:{}, 未找到对应的A+产品", skuPeopleNameDto.getSku(), "Amazon.com");
				continue;
			}
			APlusProduct aPlusProduct = aPlusProducts.get(0);
			List<APlusProduct> aPlusProductList = baseMapper.selectList(Wrappers.<APlusProduct>lambdaQuery()
					.eq(APlusProduct::getAPlusPlanId, aPlusProduct.getAPlusPlanId())
					.select(APlusProduct::getId, APlusProduct::getSku, APlusProduct::getSite));
			aPlusProductList.add(aPlusProduct);
			for (APlusProduct plusProduct : aPlusProductList) {
				List<SyncProductPublish> syncProductPublishes = syncProductPublishMapper.selectList(Wrappers.<SyncProductPublish>lambdaQuery()
						.eq(SyncProductPublish::getSku, plusProduct.getSku())
						.eq(SyncProductPublish::getSite, plusProduct.getSite())
						.select(SyncProductPublish::getThirtyDaySales)
				);
				if (CollectionUtils.isEmpty(syncProductPublishes)) {
					log.error("sku:{}, site:{}, 未找到对应的销量数据", skuPeopleNameDto.getSku(), "Amazon.com");
					continue;
				}
				SyncProductPublish syncProductPublish = syncProductPublishes.get(0);
				plusProduct.setSale30(syncProductPublish.getThirtyDaySales());
			}
			List<VisualDesigner> visualDesigners = visualDesignerMapper.selectList(Wrappers.<VisualDesigner>lambdaQuery()
					.eq(VisualDesigner::getUserName, skuPeopleNameDto.getPeopleName())
					.in(VisualDesigner::getDepartmentKey, "a_plus_plan")
			);
			if (CollectionUtils.isEmpty(visualDesigners)) {
				log.error("userName:{}, 未找到对应的视觉设计师", skuPeopleNameDto.getPeopleName());
				continue;
			}
			VisualDesigner visualDesigner = visualDesigners.get(0);

			for (APlusProduct plusProduct : aPlusProductList) {
				plusProduct
						.setIsUploadBackstage(2)
						.setUploadBackstageId(Long.valueOf(visualDesigner.getUserId()))
						.setUploadBackstageUser(visualDesigner.getUserName())
						.setUploadBackstageTime(currentTimeSecond)
				;
				baseMapper.updateById(plusProduct);
				visualDesignLogService.addLog("a_plus_product",
						String.format("sku:%s, site:%s, 上传A+产品信息修改为：上传人：%s，上传时间：%s", plusProduct.getSku(), plusProduct.getSite(), visualDesigner.getUserName(), DateUtils.format10YMD(currentTimeSecond)),
						plusProduct.getId());
				count++;
			}

		}
		log.info("共上传{}个A+产品信息", count);

	}

	@Override
	public List<PublishInfoVo> exportAPlusPublishData() {
		Map<String, List<APlusProduct>> siteMap = this.list(Wrappers.<APlusProduct>lambdaQuery().eq(APlusProduct::getAPlusPublishPlatStatus, 1).select(APlusProduct::getSku, APlusProduct::getSite))
				.stream().collect(Collectors.groupingBy(APlusProduct::getSite));

		List<Long> idList = new LinkedList<>();
		Set<String> skuSet = new HashSet<>(51200);

		siteMap.forEach((site, list) -> {
			for (APlusProduct t : list) {
				if (skuSet.contains(t.getSku() + "#" + site)) continue;
				List<String> relatedProduct = getRelatedProduct(Collections.singletonList(t.getSku()));
				relatedProduct.forEach(sku -> skuSet.add(sku + "#" + t.getSku()));
				if (relatedProduct.size() <= 1) continue;
				List<APlusProduct> aPlusProducts = this.list(Wrappers.<APlusProduct>lambdaQuery()
						.in(APlusProduct::getSku, relatedProduct)
						.eq(APlusProduct::getSite, site)
						.select(APlusProduct::getId, APlusProduct::getAPlusPublishPlatStatus)
				);
				Optional<APlusProduct> published = aPlusProducts.stream().filter(p -> p.getAPlusPublishPlatStatus() == 1).findFirst();
				List<Long> collect = aPlusProducts.stream().filter(p -> p.getAPlusPublishPlatStatus() == 0).map(APlusProduct::getId).collect(Collectors.toList());
				// 同站点变体，既存在已发布的，又存在未发布的
				if (published.isPresent() && !CollectionUtils.isEmpty(collect)) {
					idList.addAll(collect);
				}
			}
		});

		if (CollectionUtils.isEmpty(idList)) {
			log.error("没有数据需要查询！");
		}
		List<PublishInfoVo> publishInfoVOList = baseMapper.getPublishInfoByIds(idList);
		if (CollectionUtils.isEmpty(publishInfoVOList)) {
			log.error("未查询到数据！");
		}
		return publishInfoVOList;
	}
}
