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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.HomeConfigTimingReq;
import com.cyksj.model.request.HomeManageConfigReq;
import com.cyksj.model.views.HomeManagementAvailableGoodsView;
import com.cyksj.model.views.HomeManagementConfigView;
import com.cyksj.service.home.HomeManagementConfigService;
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.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

/** admin/首页管理/首页配置管理
 *项目名: netflix
 *文件名: HomeManageConfigController
 *创建者: JavaZou
 *创建时间:2023/8/17 16:46
 */
@RestController
@RequestMapping("/manage/homeManage/config")
@RequiredArgsConstructor
public class HomeManageConfigController {
	private final HomeManagementConfigService homeManagementConfigService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	private final RefreshCacheService refreshCacheService;

	private final GoodsDonCategoryService goodsDonCategoryService;

	private final BackInfoTranslationsService backInfoTranslationsService;

	private final BackInfoTranslationsFrontService backInfoTranslationsFrontService;

	/**
	 * 新增首页配置
	 */
	@PostMapping("/post")
	public Result<String> saveConfig(@RequestBody HomeManageConfigReq config) {
		homeManagementConfigService.saveOrUpdateConfig(config);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 更新首页配置
	 */
	@PutMapping("/put")
	public Result<String> updateConfig(@RequestBody HomeManageConfigReq config) {
		String lang = request.getHeader("lang");
		if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
			backInfoTranslationsService.saveOrUpdateBackInfoTranslations(BackInfoTranslations.Type.home_config, config.getId(), config, lang);
		} else {
			homeManagementConfigService.saveOrUpdateConfig(config);
		}
		refreshCacheService.refreshYhHomePageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 上下架配置
	 */
	@PutMapping("/update/status/{id}")
	public Result<String> updateStatusById(@PathVariable Long id) {
		HomeManagementConfig byId = homeManagementConfigService.getById(id);
		Assert.notNull(byId, "配置不存在");
		byId.setStatus(!byId.getStatus());
		byId.setTime(null);
		byId.setEndTime(null);
		byId.setPreStatus(null);
		homeManagementConfigService.updateById(byId);
		refreshCacheService.refreshYhHomePageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 配置 一键上下架
	 */
	@PutMapping("/batch/update/status/{status}")
	public Result<String> batchUpdateStatus(@RequestBody List<Long> ids, @PathVariable Boolean status) {
		homeManagementConfigService.update(null, Wrappers.lambdaUpdate(HomeManagementConfig.class)
				.set(HomeManagementConfig::getTime, null)
				.set(HomeManagementConfig::getEndTime, null)
				.set(HomeManagementConfig::getPreStatus, null)
				.set(HomeManagementConfig::getStatus, status)
				.in(HomeManagementConfig::getId, ids));
		//批量取消定时上下架状态
		homeManagementConfigService.batchCancelTimingStatus(ids);
		refreshCacheService.refreshYhHomePageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 分类 一键上下架
	 */
	@PutMapping("/batch/update/category/status/{status}")
	public Result<String> batchUpdateCategoryStatus(@RequestBody List<Long> ids, @PathVariable Boolean status) {
		goodsDonCategoryService.update(null, Wrappers.lambdaUpdate(GoodsDonCategory.class)
				.set(GoodsDonCategory::getStatus, status)
				.in(GoodsDonCategory::getId, ids));
		refreshCacheService.refreshYhHomePageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 配置排序
	 */
	@PutMapping("/sort")
	public Result<String> sortConfig(@RequestBody HomeManageConfigReq config) {
		Long id = config.getId();
		HomeManagementConfig byId = homeManagementConfigService.getById(id);
		Assert.notNull(byId, "配置不存在");
		Integer sorted = config.getSorted();
		byId.setSorted(sorted);
		homeManagementConfigService.updateById(byId);
		refreshCacheService.refreshYhHomePageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除首页配置
	 */
	@DeleteMapping("/del/{id}")
	public Result<String> delById(@PathVariable Long id) {
		homeManagementConfigService.update(null, Wrappers.lambdaUpdate(HomeManagementConfig.class)
						.set(HomeManagementConfig::getDeleted, false)
						.eq(HomeManagementConfig::getId, id)
						.eq(HomeManagementConfig::getDeleted, true));
		refreshCacheService.refreshYhHomePageCache();
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 首页配置列表
	 */
	@GetMapping("/get")
	public Result<SearchResult<HomeManagementConfigView>> get(@RequestParam(defaultValue = "ad") HomeManagementConfig.Type type) {
		SearchResult<HomeManagementConfigView> search = beanSearcher.search(HomeManagementConfigView.class, MapUtils.flatBuilder(request.getParameterMap())
				.field(HomeManagementConfigView::getType, type.name())
				.build());
		String lang = request.getHeader("lang");
		search.getDataList().forEach(data -> {
			Number number = beanSearcher.searchCount(HomeManagementConfigUserClickRecord.class, MapUtils.builder()
					.field(HomeManagementConfigUserClickRecord::getConfigId, data.getId()).build());
			data.setClick(number.intValue());
			if (data.getType() == HomeManagementConfig.Type.rg) {
				if (lang != null && !StrUtil.equals(UserPageLanguage.Language.zh_CN.name(), lang)) {
					backInfoTranslationsFrontService.setFieldLanguage(data.getClass(), data, BackInfoTranslations.Type.home_config.ordinal(), data.getId(), lang);
				}
			}
		});
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 首页配置 可选平台
	 */
	@GetMapping("/get/goods")
	public Result<List<HomeManagementAvailableGoodsView>> getAvailableGoodsDon(HomeManagementConfig.Type type) {
		Assert.notNull(type, "首页配置类型为空");
		List<HomeManagementAvailableGoodsView> views = beanSearcher.searchAll(HomeManagementAvailableGoodsView.class, MapUtils.flatBuilder(request.getParameterMap())
				.put("type", String.format("type = '%s' and ", type.name()))
				.field(HomeManagementAvailableGoodsView::getGoodsType, 1)
				.field(HomeManagementAvailableGoodsView::getStatus, true)
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(views);
	}

	/**
	 * 定时上下架时间
	 */
	@PutMapping("/timing/update/status")
	public Result<String> timingUpdateStatus(@RequestBody HomeConfigTimingReq req) {
		homeManagementConfigService.timingUpdateStatus(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 取消定时上下架
	 */
	@PutMapping("/timing/cancel/{id}")
	public Result<String> timingCancel(@PathVariable Long id) {
		homeManagementConfigService.timingCancel(id);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

}
