package com.ruoyi.cms.controller.cms;

import com.ruoyi.cms.domain.policy.PolicyInfo;
import com.ruoyi.cms.domain.policy.PolicyInfoQuery;
import com.ruoyi.cms.service.policy.IPolicyInfoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.uuid.IdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 政策信息CMS管理Controller
 * @author kiro
 * @date 2026-01-11
 */
@RestController
@RequestMapping("/cms/policyInfo")
@Api(tags = "CMS：政策信息管理")
public class CmsPolicyInfoController extends BaseController {

    @Autowired
    private IPolicyInfoService policyInfoService;

    @Value("${policy.upload.path:/data/policy/files}")
    private String uploadPath;

    @Value("${policy.upload.domain:}")
    private String uploadDomain;

    /**
     * 查询政策列表
     */
    @PreAuthorize("@ss.hasPermi('cms:policyInfo:list')")
    @ApiOperation("查询政策列表")
    @GetMapping("/list")
    public TableDataInfo list(PolicyInfoQuery query) {
        startPage();
        return getDataTable(policyInfoService.selectList(query));
    }

    /**
     * 获取政策详情
     */
    @PreAuthorize("@ss.hasPermi('cms:policyInfo:query')")
    @ApiOperation("获取政策详情")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(policyInfoService.selectById(id));
    }

    /**
     * 新增政策
     */
    @PreAuthorize("@ss.hasPermi('cms:policyInfo:add')")
    @Log(title = "政策信息", businessType = BusinessType.INSERT)
    @ApiOperation("新增政策")
    @PostMapping
    public AjaxResult add(@RequestBody PolicyInfo policyInfo) {
        return toAjax(policyInfoService.insert(policyInfo));
    }

    /**
     * 修改政策
     */
    @PreAuthorize("@ss.hasPermi('cms:policyInfo:edit')")
    @Log(title = "政策信息", businessType = BusinessType.UPDATE)
    @ApiOperation("修改政策")
    @PutMapping
    public AjaxResult edit(@RequestBody PolicyInfo policyInfo) {
        return toAjax(policyInfoService.update(policyInfo));
    }

    /**
     * 删除政策
     */
    @PreAuthorize("@ss.hasPermi('cms:policyInfo:remove')")
    @Log(title = "政策信息", businessType = BusinessType.DELETE)
    @ApiOperation("删除政策")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(policyInfoService.deleteByIds(ids));
    }

    /**
     * 上传政策文件
     */
    @PreAuthorize("@ss.hasPermi('cms:policyInfo:add')")
    @Log(title = "政策文件上传", businessType = BusinessType.OTHER)
    @ApiOperation("上传政策文件")
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成新文件名：日期目录 + UUID + 后缀
            String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String newFileName = IdUtils.fastSimpleUUID() + suffix;

            // 创建目录
            File destDir = new File(uploadPath + File.separator + dateDir);
            if (!destDir.exists()) {
                destDir.mkdirs();
            }

            // 保存文件
            String filePath = dateDir + "/" + newFileName;
            File destFile = new File(uploadPath + File.separator + dateDir + File.separator + newFileName);
            file.transferTo(destFile);

            // 构建返回URL
            String fileUrl = uploadDomain + "/file/" + filePath;

            Map<String, String> result = new HashMap<>();
            result.put("fileUrl", fileUrl);
            result.put("fileName", originalFilename);
            result.put("filePath", filePath);

            return success(result);
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            return error("文件上传失败：" + e.getMessage());
        }
    }
}
