package com.boyue.hasfj.controller;

import java.util.List;
import java.util.Map;
import java.nio.charset.StandardCharsets;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.boyue.common.annotation.Log;
import com.boyue.common.core.controller.BaseController;
import com.boyue.common.core.domain.AjaxResult;
import com.boyue.common.enums.BusinessType;
import com.boyue.hasfj.domain.HtmlPages;
import com.boyue.hasfj.service.IHtmlPagesService;
import com.boyue.common.utils.poi.ExcelUtil;
import com.boyue.common.core.page.TableDataInfo;
import com.boyue.common.utils.StringUtils;
import com.boyue.common.utils.file.FileUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 司法局法律规定、典型案例、单下载Controller
 *
 * @author boyue
 * @date 2025-05-28
 */
@RestController
@RequestMapping("/hasfj/hasfjpages")
@Tag(name = "【司法局法律规定、典型案例、单下载】管理")
public class HtmlPagesController extends BaseController
{
    @Autowired
    private IHtmlPagesService htmlPagesService;

    @Value("${boyue.profile}")
    private String uploadPath;

    @Autowired
    private HttpServletRequest request;

    /**
     * 查询司法局法律规定、典型案例、单下载列表
     */
    @Operation(summary = "查询司法局法律规定、典型案例、单下载列表")
//    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:list')")
    @GetMapping("/list")
    public TableDataInfo list(HtmlPages htmlPages)
    {
        startPage();
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return getDataTable(list);
    }

    /**
     * 查询指定类型的页面列表
     */
    @Operation(summary = "查询指定类型的页面列表")
    @GetMapping("/listByType/{pageType}")
    public AjaxResult listByType(@PathVariable("pageType") String pageType)
    {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType(pageType);
        htmlPages.setStatus(1); // 只查询启用状态的
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return success(list);
    }

    /**
     * 导出司法局法律规定、典型案例、单下载列表
     */
    @Operation(summary = "导出司法局法律规定、典型案例、单下载列表")
//    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:export')")
    @Log(title = "司法局法律规定、典型案例、单下载", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HtmlPages htmlPages)
    {
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        ExcelUtil<HtmlPages> util = new ExcelUtil<HtmlPages>(HtmlPages.class);
        util.exportExcel(response, list, "司法局法律规定、典型案例、单下载数据");
    }

