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.CrossOrigin;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreDictionary;
import shop.alien.store.service.DictStoreTagService;

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.7平台-店铺字典标签管理"})
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/dictStoreTag")
@RequiredArgsConstructor
public class DictStoreTagController {

    private final DictStoreTagService dictStoreTagService;

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

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

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

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

//    @ApiOperation("下载店铺标签字典导入模板")
//    @ApiOperationSupport(order = 5)
//    @GetMapping("/downloadTemplate")
//    public void downloadTemplate(HttpServletResponse response) throws IOException {
//        log.info("dictStoreTag.downloadTemplate");
//        dictStoreTagService.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);
            }
        }
    }
}


