package shop.alien.store.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreDictionary;
import shop.alien.store.service.DictionaryLibraryService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Api(tags = {"2.6平台-字典库管理"})
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/dictionaryLibrary")
@RequiredArgsConstructor
public class DictionaryLibraryController {

    private final DictionaryLibraryService dictionaryLibraryService;

    @ApiOperation("查询字典库（三级树形结构），支持根据dictDetail过滤")
    @ApiOperationSupport(order = 1)
    @GetMapping("/queryDictionaryLibraryTree")
    public R<List<StoreDictionary>> queryDictionaryLibraryTree(@RequestParam(required = false) String dictDetail) {
        log.info("dictionaryLibrary.queryDictionaryLibraryTree dictDetail={}", dictDetail);
        List<StoreDictionary> result = dictionaryLibraryService.queryDictionaryLibraryTree(dictDetail);
        return R.data(result);
    }

    @ApiOperation("新增字典库（支持一级、二级、三级）")
    @ApiOperationSupport(order = 2)
    @PostMapping("/addDictionaryLibrary")
    public R<Boolean> addDictionaryLibrary(@RequestBody StoreDictionary storeDictionary) {
        log.info("dictionaryLibrary.addDictionaryLibrary:{}", storeDictionary);
        try {
            boolean result = dictionaryLibraryService.addDictionaryLibrary(storeDictionary);
            if (result) {
                return R.success("新增成功");
            } else {
                return R.fail("新增失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("dictionaryLibrary.addDictionaryLibrary error: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("dictionaryLibrary.addDictionaryLibrary error", e);
            return R.fail("新增失败：" + e.getMessage());
        }
    }

    @ApiOperation("修改字典库（支持一级、二级、三级）")
    @ApiOperationSupport(order = 3)
    @PutMapping("/updateDictionaryLibrary")
    public R<Boolean> updateDictionaryLibrary(@RequestBody StoreDictionary storeDictionary) {
        log.info("dictionaryLibrary.updateDictionaryLibrary:{}", storeDictionary);
        try {
            boolean result = dictionaryLibraryService.updateDictionaryLibrary(storeDictionary);
            if (result) {
                return R.success("修改成功");
            } else {
                return R.fail("修改失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("dictionaryLibrary.updateDictionaryLibrary error: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("dictionaryLibrary.updateDictionaryLibrary error", e);
            return R.fail("修改失败：" + e.getMessage());
        }
    }

    @ApiOperation("批量导入字典库")
    @ApiOperationSupport(order = 4)
    @PostMapping("/import")
    public R<String> importDictionaryLibrary(@RequestParam("file") MultipartFile file) {
        log.info("dictionaryLibrary.importDictionaryLibrary fileName={}", 
                file != null ? file.getOriginalFilename() : "null");
        try {
            return dictionaryLibraryService.importDictionaryLibrary(file);
        } catch (Exception e) {
            log.error("dictionaryLibrary.importDictionaryLibrary error", e);
            return R.fail("导入失败：" + e.getMessage());
        }
    }

//    @ApiOperation("下载字典库导入模板")
//    @ApiOperationSupport(order = 5)
//    @GetMapping("/downloadTemplate")
//    public void downloadTemplate(HttpServletResponse response) throws IOException {
//        log.info("dictionaryLibrary.downloadTemplate");
//        dictionaryLibraryService.downloadTemplate(response);
//    }

    @ApiOperation("下载举报导入模板")
    @ApiOperationSupport(order = 10)
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        log.info("StoreMenuPlatformController.downloadTemplate");
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            // 从resources/templates目录读取模板文件
            Resource resource = new ClassPathResource("templates/举报导入模版.xlsx");
            inputStream = resource.getInputStream();

            // 设置响应头
            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            String fileName = "举报导入模板.xlsx";
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + encodedFileName + "\";filename*=utf-8''" + encodedFileName);

            // 输出文件流
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();

            log.info("举报导入模板下载成功");
        } catch (Exception e) {
            log.error("下载举报导入模板失败", e);
            throw new RuntimeException("下载模板失败：" + e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                log.error("关闭流失败", e);
            }
        }
    }


    @ApiOperation("删除字典库（支持一级、二级、三级）")
    @ApiOperationSupport(order = 6)
    @DeleteMapping("/deleteDictionaryLibrary/{id}")
    public R<Boolean> deleteDictionaryLibrary(@PathVariable Long id) {
        log.info("dictionaryLibrary.deleteDictionaryLibrary id={}", id);
        try {
            int result = dictionaryLibraryService.deleteDictionaryLibrary(id);
            if (result > 0) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("dictionaryLibrary.deleteDictionaryLibrary error: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("dictionaryLibrary.deleteDictionaryLibrary error", e);
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @ApiOperation("修改字典库状态（通过id修改hidden为1）")
    @ApiOperationSupport(order = 7)
    @PutMapping("/updateHiddenStatus/{id}")
    public R<Boolean> updateHiddenStatus(@PathVariable Long id) {
        log.info("dictionaryLibrary.updateHiddenStatus id={}", id);
        try {
            int result = dictionaryLibraryService.updateHiddenStatus(id);
            if (result > 0) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("dictionaryLibrary.updateHiddenStatus error: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("dictionaryLibrary.updateHiddenStatus error", e);
            return R.fail("修改失败：" + e.getMessage());
        }
    }

    @ApiOperation("根据dictDetail查询字典库（包含父级或子级树形结构）")
    @ApiOperationSupport(order = 8)
    @GetMapping("/selectDictBydictDetail")
    public R<List<StoreDictionary>> selectDictBydictDetail(@RequestParam String dictDetail) {
        log.info("dictionaryLibrary.selectDictBydictDetail dictDetail={}", dictDetail);
        try {
            // 内部调用queryDictionaryLibraryTree方法
            List<StoreDictionary> result = dictionaryLibraryService.queryDictionaryLibraryTree(dictDetail);
            return R.data(result);
        } catch (Exception e) {
            log.error("dictionaryLibrary.selectDictBydictDetail error", e);
            return R.fail("查询失败：" + e.getMessage());
        }
    }

}
