package com.fs.live.controller;

import com.fs.common.annotation.Log;
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.domain.entity.SysUser;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.hisStore.vo.FsStoreProductListVO;
import com.fs.live.domain.LiveGoods;
import com.fs.live.service.ILiveGoodsService;
import com.fs.live.vo.LiveGoodsListVo;
import com.fs.live.vo.LiveGoodsVo;
import com.fs.system.domain.SysConfig;
import com.fs.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

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

    @Autowired
    private IFsStoreProductScrmService fsStoreProductService;

    @Autowired
    private ISysConfigService configService;


    /**
     * 查询直播商品列表
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:list')")
    @GetMapping("/list")
    public TableDataInfo list(LiveGoods liveGoods)
    {
        // 设置企业ID和企业用户ID
        setCompanyId(liveGoods);
        // liveId 已通过 LiveGoods 对象传入，无需再次设置

        startPage();
        List<LiveGoodsVo> list = liveGoodsService.selectProductListByLiveId(liveGoods);
        return getDataTable(list);
    }

    /**
     * 导出直播商品列表
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:export')")
    @Log(title = "直播商品", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveGoods liveGoods)
    {
        // 设置企业ID和企业用户ID
        setCompanyId(liveGoods);

        List<LiveGoods> list = liveGoodsService.selectLiveGoodsList(liveGoods);
        ExcelUtil<LiveGoods> util = new ExcelUtil<LiveGoods>(LiveGoods.class);
        return util.exportExcel(list, "直播商品数据");
    }

    /**
     * 获取直播商品详细信息
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:query')")
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId)
    {
        //CompanyUser user = SecurityUtils.getLoginUser().getUser();
        return AjaxResult.success();
    }

    /**
     * 新增直播商品
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:add')")
    @Log(title = "直播商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Map<String, Object> payload)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //CompanyUser companyUser = companyUserService.selectCompanyUserById(loginUser.getUser().getUserId());
        SysUser user = loginUser.getUser();
        return toAjax(liveGoodsService.insertLiveGoodsAdmin(payload, user));
    }

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

    /**
     * 删除直播商品
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:remove')")
    @Log(title = "直播商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{goodsIds}")
    public AjaxResult remove(@PathVariable Long[] goodsIds)
    {
        return toAjax(liveGoodsService.deleteLiveGoodsByGoodsIds(goodsIds));
    }

    /**
     * 设置企业ID 企业用户ID
     * @param liveGoods 直播商品
     */
    private void setCompanyId(LiveGoods liveGoods) {
        // 设置企业ID 企业用户ID
        //LoginUser loginUser = SecurityUtils.getLoginUser();
        //CompanyUser companyUser = companyUserService.selectCompanyUserById(loginUser.getUser().getUserId());
        //liveGoods.setCompanyId(companyUser.getCompanyId());
        //liveGoods.setCompanyUserId(companyUser.getUserId());
    }

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:list')")
    @GetMapping("/liveList")
    public TableDataInfo liveList(LiveGoods liveGoods)
    {
        startPage();
        List<FsStoreProductListVO> list = fsStoreProductService.liveList(liveGoods);
        return getDataTable(list);
    }

    /**
     * 获取直播店铺
     * */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:query')")
    @GetMapping("/liveStore/{liveId}")
    public R liveGoodsStore(@PathVariable Long liveId,@RequestParam String key)
    {
        return liveGoodsService.getStoreByLiveId(liveId, key);
    }

    /**
     * 批量上下架视频
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:edit')")
    @PostMapping("/handleShelfOrUn")
    public R handleShelfOrUn(@RequestBody LiveGoodsListVo listVo) {
        return liveGoodsService.handleShelfOrUnAdmin(listVo);
    }

    /**
     * 批量删除视频
     */
    @PostMapping("/handleDeleteSelected")
    public R handleDeleteSelected(@RequestBody LiveGoodsListVo listVo) {
        return liveGoodsService.handleDeleteSelectedAdmin(listVo);
    }

    /**
     * 更新展示状态
     */
//    @PreAuthorize("@ss.hasPermi('live:liveGoods:edit')")
    @PostMapping("/handleIsShowChange")
    public R handleIsShowChange(@RequestBody LiveGoodsListVo listVo) {
        return liveGoodsService.handleIsShowChange(listVo);
    }

    /**
     * 查询直播低库存阈值
     */
    @GetMapping("/stockHintThreshold")
    public AjaxResult getStockHintThreshold() {
        final String configKey = "live.lowStockThreshold";
        final int defaultThreshold = 10;
        String configValue = configService.selectConfigByKey(configKey);
        int threshold = defaultThreshold;
        try {
            if (configValue != null && !configValue.trim().isEmpty()) {
                threshold = Integer.parseInt(configValue.trim());
            }
        } catch (NumberFormatException ignore) {
            threshold = defaultThreshold;
        }
        AjaxResult result = AjaxResult.success();
        result.put("configKey", configKey);
        result.put("threshold", threshold);
        return result;
    }

    /**
     * 更新直播低库存阈值
     */
    @Log(title = "直播低库存阈值", businessType = BusinessType.UPDATE)
    @PostMapping("/stockHintThreshold")
    public AjaxResult updateStockHintThreshold(@RequestParam Integer threshold) {
        final String configKey = "live.lowStockThreshold";
        if (threshold == null || threshold < 1 || threshold > 9999) {
            return AjaxResult.error("阈值范围需在1~9999");
        }
        SysConfig config = configService.selectConfigByConfigKey(configKey);
        if (config == null) {
            config = new SysConfig();
            config.setConfigName("直播低库存阈值");
            config.setConfigKey(configKey);
            config.setConfigType("N");
            config.setRemark("直播商品库存提示阈值，stock<=threshold时显示仅剩X件");
            config.setCreateBy(SecurityUtils.getUsername());
            config.setConfigValue(String.valueOf(threshold));
            configService.insertConfig(config);
        } else {
            config.setConfigValue(String.valueOf(threshold));
            config.setUpdateBy(SecurityUtils.getUsername());
            configService.updateConfig(config);
        }
        return AjaxResult.success();
    }
}
