package com.fs.web.controller.system;

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.redis.RedisCache;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.system.domain.SysKeyword;
import com.fs.system.service.ISysKeywordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统关键字Controller
 *
 * @author fs
 * @date 2025-05-14
 */
@RestController
@RequestMapping("/system/keyword")
public class SysKeywordController extends BaseController
{
    @Autowired
    private ISysKeywordService sysKeywordService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    public RedisTemplate<String,String> redisTemplate;

    private static final String REDIS_KEY = "sys:keywords";

    /**
     * 查询系统关键字列表
     */
    @PreAuthorize("@ss.hasPermi('system:keyword:list')")
    @GetMapping("/list")
    public R list(SysKeyword sysKeyword)
    {
//        startPage();
        PageHelper.startPage(sysKeyword.getPageNum(), sysKeyword.getPageSize());
        List<SysKeyword> list = sysKeywordService.selectSysKeywordList(sysKeyword);

        PageInfo<SysKeyword> pageInfo = new PageInfo<>(list);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        return R.ok(result);
    }

    /**
     * 导出系统关键字列表
     */
    @PreAuthorize("@ss.hasPermi('system:keyword:export')")
    @Log(title = "系统关键字", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysKeyword sysKeyword)
    {
        List<SysKeyword> list = sysKeywordService.selectSysKeywordList(sysKeyword);
        ExcelUtil<SysKeyword> util = new ExcelUtil<SysKeyword>(SysKeyword.class);
        return util.exportExcel(list, "系统关键字数据");
    }

    /**
     * 获取系统关键字详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:keyword:query')")
    @GetMapping(value = "/{keywordId}")
    public AjaxResult getInfo(@PathVariable("keywordId") Long keywordId)
    {
        return AjaxResult.success(sysKeywordService.selectSysKeywordById(keywordId));
    }

    /**
     * 新增系统关键字
     */
    @PreAuthorize("@ss.hasPermi('system:keyword:add')")
    @Log(title = "系统关键字", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysKeyword sysKeyword)
    {
        int i = sysKeywordService.insertSysKeyword(sysKeyword);
        // 缓存
        redisTemplate.opsForSet().add(REDIS_KEY, sysKeyword.getKeyword());
        return toAjax(i);
    }

    /**
     * 修改系统关键字
     */
    @PreAuthorize("@ss.hasPermi('system:keyword:edit')")
    @Log(title = "系统关键字", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysKeyword sysKeyword)
    {
        //获取之前的数据
        SysKeyword sysKeywordOld = sysKeywordService.selectSysKeywordById(sysKeyword.getKeywordId());
        String keywordOld = sysKeywordOld.getKeyword();
        int i = sysKeywordService.updateSysKeyword(sysKeyword);
        // 更新缓存
        redisTemplate.opsForSet().remove(REDIS_KEY, keywordOld);
        redisTemplate.opsForSet().add(REDIS_KEY, sysKeyword.getKeyword());
        return toAjax(i);
    }

    /**
     * 删除系统关键字
     */
    @PreAuthorize("@ss.hasPermi('system:keyword:remove')")
    @Log(title = "系统关键字", businessType = BusinessType.DELETE)
	@DeleteMapping("/{keywordIds}")
    public AjaxResult remove(@PathVariable Long[] keywordIds)
    {
        List<SysKeyword> sysKeywords = sysKeywordService.selectSysKeywordByIds(keywordIds);
        int i = sysKeywordService.deleteSysKeywordByIds(keywordIds);
        if (!CollectionUtils.isEmpty(sysKeywords)) {
            redisTemplate.opsForSet().remove(REDIS_KEY, sysKeywords.stream().map(SysKeyword::getKeyword).toArray(String[]::new));
        }
        return toAjax(i);
    }

    /**
     * 启动加载全部关键字到缓存
     */
    @PostConstruct
    public void initKeywords() {
        SysKeyword sysKeywordParam = new SysKeyword();
        List<SysKeyword> sysKeywords = sysKeywordService.selectSysKeywordList(sysKeywordParam);
        List<String> keywords = sysKeywords.stream()
                .map(SysKeyword::getKeyword)
                .collect(Collectors.toList());

        if (!keywords.isEmpty()) {
            redisTemplate.opsForSet().add(REDIS_KEY, keywords.toArray(new String[0]));
        }
        System.out.println("加载全部关键字到缓存");
    }
}
