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.FilterConditionService;

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 = {"平台-筛选条件管理"})
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/filterCondition")
@RequiredArgsConstructor
public class FilterConditionController {

    private final FilterConditionService filterConditionService;

    @ApiOperation("查询筛选条件（四级树形结构），支持根据dictDetail过滤")
    @ApiOperationSupport(order = 1)
    @GetMapping("/queryFilterConditionTree")
    public R<List<StoreDictionary>> queryFilterConditionTree(@RequestParam(required = false) String dictDetail) {
        log.info("filterCondition.queryFilterConditionTree dictDetail={}", dictDetail);
        List<StoreDictionary> result = filterConditionService.queryFilterConditionTree(dictDetail);
        return R.data(result);
    }

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

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

    @ApiOperation("批量导入筛选条件")
    @ApiOperationSupport(order = 4)
    @PostMapping("/import")
    public R<String> importFilterCondition(@RequestParam("file") MultipartFile file) {
        log.info("filterCondition.importFilterCondition fileName={}", 
                file != null ? file.getOriginalFilename() : "null");
        try {
            return filterConditionService.importFilterCondition(file);
        } catch (Exception e) {
            log.error("filterCondition.importFilterCondition error", e);
            return R.fail("导入失败：" + e.getMessage());
        }
    }

//    @ApiOperation("下载筛选条件导入模板")
//    @ApiOperationSupport(order = 5)
//    @GetMapping("/downloadTemplate")
//    public void downloadTemplate(HttpServletResponse response) throws IOException {
//        log.info("filterCondition.downloadTemplate");
//        filterConditionService.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);
            }
        }
    }

}

