package cn.kk.spring_simple_operation;

import cn.kk.spring_simple_operation.entity.VisualDesigner;
import cn.kk.spring_simple_operation.entity.VisualPlanExecutorTaskRecord;
import cn.kk.spring_simple_operation.mapper.*;
import cn.kk.spring_simple_operation.model.dto.SkuPeopleNameDto;
import cn.kk.spring_simple_operation.model.vo.BrandRecordStatisticsVo;
import cn.kk.spring_simple_operation.model.vo.PhotoProcessExportVo;
import cn.kk.spring_simple_operation.model.vo.VideoProductExportVo;
import cn.kk.spring_simple_operation.utils.CommonUtils;
import cn.kk.spring_simple_operation.utils.DateUtils;
import cn.kk.spring_simple_operation.utils.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author kk
 * @date 2026/2/12
 */
@SpringBootTest
public class MyTest {

	private static final Logger                   log = LoggerFactory.getLogger(MyTest.class);
	@Resource
	private              SyncProductPublishMapper syncProductPublishMapper;

	@Resource
	private PhotoProgressMapper photoProgressMapper;

	@Resource
	private VideoProductMapper videoProductMapper;

	@Resource
	private VisualPlanExecutorTaskRecordMapper visualPlanExecutorTaskRecordMapper;

	@Resource
	private VisualDesignerMapper visualDesignerMapper;


	@Test
	void exportVideoProductList() {
		List<VideoProductExportVo> voList = videoProductMapper.selectVideoProductList();
		if (CollectionUtils.isEmpty(voList)) {
			System.out.println("没有查询到数据");
			return;
		}
		ExcelUtil<VideoProductExportVo> util = new ExcelUtil<VideoProductExportVo>(VideoProductExportVo.class);
		util.exportExcelFile(voList, "精细视频数据.xlsx");
		System.out.println("导出完成，共 " + voList.size() + " 条数据");
	}


	@Test
	void exportPhotoProcessList() {
		List<PhotoProcessExportVo> voList = photoProgressMapper.selectPhotoProcessList();
		if (CollectionUtils.isEmpty(voList)) {
			System.out.println("没有查询到数据");
			return;
		}
		ExcelUtil<PhotoProcessExportVo> util = new ExcelUtil<PhotoProcessExportVo>(PhotoProcessExportVo.class);
		util.exportExcelFile(voList, "简易视频上传状态-运营.xlsx");
		System.out.println("导出完成，共 " + voList.size() + " 条数据");
	}

