package com.fs.app.controller.store;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.app.vo.IndexVO;
import com.fs.common.core.domain.R;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.service.IFsCoursePlaySourceConfigService;
import com.fs.his.config.AgreementConfig;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.param.*;
import com.fs.hisStore.service.*;
import com.fs.hisStore.vo.*;
import com.fs.live.service.ILiveDataService;
import com.fs.live.vo.LiveAppSimpleVO;
import com.fs.store.config.ConceptConfig;
import com.fs.system.service.ISysConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.Cacheable;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api("首页接口")
@RestController
@RequestMapping(value="/store/app/index")
public class IndexScrmController extends AppBaseController {

	@Autowired
	private IFsArticleCateScrmService articleCateService;

	@Autowired
	private IFsAdvScrmService advService;

	@Autowired
	private IFsStoreProductScrmService productService;



	@Autowired
	private IFsArticleScrmService articleService;

	@Autowired
	private IFsStoreCartScrmService cartService;
	@Autowired
	private IFsMenuScrmService menuService;
	@Autowired
	private IFsStoreCanvasScrmService storeCanvasService;
	@Autowired
	private ISysConfigService configService;
	@Autowired
	private IFsCoursePlaySourceConfigService coursePlaySourceConfigService;
	@Autowired
	private IFsStoreUserEndCategoryScrmService userEndCategoryScrmService;
	@Autowired
	private ILiveDataService liveDataService;

	@ApiOperation("首页初始化")
	@GetMapping("/home/init")
	public R homeInit(@RequestParam(value = "storeId", required = false) Long storeId) {
		Map<String, Object> data = new HashMap<>();
		// 金刚区：前8条，排序 asc、创建时间 desc
		List<FsStoreUserEndCategoryScrm> categoryTags = userEndCategoryScrmService.selectTop8ByPosition(storeId, 1);
		// 瀑布流：前8条，排序 asc、创建时间 desc
		List<FsStoreUserEndCategoryScrm> goodsNav = userEndCategoryScrmService.selectTop8ByPosition(storeId, 2);
		data.put("channelList", Collections.emptyList());
		data.put("categoryTags", categoryTags != null ? categoryTags : Collections.emptyList());
		data.put("goodsNav", goodsNav != null ? goodsNav : Collections.emptyList());
		return R.ok().put("data", data);
	}


	/**
	 * 首页商品列表（支持用户端分类 id、区域 position、关键字 keyword）
	 * id：用户端分类ID，为空时按 position 或查全部
	 * position：1=金刚区 2=瀑布区，传入时查询该区域下全部产品（支持 keyword）
	 * keyword：商品名称模糊搜索
	 * 去重分页查商品ID → 查商品简表+标签 → 返回 productId、productName、image、price、otPrice、sales、tagList
	 */
	@ApiOperation("首页商品列表")
	@GetMapping("/home/goods")
	public R homeGoods(@RequestParam(value = "id", required = false) Long id,
					   @RequestParam(value = "keyword", required = false) String keyword,
					   @RequestParam(value = "storeId", required = false) Long storeId,
					   @RequestParam(value = "position", required = false) Integer position,
					   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
					   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
		java.util.Map<String, Object> data = userEndCategoryScrmService.listProductsForApp(id, keyword, pageNum, pageSize, storeId, position);
		return R.ok().put("data", data);
	}


	/**
	 * 首页推荐区块（直播中、上新推荐等，可延迟加载）
	 * live：正在直播的直播间（liveId、liveType、封面、标题；liveType=2 时 liveFlag 从 Redis 查）
	 * green：商品“新品首发”开启的 2 条
	 * hot：商品“是否热卖”开启的 2 条
	 */
	@ApiOperation("首页推荐区块")
	@GetMapping("/home/recommend")
	public R homeRecommend(HttpServletRequest request) {
		String appId = request.getParameter("appId");
		List<LiveAppSimpleVO> liveList = liveDataService.listLivingLivesForApp();
		List<FsStoreProductListQueryVO> greenProduct = productService.selectFsStoreProductNewQuery(2, appId);
		List<FsStoreProductListQueryVO> hotProduct = productService.selectFsStoreProductHotQuery(2, appId);
		return R.ok()
				.put("live", liveList != null ? liveList : Collections.emptyList())
				.put("green", greenProduct != null ? greenProduct : Collections.emptyList())
				.put("hot", hotProduct != null ? hotProduct : Collections.emptyList());
	}

