package cn.kk.spring_simple_operation.service.impl;

import cn.kk.spring_simple_operation.entity.PhotoProgress;
import cn.kk.spring_simple_operation.entity.PhotoProgressPerson;
import cn.kk.spring_simple_operation.entity.VisualDesignLog;
import cn.kk.spring_simple_operation.entity.VisualDesigner;
import cn.kk.spring_simple_operation.enums.StatusEnum;
import cn.kk.spring_simple_operation.mapper.PhotoProgressMapper;
import cn.kk.spring_simple_operation.model.dto.SkuSiteDTO;
import cn.kk.spring_simple_operation.model.vo.PhotoProgressPhotographerVo;
import cn.kk.spring_simple_operation.model.vo.PhotoSkuInfo;
import cn.kk.spring_simple_operation.service.*;
import cn.kk.spring_simple_operation.utils.CommonUtils;
import cn.kk.spring_simple_operation.utils.DateUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 图片协同系统 服务实现类
 * </p>
 *
 * @author guokunkun
 * @since 2024-12-25
 */
@Slf4j
@Service
public class PhotoProgressServiceImpl extends ServiceImpl<PhotoProgressMapper, PhotoProgress> implements PhotoProgressService {

	@Resource
	private VisualDesignLogService visualDesignLogService;

	@Resource
	private VisualDesignerService visualDesignerService;

	@Resource
	private DeptGroupService deptGroupService;

	@Resource
	private PhotoProgressPersonService photoProgressPersonService;

	@Resource
	private TransactionTemplate transactionTemplate;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void setUploadStatusIsDeleted(List<SkuSiteDTO> list) {
		List<PhotoProgress> listPhotoProgress = baseMapper.getListBySku(list.stream().map(SkuSiteDTO::getSku).collect(Collectors.toList()));
		List<Long> ids = listPhotoProgress.stream()
				.filter(t -> t.getSimpleVideoUploadStatus() != 5)
				.map(PhotoProgress::getId)
				.collect(Collectors.toList());

		update(Wrappers.<PhotoProgress>lambdaUpdate().in(PhotoProgress::getId, ids)
				.set(PhotoProgress::getSimpleVideoUploadStatus, 5)
		);
		visualDesignLogService.addBatchLog("photo_progress", "根据文件将sku的视频上传后台状态设置为已删除", ids);
	}