    /**
     * 导入数据
     */
    @Operation(summary = "导入数据")
    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:import')")
    @Log(title = "司法局法律规定、典型案例、单下载", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String importType) throws Exception
    {
        try {
            // 根据importType决定导入方式
            if ("excel".equals(importType)) {
                // Excel导入
                ExcelUtil<HtmlPages> util = new ExcelUtil<HtmlPages>(HtmlPages.class);
                List<HtmlPages> htmlPagesList = util.importExcel(file.getInputStream());
                String operName = getUsername();
                String message = htmlPagesService.importHtmlPages(htmlPagesList, updateSupport, operName);
                return success(message);
            } else if ("batch".equals(importType)) {
                // JSON批量导入
                String jsonContent = new String(file.getBytes(), StandardCharsets.UTF_8);
                ObjectMapper objectMapper = new ObjectMapper();
                List<HtmlPages> htmlPagesList = objectMapper.readValue(jsonContent, 
                    objectMapper.getTypeFactory().constructCollectionType(List.class, HtmlPages.class));
                
                String operName = getUsername();
                String message = htmlPagesService.importHtmlPages(htmlPagesList, updateSupport, operName);
                return success(message);
            } else {
                return error("不支持的导入类型");
            }
        } catch (Exception e) {
            logger.error("导入数据异常", e);
            return error("导入数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 下载导入模板
     */
    @Operation(summary = "下载导入模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<HtmlPages> util = new ExcelUtil<HtmlPages>(HtmlPages.class);
        util.importTemplateExcel(response, "司法局法律规定、典型案例、单下载数据");
    }

    /**
     * 删除附件
     */
    @Operation(summary = "删除附件")
    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:edit')")
    @Log(title = "司法局法律规定、典型案例、单下载-删除附件", businessType = BusinessType.DELETE)
    @PostMapping("/deleteAttachment")
    public AjaxResult deleteAttachment(@RequestBody Map<String, String> params)
    {
        try {
            String attachmentUrl = params.get("attachmentUrl");
            if (StringUtils.isEmpty(attachmentUrl)) {
                return error("附件URL不能为空");
            }
            
            logger.info("删除附件请求: {}", attachmentUrl);
            
            boolean result = htmlPagesService.deleteAttachment(attachmentUrl);
            if (result) {
                return success("附件删除成功");
            } else {
                return error("附件删除失败，可能文件不存在或没有权限");
            }
        } catch (Exception e) {
            logger.error("删除附件异常", e);
            return error("删除附件失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据路径删除文件
     */
    @Operation(summary = "根据路径删除文件")
    @PreAuthorize("@ss.hasPermi('common:profile:delete')")  
    @Log(title = "附件管理-删除文件", businessType = BusinessType.DELETE)
    @PostMapping("/deleteFileByPath")
    public AjaxResult deleteFile(@RequestBody Map<String, String> requestBody) {
        try {
            String filePath = requestBody.get("path");
            if (StringUtils.isEmpty(filePath)) {
                return error("文件路径不能为空");
            }
            
            logger.info("删除文件请求: {}", filePath);
            
            boolean result = htmlPagesService.deleteFileByPath(filePath);
            if (result) {
                return success("文件删除成功");
            } else {
                return error("文件删除失败，可能文件不存在或没有权限");
            }
        } catch (Exception e) {
            logger.error("删除文件异常", e);
            return error("删除文件失败: " + e.getMessage());
        }
    }

    /**
     * 获取司法局法律规定、典型案例、单下载详细信息
     */
    @Operation(summary = "获取司法局法律规定、典型案例、单下载详细信息")
//    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(htmlPagesService.selectHtmlPagesById(id));
    }

    /**
     * 根据访问ID获取页面详情
     */
    @Operation(summary = "根据访问ID获取页面详情")
    @GetMapping(value = "/format/{formatId}")
    public AjaxResult getInfoByFormatId(@PathVariable("formatId") String formatId)
    {
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setFormatId(formatId);
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        if (list != null && !list.isEmpty()) {
            // 获取页面
            HtmlPages page = list.get(0);
            // 使用专门的方法更新浏览次数，避免并发问题
            htmlPagesService.updateHtmlPagesViewCount(page.getId());
            // 重新查询最新数据
            page = htmlPagesService.selectHtmlPagesById(page.getId());
            return success(page);
        }
        return error("未找到对应页面");
    }

    /**
     * 新增司法局法律规定、典型案例、单下载
     */
    @Operation(summary = "新增司法局法律规定、典型案例、单下载")
//    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:add')")
    @Log(title = "司法局法律规定、典型案例、单下载", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HtmlPages htmlPages)
    {
        return toAjax(htmlPagesService.insertHtmlPages(htmlPages));
    }

    /**
     * 修改司法局法律规定、典型案例、单下载
     */
    @Operation(summary = "修改司法局法律规定、典型案例、单下载")
//    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:edit')")
    @Log(title = "司法局法律规定、典型案例、单下载", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HtmlPages htmlPages)
    {
        return toAjax(htmlPagesService.updateHtmlPages(htmlPages));
    }

    /**
     * 删除司法局法律规定、典型案例、单下载
     */
    @Operation(summary = "删除司法局法律规定、典型案例、单下载")
//    @PreAuthorize("@ss.hasPermi('hasfj:hasfjpages:remove')")
    @Log(title = "司法局法律规定、典型案例、单下载", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable( name = "ids" ) Long[] ids)
    {
        return toAjax(htmlPagesService.deleteHtmlPagesByIds(ids));
    }

    /**
     * 获取指定类型的页面列表用于二维码展示
     */
    @Operation(summary = "获取指定类型的页面列表用于二维码展示")
    @GetMapping("/qrcodes")
    public TableDataInfo getQRCodes(
            @RequestParam(value = "type", required = false, defaultValue = "law") String type,
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "6") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        HtmlPages htmlPages = new HtmlPages();
        htmlPages.setPageType(type);
        htmlPages.setStatus(1); // 只查询启用状态的
        List<HtmlPages> list = htmlPagesService.selectHtmlPagesList(htmlPages);
        return getDataTable(list);
    }
}