	/**
	 * 首页推荐「更多」分页：绿色有机(green) / 上新推荐(hot)，逻辑同 homeRecommend 的 green、hot 查询，支持分页，默认第1页10条
	 */
	@ApiOperation("首页推荐更多分页")
	@GetMapping("/home/goods/recommend")
	public R homeGoodsRecommend(HttpServletRequest request,
								@RequestParam(value = "type") String type,
								@RequestParam(value = "keyword", required = false) String keyword,
								@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
								@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
		String appId = request.getParameter("appId");
		if (!"green".equalsIgnoreCase(type) && !"hot".equalsIgnoreCase(type)) {
			return R.ok().put("data", new PageInfo<>(Collections.emptyList()));
		}
		List<FsStoreProductListQueryVO> list = "green".equalsIgnoreCase(type)
				? productService.selectFsStoreProductNewQueryPage(pageNum, pageSize, appId, keyword)
				: productService.selectFsStoreProductHotQueryPage(pageNum, pageSize, appId, keyword);
		PageInfo<FsStoreProductListQueryVO> pageInfo = new PageInfo<>(list);
		return R.ok().put("data", pageInfo);
	}



	@ApiOperation("获取首页数据")
	@GetMapping("/getIndexData")
	public R getIndexData(HttpServletRequest request){
		List<FsArticleCateListQueryVO> articleCateList=articleCateService.selectFsArticleCateListQuery();
		List<FsAdvListQueryVO> advList=advService.selectFsAdvListQuery(1);
		List<FsStoreProductListQueryVO> newProductList=productService.selectFsStoreProductNewQuery(10, request.getParameter("appId"));
		List<FsStoreProductListQueryVO> hotProductList=productService.selectFsStoreProductHotQuery(12, request.getParameter("appId"));
		IndexVO vo=IndexVO.builder().articleCateList(articleCateList).advList(advList).newProductList(newProductList).hotProductList(hotProductList).build();
		return R.ok().put("data", vo);
	}




	@ApiOperation("读取菜单数据")
	@GetMapping("/getMenu")
	@Cacheable("menu")
	public R getMenu(FsMenuScrm map){
		map.setIsShow(1);
		map.setMenuType(1);
		List<FsMenuScrm> list=menuService.selectFsMenuList(map);
		return R.ok().put("data",list);
	}


	@ApiOperation("读取养生有道")
	@GetMapping("/getMenuTwo")
	@Cacheable("menuTwo")
	public R getMenuTwo(HttpServletRequest request){
		FsMenuScrm map=new FsMenuScrm();
		map.setIsShow(1);
		map.setMenuType(2);
		List<FsMenuScrm> list=menuService.selectFsMenuList(map);
		return R.ok().put("data",list);
	}

	@ApiOperation("读取菜单配置")
	@GetMapping("/getMenuList")
	public R getMenuList(FsMenuScrm map){
		map.setIsShow(1);
		List<FsMenuScrm> list=menuService.selectFsMenuList(map);
		return R.ok().put("data",list);
	}

	@ApiOperation("读取个人中心")
	@GetMapping("/getMenuUser")
	@Cacheable("menuUser")
	public R getMenuUser(HttpServletRequest request){
		FsMenuScrm map=new FsMenuScrm();
		map.setIsShow(1);
		map.setMenuType(3);
		List<FsMenuScrm> list=menuService.selectFsMenuList(map);
		return R.ok().put("data",list);
	}

	@ApiOperation("企业理念")
	@GetMapping("/getConcept")
	@Cacheable("getConcept")
	public R getConcept(HttpServletRequest request){
		String json=configService.selectConfigByKey("store.concept");
		ConceptConfig config = JSONUtil.toBean(json, ConceptConfig.class);
		return R.ok().put("data",config);
	}


	@ApiOperation("读取画布数据")
	@GetMapping("/getCanvas")
	@Cacheable("canvas")
	public R getCanvas(HttpServletRequest request){
		FsStoreCanvasScrm map=new FsStoreCanvasScrm();
		map.setIsDel(0);
		map.setType(1);
		List<FsStoreCanvasScrm> canvas=storeCanvasService.selectFsStoreCanvasList(map);
		if (CollectionUtils.isNotEmpty(canvas)){
			return R.ok().put("data", canvas.get(0));
		}
		return R.ok();
	}



	@ApiOperation("获取推荐健康知识")
	@GetMapping("/getTuiArticle")
	public R getTuiArticle(FsArticleQueryParam param){

		List<FsArticleListQueryVO> list=articleService.selectFsArticleListQuery(param);
		return R.ok().put("data", list);
	}


	@Login
	@ApiOperation("获取购物车数量")
	@GetMapping("/getCartCount")
	public R getCartCount(){
		Integer count=cartService.selectFsStoreCartCountByUserId(Long.parseLong(getUserId()));
		return R.ok().put("data", count);
	}

	@Autowired
	private IFsFamousPrescribeScrmService fsFamousPrescribeService;

	@Autowired
	private IFsQuestionsScrmService questionsService;

	@Autowired
	private IFsMedicatedFoodScrmService medicatedFoodService;

	@Autowired
	private IFsVesselScrmService vesselService;

	@Autowired
	private IFsChineseMedicineScrmService chineseMedicineService;