	@Override
	public void getVideoSkuArea() {
		//List<PhotoSkuInfo> skuInfoList = baseMapper.getSkuInfo();
		//ConcurrentHashMap<String, Integer> areaCountSingleMap = new ConcurrentHashMap<>();
		//areaCountSingleMap.put("深圳", 0);
		//areaCountSingleMap.put("武汉", 0);
		//areaCountSingleMap.put("合肥", 0);
		//areaCountSingleMap.put("长沙", 0);
		//ConcurrentHashMap<String, ConcurrentSkipListSet<String>> areaCountMainMap = new ConcurrentHashMap<>();
		//areaCountMainMap.put("深圳", new ConcurrentSkipListSet<>());
		//areaCountMainMap.put("武汉", new ConcurrentSkipListSet<>());
		//areaCountMainMap.put("合肥", new ConcurrentSkipListSet<>());
		//areaCountMainMap.put("长沙", new ConcurrentSkipListSet<>());
		//
		//
		//skuInfoList.forEach(t -> {
		//	String region = CommonUtils.getRegion(t.getDept());
		//	areaCountSingleMap.put(region, areaCountSingleMap.getOrDefault(region, 0) + 1);
		//
		//	ConcurrentSkipListSet<String> skuList = areaCountMainMap.get(region);
		//	if (Objects.isNull(skuList)) {
		//		throw new RuntimeException("区域：" + region + "不存在");
		//	}
		//
		//	switch (t.getProductType()) {
		//		case 1:
		//			// 普通产品
		//			if (StringUtils.isEmpty(t.getRelativeSku())) {
		//				skuList.add(t.getSku());
		//			}
		//			else {
		//				skuList.add(t.getRelativeSku());
		//			}
		//			break;
		//		case 2:
		//			// 组合产品
		//			if (t.getIsCombVariant() == 0) {
		//				//母体
		//				skuList.add(t.getSku());
		//			}
		//			else if (t.getIsCombVariant() == 1) {
		//				// 变体，添加他的母体
		//				skuList.add(t.getCombParentSku());
		//			}
		//			break;
		//		case 3:
		//			skuList.add(t.getRelativeSku());
		//			break;
		//		default:
		//			log.error("产品类型错误：" + t.getProductType());
		//			break;
		//	}
		//
		//});
		//
		//AtomicInteger totalCount = new AtomicInteger(0);
		//log.info("区域统计结果：----母体sku总数");
		//areaCountMainMap.forEach((k, v) -> {
		//	log.info("区域：" + k + "，SKU数量：" + v.size());
		//	totalCount.addAndGet(v.size());
		//});
		//log.info("合计： " + totalCount.get());
		//
		//totalCount.set(0);
		//
		//log.info("区域统计结果：----sku总数");
		//areaCountSingleMap.forEach((k, v) -> {
		//	log.info("区域：" + k + "，SKU数量：" + v);
		//	totalCount.addAndGet(v);
		//});
		//log.info("合计： " + totalCount.get());
		//
		//areaCountMainMap.clear();
		//areaCountSingleMap.clear();
		//areaCountSingleMap.put("深圳", 0);
		//areaCountSingleMap.put("武汉", 0);
		//areaCountSingleMap.put("合肥", 0);
		//areaCountSingleMap.put("长沙", 0);
		//areaCountMainMap.put("深圳", new ConcurrentSkipListSet<>());
		//areaCountMainMap.put("武汉", new ConcurrentSkipListSet<>());
		//areaCountMainMap.put("合肥", new ConcurrentSkipListSet<>());
		//areaCountMainMap.put("长沙", new ConcurrentSkipListSet<>());
		//
		//
		//
		//baseMapper.getSkuInfo2().forEach(t -> {
		//	String region = CommonUtils.getRegion(t.getDept());
		//	areaCountSingleMap.put(region, areaCountSingleMap.getOrDefault(region, 0) + 1);
		//
		//	ConcurrentSkipListSet<String> skuList = areaCountMainMap.get(region);
		//	if (Objects.isNull(skuList)) {
		//		throw new RuntimeException("区域：" + region + "不存在");
		//	}
		//
		//	switch (t.getProductType()) {
		//		case 1:
		//			// 普通产品
		//			if (StringUtils.isEmpty(t.getRelativeSku())) {
		//				skuList.add(t.getSku());
		//			}
		//			else {
		//				skuList.add(t.getRelativeSku());
		//			}
		//			break;
		//		case 2:
		//			// 组合产品
		//			if (t.getIsCombVariant() == 0) {
		//				//母体
		//				skuList.add(t.getSku());
		//			}
		//			else if (t.getIsCombVariant() == 1) {
		//				// 变体，添加他的母体
		//				skuList.add(t.getCombParentSku());
		//			}
		//			break;
		//		case 3:
		//			skuList.add(t.getRelativeSku());
		//			break;
		//		default:
		//			log.error("产品类型错误：" + t.getProductType());
		//			break;
		//	}
		//
		//});
		//
		//totalCount.set(0);
		//
		//log.info("老任务区域统计结果：----母体sku总数");
		//areaCountMainMap.forEach((k, v) -> {
		//	log.info("区域：" + k + "，SKU数量：" + v.size());
		//	totalCount.addAndGet(v.size());
		//});
		//log.info("合计： " + totalCount.get());
		//
		//totalCount.set(0);
		//
		//log.info("老任务区域统计结果：----sku总数");
		//areaCountSingleMap.forEach((k, v) -> {
		//	log.info("区域：" + k + "，SKU数量：" + v);
		//	totalCount.addAndGet(v);
		//});
		//log.info("合计： " + totalCount.get());
	}

