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

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("/dictOpinionFeedback")
@RequiredArgsConstructor
public class DictOpinionFeedbackController {

    private final DictOpinionFeedbackService dictOpinionFeedbackService;

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

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

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

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

//    @ApiOperation("下载意见反馈字典导入模板")
//    @ApiOperationSupport(order = 5)
//    @GetMapping("/downloadTemplate")
//    public void downloadTemplate(HttpServletResponse response) throws IOException {
//        log.info("dictOpinionFeedback.downloadTemplate");
//        dictOpinionFeedbackService.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);
            }
        }
    }
}