	@ApiOperation("获取名方列表")
	@GetMapping("/getFamousPrescribeList")
	public R getFamousPrescribeList(FsFamousPrescribeListUParam param)
	{
		PageHelper.startPage(param.getPageNum(), param.getPageSize());
		List<FsFamousPrescribeListUVO> list=fsFamousPrescribeService.selectFsFamousPrescribeListUVO(param);
		PageInfo<FsFamousPrescribeListUVO> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}

	@GetMapping("/getFamousPrescribeById")
	public R getFamousPrescribeById(@RequestParam("id")Long id)
	{
		FsFamousPrescribeScrm fsFamousPrescribe=fsFamousPrescribeService.selectFsFamousPrescribeById(id);
		return R.ok().put("data",fsFamousPrescribe);
	}
	@ApiOperation("获取问答列表")
	@GetMapping("/getQuestionsList")
	public R getQuestionsList(FsQuestionsListUParam param)
	{
		PageHelper.startPage(param.getPageNum(), param.getPageSize());
		List<FsQuestionsListUVO> list=questionsService.selectFsQuestionsListUVO(param);
		PageInfo<FsQuestionsListUVO> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}

	@GetMapping("/getQuestionsById")
	public R getQuestionsById(@RequestParam("id")Long id)
	{
		FsQuestionsScrm questions=questionsService.selectFsQuestionsById(id);
		return R.ok().put("data",questions);
	}
	@ApiOperation("获取穴位列表")
	@GetMapping("/getVesselList")
	public R getVesselList(FsVesselListUParam param)
	{
		PageHelper.startPage(param.getPageNum(), param.getPageSize());
		List<FsVesselListUVO> list=vesselService.selectFsVesselListUVO(param);
		PageInfo<FsVesselListUVO> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}

	@GetMapping("/getVesselById")
	public R getVesselById(@RequestParam("id")Long id)
	{
		FsVesselScrm vessel=vesselService.selectFsVesselById(id);
		return R.ok().put("data",vessel);
	}
	@ApiOperation("获取食谱列表")
	@GetMapping("/getMedicatedFoodList")
	public R getMedicatedFoodList(FsMedicateFoodListUParam param)
	{
		PageHelper.startPage(param.getPageNum(), param.getPageSize());
		List<FsMedicateFoodListUVO> list=medicatedFoodService.selectFsMedicatedFoodListUVO(param);
		PageInfo<FsMedicateFoodListUVO> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}

	@GetMapping("/getMedicatedFoodById")
	public R getMedicatedFoodById(@RequestParam("id")Long id)
	{
		FsMedicatedFoodScrm food=medicatedFoodService.selectFsMedicatedFoodById(id);
		return R.ok().put("data",food);
	}
	@ApiOperation("获取中医列表")
	@GetMapping("/getChineseMedicineList")
	public R getChineseMedicineList(FsChineseMedicineListUParam param)
	{
		PageHelper.startPage(param.getPageNum(), param.getPageSize());
		List<FsChineseMedicineListUVO> list=chineseMedicineService.selectFsChineseMedicineListUVO(param);
		PageInfo<FsChineseMedicineListUVO> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}

	@GetMapping("/getChineseMedicineById")
	public R getChineseMedicineById(@RequestParam("id")Long id)
	{
		FsChineseMedicineScrm chineseMedicine=chineseMedicineService.selectFsChineseMedicineById(id);
		return R.ok().put("data",chineseMedicine);
	}

	/**
	 * 用户协议
	 * @return
	 */
	@GetMapping("/getAgreementConfig")
	public R getAgreementConfig(@RequestParam("name") String name)
	{
		String json=configService.selectConfigByKey("his.agreementConfig");
		AgreementConfig config= JSONUtil.toBean(json, AgreementConfig.class);
		String data = null;
		switch (name){
			case "userRegister":
				data = config.getUserRegister();
				break;
			case "userPrivacy":
				data = config.getUserPrivacy();
				break;
			case "userHealth":
				data = config.getUserHealth();
				break;
			case "vipService":
				data = config.getVipService();
				break;
			case "vipAutomaticService":
				data = config.getVipAutomaticService();
				break;
			case "userRemoveService":
				data = config.getUserRemoveService();
				break;
			default:
				break;
		}

		return R.ok().put("data",data);
	}

	/**
	 * 获取小程序logo
	 * @return
	 */
	@GetMapping("/getAppInfo")
	public R getAppInfo(@RequestParam("appId") String appId)
	{
		Wrapper<FsCoursePlaySourceConfig> queryWrapper = Wrappers.<FsCoursePlaySourceConfig>lambdaQuery()
				.eq(FsCoursePlaySourceConfig::getAppid, appId)
				.eq(FsCoursePlaySourceConfig::getIsDel, 0)
				.last("limit 1");
		FsCoursePlaySourceConfig sourceConfig = coursePlaySourceConfigService.getOne(queryWrapper);
		FsCoursePlaySourceConfig vo = new FsCoursePlaySourceConfig();
		vo.setAppid(appId);
		vo.setImg(sourceConfig.getImg());
		vo.setName(sourceConfig.getName());
		return R.ok().put("data",vo);
	}


}
