package com.fs.app.controller;

import com.fs.common.annotation.Log;
import com.fs.common.constant.LiveKeysConstant;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.live.domain.LiveGoods;
import com.fs.live.service.ILiveGoodsService;
import com.fs.store.domain.FsStoreProduct;
import com.fs.store.domain.FsStoreProductAttr;
import com.fs.store.domain.FsStoreProductAttrValue;
import com.fs.store.domain.FsStoreProductRelation;
import com.fs.store.service.IFsStoreProductAttrService;
import com.fs.store.service.IFsStoreProductAttrValueService;
import com.fs.store.service.IFsStoreProductRelationService;
import com.fs.store.service.IFsStoreProductService;
import com.fs.store.vo.FsStoreProductListQueryVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.fs.app.constant.CommonConstant.REDIS_KEY_COMPANY_USER_TOKEN;

/**
 * 直播商品Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@RestController
@RequestMapping("/app/live/liveGoods")
public class LiveGoodsController extends AppBaseController
{
    @Autowired
    private ILiveGoodsService liveGoodsService;

    @Autowired
    private IFsStoreProductService fsStoreProductService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IFsStoreProductAttrService attrService;
    @Autowired
    private IFsStoreProductRelationService productRelationService;

    @Autowired
    private IFsStoreProductAttrValueService attrValueService;

    /**
     * 查询直播商品列表
     */
    @GetMapping("/list")
    public R list(LiveGoods liveGoods)
    {
        PageHelper.startPage(Integer.parseInt(ServletUtils.getParameter("pageNum")), Integer.parseInt(ServletUtils.getParameter("pageSize")));
        List<LiveGoods> list = liveGoodsService.selectLiveGoodsList(liveGoods);
        PageInfo<LiveGoods> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    /**
     * 导出直播商品列表
     */
    @Log(title = "直播商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveGoods liveGoods)
    {
        List<LiveGoods> list = liveGoodsService.selectLiveGoodsList(liveGoods);
        ExcelUtil<LiveGoods> util = new ExcelUtil<LiveGoods>(LiveGoods.class);
        return util.exportExcel(list, "直播商品数据");
    }

    /**
     * 获取直播商品详细信息
     */
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId)
    {
        return AjaxResult.success(liveGoodsService.selectLiveGoodsByGoodsId(goodsId));
    }

    /**
     * 新增直播商品
     */
    @Log(title = "直播商品", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody LiveGoods liveGoods)
    {
        liveGoodsService.insertLiveGoods(liveGoods);
        return R.ok();
    }

    /**
     * 修改直播商品
     */
    @Log(title = "直播商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody LiveGoods liveGoods)
    {
        return liveGoodsService.updateLiveGoods(liveGoods);
    }

    /**
     * 删除直播商品
     */
    @Log(title = "直播商品", businessType = BusinessType.DELETE)
	@DeleteMapping("/{goodsIds}")
    public R remove(@PathVariable Long[] goodsIds)
    {
        liveGoodsService.deleteLiveGoodsByGoodsIds(goodsIds);
        return R.ok();
    }

    /**
     * 获取直播店铺
     * */
    @GetMapping("/liveStore/{liveId}")
    public R liveGoodsStore(@PathVariable Long liveId,@RequestParam String key)
    {
        String userId = getUserId();
        return liveGoodsService.getStoreByLiveId(liveId, key, userId);
    }

    /**
     *商品详情
     */
    @GetMapping("/liveGoodsDetail/{productId}")
    public R liveGoodsDetail(@PathVariable Long productId)
    {
        return R.ok().put("data",fsStoreProductService.selectFsStoreProductById(productId));

//        // 先从缓存中获取商品详情
//        String cacheKey = String.format(LiveKeysConstant.PRODUCT_DETAIL_CACHE, productId);
//        Map<String, Object> cachedData = redisCache.getCacheObject(cacheKey);
//
//        FsStoreProduct product;
//        List<FsStoreProductAttr> productAttr;
//        List<FsStoreProductAttrValue> productValues;
//
//        if (cachedData != null) {
//            // 从缓存中获取数据
//            product = (FsStoreProduct) cachedData.get("product");
//            productAttr = (List<FsStoreProductAttr>) cachedData.get("productAttr");
//            productValues = (List<FsStoreProductAttrValue>) cachedData.get("productValues");
//        } else {
//            // 缓存中没有，从数据库查询
//            product = fsStoreProductService.selectFsStoreProductById(productId);
//            if(product==null){
//                return R.error("商品不存在或已下架");
//            }
//            productAttr = attrService.selectFsStoreProductAttrByProductId(productId);
//            productValues = attrValueService.selectFsStoreProductAttrValueByProductId(productId);
//
//            // 将数据存入缓存
//            Map<String, Object> cacheData = new HashMap<>();
//            cacheData.put("product", product);
//            cacheData.put("productAttr", productAttr);
//            cacheData.put("productValues", productValues);
//            redisCache.setCacheObject(cacheKey, cacheData, LiveKeysConstant.PRODUCT_DETAIL_CACHE_EXPIRE, TimeUnit.SECONDS);
//        }
//
//        // 获取用户的TOKEN写入足迹
//        String userId=getUserId();
//        if(userId!=null){
//            FsStoreProductRelation productRelation=new FsStoreProductRelation();
//            productRelation.setIsDel(0);
//            productRelation.setUserId(Long.parseLong(userId));
//            productRelation.setProductId(product.getProductId());
//            productRelation.setType("foot");
//            List<FsStoreProductRelation> productRelations=productRelationService.selectFsStoreProductRelationList(productRelation);
//            if(productRelations!=null&&productRelations.size()>0){
//                FsStoreProductRelation relation=productRelations.get(0);
//                relation.setUpdateTime(new Date());
//                productRelationService.updateFsStoreProductRelation(relation);
//            }
//            else{
//                FsStoreProductRelation relation=new FsStoreProductRelation();
//                relation.setUserId(Long.parseLong(userId));
//                relation.setIsDel(0);
//                relation.setProductId(product.getProductId());
//                relation.setUpdateTime(new Date());
//                relation.setType("foot");
//                relation.setCreateTime(new Date());
//                relation.setUpdateTime(new Date());
//                productRelationService.insertFsStoreProductRelation(relation);
//            }
//        }
//        return R.ok().put("product",product).put("productAttr",productAttr).put("productValues",productValues);

    }

    /**
     *当前正在展示的商品
     */
    @GetMapping("/showGoods/{liveId}")
    public R showGoods(@PathVariable Long liveId)
    {
        return R.ok().put("data", liveGoodsService.showGoods(liveId));
    }


}