	@Test
	void exportBrandList() {

		ArrayList<String> accountList = Lists.newArrayList("HOD", "SDT", "AE", "HOL", "HON", "AH", "AI", "AL", "AN", "HOS", "AO", "HOU", "QAA", "AR", "SEE", "AU", "AW", "AY", "YQQ", "AZ", "FLA", "SEL", "QAO", "BA", "BB", "SES", "BC", "BD", "BE", "QAR", "SEW", "SEV", "SEY", "FLO", "BK", "BL", "BM", "BO", "BQ", "WNE", "BS", "BT", "BV", "BW", "BY", "JUA", "DIB", "DIA", "CA", "JUI", "LYN", "JUL", "CD", "CE", "CG", "CH", "CI", "JUQ", "CK", "DIN", "CL", "JUS", "CM", "CN", "JUU", "CO", "CP", "CR", "CS", "CU", "BEU", "CW", "WOO", "CZ", "WON", "BEY", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DK", "DL", "DN", "DO", "DQ", "DR", "DS", "JIZH", "DT", "DU", "SHE", "DW", "DY", "SHI", "SHN", "SHP", "SHO", "EA", "SHQ", "EC", "EE", "EF", "SHU", "EG", "EI", "YUA", "SHY", "EK", "EL", "YUE", "EN", "EO", "SIA", "YUG", "EP", "EQ", "YUI", "SIC", "ER", "YUH", "ES", "ET", "EU", "QEE", "SIG", "YUM", "YUL", "EW", "YUO", "SII", "EX", "YUN", "EY", "YUQ", "SIJ", "SIL", "YUR", "YUU", "SIO", "SIN", "YUT", "FA", "FB", "QEQ", "FC", "SIR", "YUX", "FD", "SIU", "FE", "FG", "HTN", "SIX", "FL", "FM", "FN", "WRD", "FR", "FS", "JYD", "HUB", "HUA", "HUD", "FQA", "HUE", "GA", "JYI", "GC", "HUJ", "BIC", "HUI", "SJU", "HUN", "HUM", "GJ", "GL", "HUQ", "GM", "HUS", "GO", "BIO", "HUU", "GR", "JYY", "GT", "GU", "OCE", "GY", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HI", "HJ", "HL", "HM", "HN", "HO", "YXE", "HR", "HS", "HT", "HU", "HY", "SLI", "HZ", "IA", "DOE", "IE", "IF", "IG", "II", "DON", "IL", "IM", "DOR", "QIA", "IT", "DOU", "YYJ", "IU", "IV", "DOZ", "DOY", "MAD", "SMO", "YYW", "JA", "QIN", "JB", "BLB", "JD", "MAO", "MAN", "QIR", "JF", "QIU", "JG", "QIT", "QIY", "JK", "JO", "JR", "JS", "JT", "JV", "JY", "JZ", "KA", "KB", "KF", "KG", "KH", "FUN", "KK", "KL", "KM", "KN", "KO", "KQ", "KS", "SOG", "KV", "KX", "KY", "KZ", "SON", "LA", "LB", "LE", "LG", "LH", "LI", "LL", "LM", "LN", "LO", "LS", "UTE", "LT", "SPE", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MI", "BOI", "MK", "ML", "MM", "MO", "MP", "BOO", "QMA", "MS", "MT", "MX", "QMF", "MY", "MEE", "BOY", "MZ", "MED", "MEG", "KAE", "MEF", "MEI", "KAI", "OIL", "MEM", "NC", "MEL", "MEN", "MEQ", "KAO", "NG", "KAS", "NL", "NM", "NO", "NS", "NT", "QNH", "OA", "OB", "DUC", "OC", "OE", "OF", "DUG", "OH", "DUI", "OJ", "OK", "DUN", "OL", "OM", "ON", "DUO", "OO", "OR", "DUU", "OU", "OV", "OY", "PA", "PD", "SSU", "PE", "PL", "lexq", "PP", "STA", "PR", "PS", "ZAI", "PT", "STE", "ZAN", "STJ", "OLI", "QA", "QE", "QG", "QI", "STY", "QP", "QQ", "SUE", "QU", "QX", "ZBN", "KED", "MII", "SUN", "KEI", "SUR", "KEJ", "RE", "MIN", "KEO", "KEN", "RH", "RI", "IAN", "MIU", "RK", "RO", "RP", "RS", "KEZ", "RT", "RU", "RY", "ZCO", "ONG", "SC", "SD", "SE", "MJO", "SG", "SH", "SI", "SJ", "ONU", "SK", "SL", "SO", "SP", "SR", "SS", "ST", "SW", "SZ", "TA", "TC", "TD", "TE", "TF", "TG", "TH", "TM", "TN", "TO", "ZEE", "TR", "TS", "TT", "TU", "TV", "TW", "TX", "XAN", "TY", "TZ", "XAO", "UA", "UD", "UE", "UG", "UJ", "UL", "SYA", "QUA", "UR", "US", "QUE", "UY", "MME", "QUN", "QUQ", "SYU", "VI", "KIR", "VO", "MNA", "WA", "WB", "WC", "WD", "WE", "WF", "WG", "WI", "WL", "WM", "WN", "IFS", "WO", "ZHI", "WS", "WT", "WV", "WW", "MOC", "ZHO", "ZHU", "ZHW", "MOO", "XE", "XI", "XJ", "XN", "ZIF", "XO", "MOX", "XP", "XS", "XU", "XEI", "VAN", "YB", "XEU", "YD", "YE", "YG", "YH", "YL", "YM", "YN", "YQ", "YR", "YS", "YT", "YU", "YW", "YX", "YY", "GEE", "ZA", "GEG", "GEI", "ZE", "ZH", "GEM", "ZI", "GEL", "ZJ", "ZK", "GEN", "ZM", "ZN", "GES", "ZO", "GET", "GEY", "GEX", "ZY", "GFA", "MRK", "KOO", "GGN", "KOU", "XIA", "VEA", "TAB", "XIE", "XIH", "XII", "XIL", "XIK", "XIN", "XIM", "VEN", "TAN", "XIQ", "TAO", "XIU", "XIX", "TAT", "TAY", "MTY", "MUA", "OYH", "MUI", "MUL", "GIM", "MUY", "EES", "CAS", "ZON", "XLA", "XLN", "TEA", "TEN", "TET", "KUA", "CEE", "KUL", "MYU", "KUR", "THE", "THI", "ISI", "GOH", "GOO", "GON", "GOR", "TID", "ZUN", "PAC", "ZUO", "TIL", "TIN", "ZUU", "TIO", "PAN", "CHA", "ELE", "CHE", "TIU", "CHH", "ELL", "CHI", "TIY", "CHO", "CHT", "CHS", "CHU", "CHX", "GQE", "CII", "ZWA", "GRA", "fob", "GRE", "GRH", "ENV", "GRY", "RHO", "RHY", "XUE", "XUL", "RIM", "PEN", "XUU", "NAN", "CLO", "NAY", "GUF", "GUI", "GUH", "GUR", "GUU", "TOO", "TOU", "COM", "COO", "COT", "PIN", "NEN", "LAN", "PIR", "NET", "NEV", "LAU", "NEW", "LAY", "ANB", "TSV", "CRI", "ANL", "TTC", "AOE", "PLU", "LED", "LEC", "JAA", "JAC", "LEE", "JAF", "NIL", "TUR", "LEI", "LEL", "LEN", "LEM", "JAN", "LER", "JAO", "LET", "JAX", "JAW", "JAY", "RRY", "ARI", "YAC", "YAJ", "YAN", "YAR", "YAW", "LHJ", "LIA", "RUJ", "RUI", "LIC", "LIF", "HAA", "LIE", "RUN", "JEE", "JEI", "LIN", "JEL", "HAI", "LIO", "RUX", "HAN", "LIR", "HAP", "JER", "HAT", "LIY", "HAY", "YCL", "PRI", "JGF", "JGG", "YEE", "WAE", "WAD", "YEI", "YEO", "YEN", "YES", "WAP", "YEU", "WAR", "WAY", "JIA", "JIH", "HEE", "PUM", "JIL", "HEL", "JIN", "HEN", "FAN", "HEQ", "YGE", "WCE", "FAS", "HEY", "LNA", "LNE", "LNG", "AYA", "LNN", "LNY", "AYO", "TJRW", "YHO", "LON", "LOM", "LOO", "YIE", "WEG", "YIO", "YIN", "WEN", "WEQ", "UAN", "YIU", "YIT", "FDE", "NUE", "HID", "HIC", "DAB", "DAC", "FEE", "HIJ", "HII", "DAG", "HIM", "FEN", "DAN", "FER", "DAO", "YKH", "FEY", "DAY", "JNE", "LRU", "JNU", "YLF", "YLI", "JOO", "YMF", "JOY", "SAI", "WIL", "SAH", "WIO", "SAN", "SAW", "YNG", "LUA", "DEA", "YNX", "YNY", "LUO", "DEL", "YOA", "BAN", "DER", "YOG", "YOF", "YOJ", "HMY", "YOL", "YON", "YOU");
		//ArrayList<String> accountList = Lists.newArrayList("HOD", "SDT", "AE", "HOL", "HON", "AH", "AI", "AL", "AN", "HOS", "AO", "HOU");


		List<List<String>> listList = Lists.partition(accountList, 10);
		List<BrandRecordStatisticsVo> exports = new LinkedList<>();
		for (int i = 1; i <= listList.size(); i++) {
			Integer startTime = DateUtils.getCurrentTimeSecond();
			List<String> list = listList.get(i - 1);
			List<BrandRecordStatisticsVo> voList = syncProductPublishMapper.selectBrandRecordStatistics(list);
			if (CollectionUtils.isEmpty(voList)) {
				continue;
			}
			exports.addAll(voList);
			System.out.println("已获取第 " + i + " 批数据：" + voList.size() + "耗时：" + (DateUtils.getCurrentTimeSecond() - startTime) + "秒。");
		}

		ExcelUtil<BrandRecordStatisticsVo> util = new ExcelUtil<BrandRecordStatisticsVo>(BrandRecordStatisticsVo.class);
		util.exportExcelFile(exports, "运营导数据.xlsx");

	}


	@Test
	public void updatePlanMonthData() throws Exception {
		Set<Integer> userSet = new HashSet<>();
		userSet.add(5384);
		userSet.add(5779);
		userSet.add(8317);

		Map<String, Integer> userNumberMap = visualDesignerMapper.selectList(Wrappers.<VisualDesigner>lambdaQuery()
				.in(VisualDesigner::getDepartmentKey, "a_plus_plan", "video_plan")
				.select(VisualDesigner::getVisualNumber, VisualDesigner::getUserId)
		).stream().collect(Collectors.toMap(VisualDesigner::getVisualNumber, VisualDesigner::getUserId, (a, b) -> b));

		File file = new File("A+.xlsx");
		ExcelUtil<SkuPeopleNameDto> util = new ExcelUtil<>(SkuPeopleNameDto.class);
		List<SkuPeopleNameDto> list = util.importExcel(Files.newInputStream(file.toPath()));

		list.stream().collect(Collectors.groupingBy(SkuPeopleNameDto::getMonth))
				.forEach((monthCh, voList) -> {
					int month = Integer.parseInt(monthCh.replace("月", ""));

					List<VisualPlanExecutorTaskRecord> visualPlanExecutorTaskRecords = visualPlanExecutorTaskRecordMapper.selectList(Wrappers.<VisualPlanExecutorTaskRecord>lambdaQuery()
							.eq(VisualPlanExecutorTaskRecord::getYearInt, 2026)
							.eq(VisualPlanExecutorTaskRecord::getMonthInt, month)
					);
					if (CollectionUtils.isEmpty(visualPlanExecutorTaskRecords)) return;

					Calendar calendar = Calendar.getInstance();
					calendar.set(2026, month - 1, 1);
					Date time = calendar.getTime();

					Map<Integer, VisualPlanExecutorTaskRecord> userMap = visualPlanExecutorTaskRecords.stream().collect(Collectors.toMap(VisualPlanExecutorTaskRecord::getUserId, Function.identity()));
					for (SkuPeopleNameDto dto : voList) {
						Integer userId = userNumberMap.get(dto.getNumber());
						if (CommonUtils.isNullOrZero(userId)) {
							log.error("未找到用户：{}", dto.getNumber());
							continue;
						}
						VisualPlanExecutorTaskRecord record = userMap.get(userId);
						if (record != null) {
							record.setSalesGrowth(dto.getPositiveSalesGrowth());
							int appraisingNum = visualPlanExecutorTaskRecordMapper.getAPlusAppraisingCountByUser(DateUtils.formatDate(time, "yyyy-MM"), dto.getNumber());
							record.setAppraisingNum(appraisingNum);
						}

					}
					List<VisualPlanExecutorTaskRecord> sortList = visualPlanExecutorTaskRecords.stream().filter(t -> !userSet.contains(t.getUserId()))
							.sorted(Comparator.comparingInt(VisualPlanExecutorTaskRecord::getSalesGrowth).reversed()).collect(Collectors.toList());

					// 设置排名，相同值排名相同，下一位跳过当前排名
					int rank = 1;
					int lastSales = 0;
					for (int i = 0; i < sortList.size(); i++) {
						VisualPlanExecutorTaskRecord current = sortList.get(i);
						if (i > 0) {
							// 如果当前值与前一个值不同，则更新排名为当前位置+1
							if (current.getSalesGrowth() != lastSales) {
								rank = i + 1;  // 实现相同值排名相同且下一位跳过排名
							}
						}
						lastSales = current.getSalesGrowth();
						current.setSalesGrowthRank(rank);
					}

					try (BufferedWriter writer = new BufferedWriter(new FileWriter("a_plus_plan_month_data_" + month + ".sql"))) {
						for (VisualPlanExecutorTaskRecord record : visualPlanExecutorTaskRecords) {
							writer.write(String.format("update visual_plan_executor_task_record set appraising_num = %d, sales_growth_rank = %d, sales_growth = %d where id = %d;\n",
									record.getAppraisingNum(), record.getSalesGrowthRank(), record.getSalesGrowth(), record.getId()));
						}

					} catch (IOException e) {
						e.printStackTrace();
					}
				});


		file = new File("视频.xlsx");
		util = new ExcelUtil<>(SkuPeopleNameDto.class);
		list = util.importExcel(Files.newInputStream(file.toPath()));

		list.stream().collect(Collectors.groupingBy(SkuPeopleNameDto::getMonth))
				.forEach((monthCh, voList) -> {
					int month = Integer.parseInt(monthCh.replace("月", ""));

					List<VisualPlanExecutorTaskRecord> visualPlanExecutorTaskRecords = visualPlanExecutorTaskRecordMapper.selectList(Wrappers.<VisualPlanExecutorTaskRecord>lambdaQuery()
							.eq(VisualPlanExecutorTaskRecord::getYearInt, 2026)
							.eq(VisualPlanExecutorTaskRecord::getMonthInt, month)
					);
					if (CollectionUtils.isEmpty(visualPlanExecutorTaskRecords)) return;

					Calendar calendar = Calendar.getInstance();
					calendar.set(2026, month - 1, 1);
					Date time = calendar.getTime();
					Integer timeSecond = DateUtils.date2TimeSecond(time);

					Map<Integer, VisualPlanExecutorTaskRecord> userMap = visualPlanExecutorTaskRecords.stream().collect(Collectors.toMap(VisualPlanExecutorTaskRecord::getUserId, Function.identity()));
					for (SkuPeopleNameDto dto : voList) {
						Integer userId = userNumberMap.get(dto.getNumber());
						if (CommonUtils.isNullOrZero(userId)) {
							log.error("未找到用户：{}", dto.getNumber());
							continue;
						}
						VisualPlanExecutorTaskRecord record = userMap.get(userId);
						if (record != null) {
							record.setSalesGrowth(dto.getPositiveSalesGrowth());

							int appraisingNum = visualPlanExecutorTaskRecordMapper.getVideoAppraisingCountByUser(DateUtils.getStartMonthOffset(timeSecond, 0), DateUtils.getEndMonthOffset(timeSecond, 0), dto.getNumber());

							record.setAppraisingNum(appraisingNum);
						}

					}
					List<VisualPlanExecutorTaskRecord> sortList = visualPlanExecutorTaskRecords.stream().filter(t -> !userSet.contains(t.getUserId())).collect(Collectors.toList());

					// 设置排名，相同值排名相同，下一位跳过当前排名
					int rank = 1;
					int lastSales = 0;
					for (int i = 0; i < sortList.size(); i++) {
						VisualPlanExecutorTaskRecord current = sortList.get(i);
						if (i > 0) {
							// 如果当前值与前一个值不同，则更新排名为当前位置+1
							if (current.getSalesGrowth() != lastSales) {
								rank = i + 1;  // 实现相同值排名相同且下一位跳过排名
							}
						}
						lastSales = current.getSalesGrowth();
						current.setSalesGrowthRank(rank);
					}

					try (BufferedWriter writer = new BufferedWriter(new FileWriter("video_plan_month_data_" + month + ".sql"))) {
						for (VisualPlanExecutorTaskRecord record : visualPlanExecutorTaskRecords) {
							writer.write(String.format("update visual_plan_executor_task_record set appraising_num = %d, sales_growth_rank = %d, sales_growth = %d where id = %d;\n",
									record.getAppraisingNum(), record.getSalesGrowthRank(), record.getSalesGrowth(), record.getId()));
						}

					} catch (IOException e) {
						e.printStackTrace();
					}
				});

	}
}