	@Override
	public void brushSimpleVideoData() {

		Map<String, VisualDesigner> simpleNameMap = visualDesignerService.list(Wrappers.<VisualDesigner>lambdaQuery().eq(VisualDesigner::getDepartmentKey, "photographer_group")
						.in(VisualDesigner::getUserName, "江雯洁", "曾雪萍", "潘婷", "薛天"))
				.stream().collect(Collectors.toMap(VisualDesigner::getUserName, Function.identity(), (a, b) -> a));
		Assert.isTrue(simpleNameMap.size() == 4, "简易视频师不全！");

		List<String> developerNumList = deptGroupService.getDeveloperNumByNodePathList("wal_develop", Collections.singletonList("DEVELOPER-YF2"));

		List<PhotoSkuInfo> skuInfoList = baseMapper.getSkuInfo(developerNumList);
		List<VisualDesignLog> logList = new ArrayList<>();
		Integer currentTimeSecond = DateUtils.getCurrentTimeSecond();
		List<PhotoProgressPerson> updateList = new LinkedList<>();

		skuInfoList.forEach(t -> {
			String region = CommonUtils.getRegion(t.getDept());

			PhotoProgressPerson photoProgressPerson = new PhotoProgressPerson();
			photoProgressPerson.setId(t.getId())
					.setIsChangeSimpleVideoStatus(1)
					.setSimpleVideoStatus(StatusEnum.UNFINISHED.getCode());
			String content = "修改简易视频任务状态为未完成，";

			VisualDesigner visualDesigner = null;
			switch (region) {
				case "深圳":
					visualDesigner = simpleNameMap.get("江雯洁");
					break;
				case "武汉":
					visualDesigner = simpleNameMap.get("曾雪萍");
					break;
				case "长沙":
					visualDesigner = simpleNameMap.get("潘婷");
					break;
				case "合肥":
					visualDesigner = simpleNameMap.get("薛天");
					break;
			}
			if (Objects.nonNull(visualDesigner)) {
				photoProgressPerson
						.setSimpleVideoPhotographerName(visualDesigner.getUserName())
						.setSimpleVideoPhotographerNum(visualDesigner.getVisualNumber());
				content += "根据开发地区修改简易视频师为：" + visualDesigner.getUserName();
			}
			else {
				return;
			}

			logList.add(new VisualDesignLog()
					.setId(IdWorker.getId())
					.setOperationKey("photo_progress")
					.setOperationContent(content)
					.setRelationId(t.getId())
					.setOperationType("is_change_simple_video_status")
					.setCreateTime(currentTimeSecond)
					.setCreateId(0)
					.setCreateName("job")
			);

			updateList.add(photoProgressPerson);

		});


		if (!CollectionUtils.isEmpty(updateList)) {
			List<List<PhotoProgressPerson>> pppList = Lists.partition(updateList, 500);
			List<List<VisualDesignLog>> listList = Lists.partition(logList, 500);
			for (int i = 0; i < pppList.size(); i++) {
				int finalI = i;
				transactionTemplate.execute(status -> {
					photoProgressPersonService.updateBatchById(pppList.get(finalI));
					visualDesignLogService.saveBatch(listList.get(finalI));
					log.info("第{}/{}次更新数据库完成！", (finalI + 1), pppList.size());
					return true;
				});
			}
		}
		log.info("修改简易视频任务状态成功，共修改{}条数据！", updateList.size());
	}

	@Override
	public void brushSimpleVideoDataPeople(List<SkuSiteDTO> list) {
		if (CollectionUtils.isEmpty(list)) return;
		Integer currentTimeSecond = DateUtils.getCurrentTimeSecond();

		list.stream().collect(Collectors.groupingBy(SkuSiteDTO::getNumber))
				.forEach((number, ls) -> {
					Lists.partition(ls, 500).forEach(l -> {
						List<VisualDesignLog> logList = new ArrayList<>();
						List<PhotoProgressPerson> photoProgressPersonList = new ArrayList<>();
						SkuSiteDTO skuSiteDTO = l.get(0);
						List<PhotoSkuInfo> photoSkuInfoList = baseMapper.getPhotoSkuInfo(l.stream().map(SkuSiteDTO::getSku).collect(Collectors.toList()));
						photoSkuInfoList.forEach(p -> {
							PhotoProgressPerson photoProgressPerson = new PhotoProgressPerson();
							photoProgressPerson.setId(p.getId())
											.setSimpleVideoPhotographerName(skuSiteDTO.getName())
											.setSimpleVideoPhotographerNum(skuSiteDTO.getNumber())
									;
							photoProgressPersonList.add(photoProgressPerson);

							logList.add(new VisualDesignLog()
									.setId(IdWorker.getId())
									.setOperationKey("photo_progress")
									.setOperationContent(String.format("简易视频摄影师由[%s]修改为[%s]", p.getSimpleVideoPhotographerName(), skuSiteDTO.getName()))
									.setRelationId(p.getId())
									.setOperationType("simple_video_photographer_num")
									.setCreateTime(currentTimeSecond)
									.setCreateId(0)
									.setCreateName("job")
							);
						});
						if (!CollectionUtils.isEmpty(photoProgressPersonList)) {
							photoProgressPersonService.updateBatchById(photoProgressPersonList);
							visualDesignLogService.saveBatch(logList);
							log.info("本次修改简易视频师成功，共修改{}条数据！", photoProgressPersonList.size());
						}
					});
				});
	}

