package com.cyksj.web.controller.manage.goods;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsClickUserRecordMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.GoodsDonCategoryGoodsView;
import com.cyksj.model.views.GoodsDonCategoryView;
import com.cyksj.service.mange.CmsGoodsDonService;
import com.cyksj.service.mange.GoodsDonCategoryRelateService;
import com.cyksj.service.mange.GoodsDonCategoryService;
import com.cyksj.service.mange.RefreshCacheService;
import com.cyksj.service.translations.BackInfoTranslationsFrontService;
import com.cyksj.service.translations.BackInfoTranslationsService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/*
 *项目名: netflix
 *文件名: CmsGoodsDonCategoryController
 *创建者: JavaZou
 *创建时间:2023/8/11 13:40
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/goods/category")
public class CmsGoodsDonCategoryController {
	private final GoodsDonCategoryService goodsDonCategoryService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final GoodsClickUserRecordMapper goodsClickUserRecordMapper;

	private final CmsGoodsDonService goodsDonService;

	private final GoodsDonCategoryRelateService goodsDonCategoryRelateService;

	private final RefreshCacheService refreshCacheService;

	private final BackInfoTranslationsService backInfoTranslationsService;

	private final BackInfoTranslationsFrontService backInfoTranslationsFrontService;

	/**
	 * 新增分类
	 */
	@PostMapping("/post")
	public Result<GoodsDonCategory> saveGoodsDonCategory(@RequestBody @Validated GoodsDonCategory category) {
		goodsDonCategoryService.saveOrUpdateGoods(category);
		return GatewayResponse.SUCCESS.newBuilder().toResult(category);
	}

	/**
	 * 编辑分类
	 */
	@PutMapping("/put")
	public Result<String> updateGoodsDonCategory(@RequestBody List<GoodsDonCategory> categorys) {
		String lang = request.getHeader("lang");
		//多语言
		if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
			categorys.forEach(category -> backInfoTranslationsService.saveOrUpdateBackInfoTranslations(BackInfoTranslations.Type.goods_category, category.getId(), category, lang));
		} else {
			categorys.forEach(category -> goodsDonCategoryService.saveOrUpdateGoods(category));
		}
		refreshCacheService.refreshYhHomeCategoryPageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 分类上下架
	 */
	@PutMapping("/update/status/{id}")
	public Result<String> updateStatusById(@PathVariable Long id) {
		GoodsDonCategory byId = goodsDonCategoryService.getById(id);
		Assert.notNull(byId, "分类不存在");
		byId.setStatus(!byId.getStatus());
		goodsDonCategoryService.updateById(byId);
		refreshCacheService.refreshYhHomeCategoryPageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 根据id删除分类
	 */
	@DeleteMapping("/del/{id}")
	public Result<String> del(@PathVariable Long id) {
		int count = goodsDonService.count(Wrappers.lambdaQuery(GoodsDon.class)
				.eq(GoodsDon::getCategory, id));
		if (count > 0) {
			throw BusinessRuntimeException.getInstance("存在该分类下平台");
		}
		goodsDonCategoryService.delById(id);
		refreshCacheService.refreshYhHomeCategoryPageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 修改分类排序
	 */
	@PutMapping("/sort")
	public Result<String> sortCategory(@RequestBody GoodsDonCategory category) {
		Long id = category.getId();
		Assert.notNull(id, "分类不存在");
		GoodsDonCategory byId = goodsDonCategoryService.getById(id);
		if (category.getSorted() != null) {
			byId.setSorted(category.getSorted());
			goodsDonCategoryService.updateById(byId);
			refreshCacheService.refreshYhHomeCategoryPageCache();
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 分类列表 分页
	 */
	@GetMapping("/get")
	public Result<SearchResult<GoodsDonCategoryView>> getCategory() {
		String lang = request.getHeader("lang");
		SearchResult<GoodsDonCategoryView> search = beanSearcher.search(GoodsDonCategoryView.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		search.getDataList().forEach(data->{
			Integer count = goodsClickUserRecordMapper.selectCount(Wrappers.lambdaQuery(GoodsClickUserRecord.class)
					.eq(GoodsClickUserRecord::getCategory, data.getId()));
			data.setClick(count);
			//多语言
			if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
				String categoryNameLanguage = backInfoTranslationsFrontService.getCategoryNameLanguage(data.getId(), lang);
				if (StrUtil.isNotBlank(categoryNameLanguage)) {
					data.setName(categoryNameLanguage);
				}
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 分类平台列表
	 */
	@GetMapping("/get/goods")
	public Result<SearchResult<GoodsDonCategoryGoodsView>> getCategoryGoodsView() {
		MapBuilder mapBuilder = MapUtils.flatBuilder(request.getParameterMap());
		SearchResult<GoodsDonCategoryGoodsView> search = beanSearcher.search(GoodsDonCategoryGoodsView.class, mapBuilder.build());
		search.getDataList().forEach(data->{
			Integer count = goodsClickUserRecordMapper.selectCount(Wrappers.lambdaQuery(GoodsClickUserRecord.class)
					.eq(GoodsClickUserRecord::getGoodsId, data.getGoodsId()));
			data.setClick(count);
//			GoodsDonCategoryGoodsView goodsDonCategoryGoodsView = goodsClickUserRecordMapper.selectEnvTypeClickRecord(data.getGoodsId());
//			if (goodsDonCategoryGoodsView != null) {
//				data.setPcClick(goodsDonCategoryGoodsView.getPcClick());
//				data.setH5Click(goodsDonCategoryGoodsView.getH5Click());
//				data.setH5TjClick(goodsDonCategoryGoodsView.getH5TjClick());
//			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 修改平台排序
	 */
	@PutMapping("/sort/goods")
	public Result<String> sortGoods(@RequestBody List<GoodsDonCategoryGoodsView> request) {
		List<GoodsDonCategoryRelate> updateList = new ArrayList<>(request.size());
		request.forEach(data->{
			Long goodsId = data.getGoodsId();
			Integer sorted = data.getSorted();
			GoodsDonCategoryRelate relate = goodsDonCategoryRelateService.getOne(Wrappers.lambdaQuery(GoodsDonCategoryRelate.class)
					.eq(GoodsDonCategoryRelate::getCategory, data.getCategory())
					.eq(GoodsDonCategoryRelate::getGoodsId, goodsId).last("limit 1"));
			if (sorted != null && sorted != relate.getSorted()) {
				relate.setSorted(sorted);
				updateList.add(relate);
			}
		});
		if (CollUtil.isNotEmpty(updateList)) {
			goodsDonCategoryRelateService.updateBatchById(updateList);
			refreshCacheService.refreshYhHomeCategoryPageCache();
		}

		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 移除分类下的平台
	 */
	@DeleteMapping("/delete/{relateId}")
	public Result<String> deleteCategoryByRelateId(@PathVariable Long relateId) {
		goodsDonCategoryRelateService.removeById(relateId);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 获取所有分类列表
	 */
	@GetMapping("/get/all")
	public Result<List<GoodsDonCategory>> getAll() {
		List<GoodsDonCategory> search = beanSearcher.searchAll(GoodsDonCategory.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 获取所有分类下平台 树形结构
	 */
	@GetMapping("/get/goods/tree")
	public Result<List<GoodsDonCategory>> getCategoryGoodsTreeView() {
		List<GoodsDonCategory> all = beanSearcher.searchAll(GoodsDonCategory.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(GoodsDonCategory::getStatus, true)
				.orderBy(GoodsDonCategory::getSorted).desc()
				.build());
		all.forEach(data -> {
			List<GoodsDonCategoryGoodsView> categoryGoodsViewList = beanSearcher.searchAll(GoodsDonCategoryGoodsView.class, MapUtils.
					builder().field(GoodsDonCategoryGoodsView::getCategory, data.getId())
					.field(GoodsDonCategoryGoodsView::getStatus, true).build());
			data.setCategoryGoodsList(categoryGoodsViewList);
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(all);
	}
}
