package com.cyksj.service.translations.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.mapper.BackInfoTranslationsMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.mapper.manage.coupon.CouponSkuMapper;
import com.cyksj.model.entity.BackInfoTranslations;
import com.cyksj.model.entity.GoodsDonSku;
import com.cyksj.model.entity.UserPageLanguage;
import com.cyksj.model.manage.views.GoodsDonViewer;
import com.cyksj.model.views.*;
import com.cyksj.service.translations.BackInfoTranslationsFrontService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目名: yhlxj2
 * 文件名: BackInfoTranslationsFrontServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/7/16 15:07
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BackInfoTranslationsFrontServiceImpl implements BackInfoTranslationsFrontService {
	private final BackInfoTranslationsMapper backInfoTranslationsMapper;

	private final CouponMapper couponMapper;

	private final CouponSkuMapper couponSkuMapper;

	@Override
	public void setGoodsDetailLanguage(GoodsFrontListView views, String lang) {
		if (views == null) {
			return;
		}
		//平台
		setFieldLanguage(views.getClass(), views, BackInfoTranslations.Type.goods.ordinal(), views.getId(), lang);
		//规格
		List<GoodsDonSkuFrontView> skuList = views.getSkuList();
		if (CollUtil.isNotEmpty(skuList)) {
			skuList.forEach(sku -> setFieldLanguage(sku.getClass(), sku, BackInfoTranslations.Type.sku.ordinal(), sku.getId(), lang));
		}
		GoodsDonSpecFrontView specs = views.getSpecs();
		if (specs != null) {
			setFieldLanguage(specs.getClass(), specs, BackInfoTranslations.Type.spec.ordinal(), specs.getId(), lang);
		}
	}

	@Override
	public void setCategoryGoodsLanguage(GoodsFrontListCategoryView data, String lang) {
		if (data == null) {
			return;
		}
		//平台
		setFieldLanguage(data.getClass(), data, BackInfoTranslations.Type.goods.ordinal(), data.getId(), lang);
	}

	@Override
	public String getLanguagePayTitle(Long goodsId, Long skuId, String lang) {
		if (StrUtil.isEmpty(lang)) {
			return null;
		}
		BackInfoTranslations goodsL = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
				.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.goods.ordinal())
				.eq(BackInfoTranslations::getFuncId, goodsId)
				.eq(BackInfoTranslations::getLang, lang)
				.eq(BackInfoTranslations::getFieldName, "title"));
		StringBuilder payTitle = new StringBuilder();
		if (goodsL != null) {
			payTitle.append(goodsL.getDesp());
		}
		if (skuId != null) {
			BackInfoTranslations skuL = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
					.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.sku.ordinal())
					.eq(BackInfoTranslations::getFuncId, skuId)
					.eq(BackInfoTranslations::getLang, lang)
					.eq(BackInfoTranslations::getFieldName, "specVal"));
			if (skuL != null) {
				if (payTitle.length() > 0) {
					payTitle.append(" ");
				}
				payTitle.append(skuL.getDesp());
			}
		}
		if (payTitle.length() > 0) {
			return payTitle.toString();
		}
		return null;
	}

	@Override
	public void setGoodsBackLanguage(GoodsDonViewer goodsDonViewer, String lang) {
		//sku
		setFieldLanguage(goodsDonViewer.getClass(), goodsDonViewer, BackInfoTranslations.Type.goods.ordinal(), goodsDonViewer.getId(), lang);
		//spec
		//特殊处理specJson
		String specsJson = goodsDonViewer.getSpecsJson();
		setFieldLanguage(goodsDonViewer.getClass(), goodsDonViewer, BackInfoTranslations.Type.spec.ordinal(), goodsDonViewer.getSpecId(), lang);
		String specsJsonLang = goodsDonViewer.getSpecsJson();
		goodsDonViewer.setSpecsJson(replaceSpecValues(specsJson, specsJsonLang));
	}

	@Override
	public void setSkuBackLanguage(List<GoodsDonSku> goodsDonSkus, String lang) {
		goodsDonSkus.forEach(sku -> setFieldLanguage(sku.getClass(), sku, BackInfoTranslations.Type.sku.ordinal(), sku.getId(), lang));
	}

	@Override
	public String getLanguageSpecVal(Long skuId, String lang) {
		if (skuId == null) {
			return null;
		}
		BackInfoTranslations skuL = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
				.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.sku.ordinal())
				.eq(BackInfoTranslations::getFuncId, skuId)
				.eq(BackInfoTranslations::getLang, lang)
				.eq(BackInfoTranslations::getFieldName, "specVal"));
		if (skuL != null) return skuL.getDesp();
		return null;
	}

	@Override
	public String getGoodsTitleLanguage(Long goodsId, String lang) {
		BackInfoTranslations goodsL = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
				.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.goods.ordinal())
				.eq(BackInfoTranslations::getFuncId, goodsId)
				.eq(BackInfoTranslations::getLang, lang)
				.eq(BackInfoTranslations::getFieldName, "title"));
		if (goodsL != null) return goodsL.getDesp();
		return null;
	}

	@Override
	public void setCouponLanguage(CouponView couponView, String lang) {
		setFieldLanguage(couponView.getClass(), couponView, BackInfoTranslations.Type.coupon.ordinal(), couponView.getId(), lang);
		if (couponView.getClassificationId() != null) {
			BackInfoTranslations classificationTranslation = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
					.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.coupon_classification.ordinal())
					.eq(BackInfoTranslations::getLang, lang)
					.eq(BackInfoTranslations::getFuncId, couponView.getClassificationId())
					.eq(BackInfoTranslations::getFieldName, "name"));
			if (classificationTranslation != null) {
				couponView.setCouponClassificationName(classificationTranslation.getDesp());
			}
		}
	}

	@Override
	public void setFieldLanguage(Class<?> tclass, Object obj, Integer type, Long funcId, String lang) {
		if (StrUtil.isEmpty(lang) || StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
			return;
		}
		List<BackInfoTranslations> backInfoTranslations = backInfoTranslationsMapper.selectList(Wrappers.lambdaQuery(BackInfoTranslations.class)
				.eq(BackInfoTranslations::getType, type)
				.eq(BackInfoTranslations::getLang, lang)
				.eq(BackInfoTranslations::getFuncId, funcId));

		if (CollUtil.isNotEmpty(backInfoTranslations)) {
			backInfoTranslations.forEach(tanslate -> {
				String fieldName = tanslate.getFieldName();
				try {
					Field declaredField = tclass.getDeclaredField(fieldName);
					declaredField.setAccessible(true);
					declaredField.set(obj, tanslate.getDesp());
				} catch (IllegalAccessException e) {
				} catch (NoSuchFieldException e) {
				}
			});
		}
	}


	@Override
	public String setCouponGoodsSkuStrLanguage(Long couponId, String lang) {
		if (StrUtil.isEmpty(lang) || StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
			String str = couponSkuMapper.selectGoodsSkuStr(couponId);
			str = str.replaceAll(",", "/").replaceAll(";", "");
			return str;
		}

		List<GoodsDonSku> goodsDonSkus = new ArrayList<>();
		StringBuilder skuGoodsStrSb = new StringBuilder(128);
		Map<Long, String> map = new HashMap<>();
		goodsDonSkus.forEach(sku -> {
			String title = map.get(sku.getGoodsId());
			if (StrUtil.isEmpty(title)) {
				BackInfoTranslations backGoodsInfoTranslations = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
						.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.goods.ordinal())
						.eq(BackInfoTranslations::getLang, lang)
						.eq(BackInfoTranslations::getFieldName, "title")
						.eq(BackInfoTranslations::getFuncId, sku.getGoodsId()));
				if (backGoodsInfoTranslations != null) {
					title = backGoodsInfoTranslations.getDesp();
					map.put(sku.getGoodsId(), title);
				}
			}
			BackInfoTranslations backSkuInfoTranslations = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
					.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.sku.ordinal())
					.eq(BackInfoTranslations::getLang, lang)
					.eq(BackInfoTranslations::getFieldName, "specVal")
					.eq(BackInfoTranslations::getFuncId, sku.getId()));
			if (skuGoodsStrSb.length() > 0) {
				skuGoodsStrSb.append("/");
			}
			if (backSkuInfoTranslations != null) {
				skuGoodsStrSb.append(title).append(" ").append(backSkuInfoTranslations.getDesp());
			}
		});

		return skuGoodsStrSb.toString();
	}

	@Override
	public void setListCategoryNameLanguage(List<GoodsDonCategoryFrontView> list, String lang) {
		if (list == null) {
			return;
		}
		list.forEach(category -> setFieldLanguage(category.getClass(), category, BackInfoTranslations.Type.goods_category.ordinal(), category.getId(), lang));
	}

	@Override
	public String getCategoryNameLanguage(Long category, String lang) {
		BackInfoTranslations categoryName = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
				.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.goods_category.ordinal())
				.eq(BackInfoTranslations::getFuncId, category)
				.eq(BackInfoTranslations::getLang, lang)
				.eq(BackInfoTranslations::getFieldName, "name"));
		if (categoryName != null) return categoryName.getDesp();
		return null;
	}

	@Override
	public String getLanguagePayDesc(Long goodsId, String lang) {
		if (StrUtil.isEmpty(lang)) {
			return null;
		}
		BackInfoTranslations goodsL = backInfoTranslationsMapper.selectOne(Wrappers.lambdaQuery(BackInfoTranslations.class)
				.eq(BackInfoTranslations::getType, BackInfoTranslations.Type.goods.ordinal())
				.eq(BackInfoTranslations::getFuncId, goodsId)
				.eq(BackInfoTranslations::getLang, lang)
				.eq(BackInfoTranslations::getFieldName, "payDesc"));
		if (goodsL != null) {
			return goodsL.getDesp();
		}
		return null;
	}

	@Override
	public void getHomeConfigRealGoodsLanguage(List<HomeManagementFrontView> homeManagementFrontViews, String lang) {
		if (homeManagementFrontViews == null) {
			return;
		}
		if (CollUtil.isNotEmpty(homeManagementFrontViews)) {
			homeManagementFrontViews.forEach(rg -> setFieldLanguage(rg.getClass(), rg, BackInfoTranslations.Type.home_config.ordinal(), rg.getHomeManageConfigId(), lang));
		}
	}

	/**
	 * 多语言特殊处理specJson
	 */
	public static String replaceSpecValues(String specJsons, String specJsons2) {
		try {
			JSONArray specArray = JSONUtil.parseArray(specJsons);
			JSONArray specArray2 = JSONUtil.parseArray(specJsons2);

			Map<Integer, String> replacementMap = new HashMap<>();

			for (Object obj2 : specArray2) {
				JSONObject spec2 = (JSONObject) obj2;
				JSONArray values2 = spec2.getJSONArray("values");
				if (values2 != null) {
					for (Object value2Obj : values2) {
						JSONObject value2 = (JSONObject) value2Obj;
						Integer id = value2.getInt("id");
						String valueStr = value2.getStr("value");
						if (id != null && valueStr != null) {
							replacementMap.put(id, valueStr);
						}
					}
				}
			}

			for (Object obj : specArray) {
				JSONObject spec = (JSONObject) obj;
				JSONArray values = spec.getJSONArray("values");
				if (values != null) {
					for (Object valueObj : values) {
						JSONObject value = (JSONObject) valueObj;
						Integer id = value.getInt("id");
						if (id != null && replacementMap.containsKey(id)) {
							value.set("value", replacementMap.get(id));
						}
					}
				}
			}

			return JSONUtil.toJsonStr(specArray);
		} catch (Exception e) {
			log.error("处理JSON时发生错误: " + e.getMessage());
			return specJsons;
		}
	}
}