	@Override
	public void brushSimpleVideoDataStatus(List<SkuSiteDTO> list) {
		if (CollectionUtils.isEmpty(list)) return;
		Integer currentTimeSecond = DateUtils.getCurrentTimeSecond();
		List<String> skuList = list.stream().map(SkuSiteDTO::getSku).collect(Collectors.toList());
		Lists.partition(skuList, 500).forEach(l -> {
			List<VisualDesignLog> logList = new ArrayList<>();
			List<PhotoProgressPerson> photoProgressPersonList = new ArrayList<>();
			List<PhotoSkuInfo> photoSkuInfoList = baseMapper.getPhotoSkuSimpleVideoStatus(l);
			photoSkuInfoList.forEach(p -> {
				PhotoProgressPerson photoProgressPerson = new PhotoProgressPerson();
				photoProgressPerson.setId(p.getId())
								.setSimpleVideoStatus(StatusEnum.PHOTOGRAPHY_NO_NEED_HANDLE.getCode())
						;
				photoProgressPersonList.add(photoProgressPerson);
				logList.add(new VisualDesignLog()
						.setId(IdWorker.getId())
						.setOperationKey("photo_progress")
						.setOperationContent(String.format("简易视频摄影状态由[%s]修改为[%s]", StatusEnum.get(p.getSimpleVideoStatus()), StatusEnum.PHOTOGRAPHY_NO_NEED_HANDLE.getMessage()))
						.setRelationId(p.getId())
						.setOperationType("simple_video_status")
						.setCreateTime(currentTimeSecond)
						.setCreateId(0)
						.setCreateName("job")
				);
			});
			if (!CollectionUtils.isEmpty(photoProgressPersonList)) {
				photoProgressPersonService.updateBatchById(photoProgressPersonList);
				visualDesignLogService.saveBatch(logList);
				log.info("本次修改简易视频摄影状态成功，共修改{}条数据！", photoProgressPersonList.size());
			}
		});

	}

	@Override
	public void updatePhotoProgressPhotographer(List<SkuSiteDTO> list) {

		for (SkuSiteDTO dto : list) {
			List<String> developers = baseMapper.getDevelopers(Arrays.stream(dto.getDeveloper().split(",")).map(str -> str.replaceAll("\\s+", "")).collect(Collectors.toList()));
			if (CollectionUtils.isEmpty(developers)) {
				log.error("未查询到开发人员：{}", dto.getDeveloper());
				continue;
			}
			List<VisualDesigner> visualDesigners = visualDesignerService.list(Wrappers.<VisualDesigner>lambdaQuery().eq(VisualDesigner::getUserName, dto.getPhotography().replaceAll("\\s+", ""))
					.eq(VisualDesigner::getDepartmentKey, "photographer_group"));
			if (CollectionUtils.isEmpty(visualDesigners)) {
				log.error("未查询到摄影人员：{}", dto.getPhotography().replaceAll("\\s+", ""));
				continue;
			}
			VisualDesigner visualDesigner = visualDesigners.get(0);

			List<PhotoProgressPhotographerVo> voList = baseMapper.getPhotoProgressIdByDeveloper(developers);

			List<VisualDesignLog> logList = new ArrayList<>();
			Integer currentTimeSecond = DateUtils.getCurrentTimeSecond();

			for (PhotoProgressPhotographerVo p : voList) {
				logList.add(new VisualDesignLog()
						.setId(IdWorker.getId())
						.setOperationKey("photo_progress")
						.setOperationContent(String.format("图片摄影师由【%s】修改为【%s】", p.getPhotographerName(), visualDesigner.getUserName()) )
						.setRelationId(p.getId())
						.setOperationType("photographer_name")
						.setCreateTime(currentTimeSecond)
						.setCreateId(0)
						.setCreateName("job")
				);
			}

			transactionTemplate.execute(status -> {
				visualDesignLogService.saveBatch(logList);
				baseMapper.updatePhotography(visualDesigner.getVisualNumber(), visualDesigner.getUserName(), voList.stream().map(PhotoProgressPhotographerVo::getId).collect(Collectors.toList()));
				log.info("已刷完：{}, {}条任务。", visualDesigner.getUserName(), voList.size());
				return true;
			});

		}

	}


	@Override
	public void updatePhotoProgressSimplePhotographer(List<SkuSiteDTO> list) {
		if (CollectionUtils.isEmpty(list)) return;
		Integer currentTimeSecond = DateUtils.getCurrentTimeSecond();
		//List<String> skuList = list.stream().map(SkuSiteDTO::getSku).collect(Collectors.toList());
		List<String> photographers = list.stream().map(SkuSiteDTO::getSimpleVideoPhotography).distinct().collect(Collectors.toList());
		List<VisualDesigner> visualDesigners = visualDesignerService.list(Wrappers.<VisualDesigner>lambdaQuery().in(VisualDesigner::getUserName, photographers));
		Map<String, String> photoMap = visualDesigners.stream().collect(Collectors.toMap(VisualDesigner::getUserName, VisualDesigner::getVisualNumber, (a, b) -> b));
		List<String> errorSkuList = new LinkedList<>();


		Lists.partition(list, 500).forEach(l -> {
			List<VisualDesignLog> logList = new ArrayList<>();
			List<PhotoProgressPerson> photoProgressPersonList = new ArrayList<>();
			List<String> skuList = l.stream().map(SkuSiteDTO::getSku).collect(Collectors.toList());
			List<PhotoProgressPerson> personList = baseMapper.getPhotoSkuSimpleVideoPhotography(skuList);
			Map<String, PhotoProgressPerson> personMap = personList.stream().collect(Collectors.toMap(PhotoProgressPerson::getSku, Function.identity(), (a, b) -> b));
			l.forEach(p -> {

				PhotoProgressPerson photoProgressPerson = personMap.get(p.getSku());
				if (Objects.isNull(photoProgressPerson)) {
					errorSkuList.add(p.getSku());
					return;
				}
				if (p.getSimpleVideoPhotography().equals(photoProgressPerson.getSimpleVideoPhotographerName())) {
					return;
				}
				String number = photoMap.get(p.getSimpleVideoPhotography());
				if (StringUtils.isEmpty(number)) {
					errorSkuList.add(p.getSku() + "--" + p.getSimpleVideoPhotography());
					return;
				}
				logList.add(new VisualDesignLog()
								.setId(IdWorker.getId())
								.setOperationKey("photo_progress")
								.setOperationContent(String.format("简易视频摄影摄影师由[%s]修改为[%s]", photoProgressPerson.getSimpleVideoPhotographerName(), p.getSimpleVideoPhotography()))
								.setRelationId(photoProgressPerson.getId())
								.setOperationType("simple_video_photographer_num")
								.setCreateTime(currentTimeSecond)
								.setCreateId(0)
								.setCreateName("job")
				);

				photoProgressPerson.setSimpleVideoPhotographerNum(number)
								.setSimpleVideoPhotographerName(p.getSimpleVideoPhotography());

				photoProgressPersonList.add(photoProgressPerson);


			});
			if (!CollectionUtils.isEmpty(photoProgressPersonList)) {
				photoProgressPersonService.updateBatchById(photoProgressPersonList);
				visualDesignLogService.saveBatch(logList);
				log.info("本次修改简易视频摄影摄影师成功，共修改{}条数据！", photoProgressPersonList.size());
			}
		});

		if (!CollectionUtils.isEmpty(errorSkuList)) {
			log.error("更新失败的sku：{}", String.join("  ;", errorSkuList));
		}
	}
}
