package shop.alien.storeplatform.controller;

import io.swagger.annotations.*;
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.storeplatform.entity.StorePlatformBathFacility;
import shop.alien.storeplatform.service.StorePlatformBathFacilityService;
import shop.alien.storeplatform.vo.ExcelImportVo;

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

/**
 * 商户平台-洗浴设施及服务Controller
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"商户平台-洗浴汗蒸"})
@ApiSort(4)
@CrossOrigin
@RestController
@RequestMapping("/bathFacilityService")
@RequiredArgsConstructor
public class StorePlatformBathFacilityServiceController {

    private final StorePlatformBathFacilityService facilityService;

    @ApiOperation("根据ID查询设施")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设施ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getById")
    public R<StorePlatformBathFacility> getById(@RequestParam("id") Integer id) {
        log.info("StorePlatformBathFacilityServiceController.getById id={}", id);
        StorePlatformBathFacility facility = facilityService.getById(id);
        if (facility == null) {
            return R.fail("设施不存在");
        }
        return R.data(facility);
    }

    @ApiOperation("根据门店ID查询设施列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getListByStoreId")
    public R<List<StorePlatformBathFacility>> getListByStoreId(@RequestParam("storeId") Integer storeId) {
        log.info("StorePlatformBathFacilityServiceController.getListByStoreId storeId={}", storeId);
        List<StorePlatformBathFacility> list = facilityService.getListByStoreId(storeId);
        return R.data(list);
    }

    @ApiOperation("根据门店ID和区域分类查询设施列表")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "facilityCategory", value = "区域分类(1:洗浴区, 2:汗蒸区, 3:休闲区, 4:餐饮区)", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getListByStoreIdAndCategory")
    public R<List<StorePlatformBathFacility>> getListByStoreIdAndCategory(@RequestParam("storeId") Integer storeId,
                                                                         @RequestParam(value = "facilityCategory", required = false) Integer facilityCategory) {
        log.info("StorePlatformBathFacilityServiceController.getListByStoreIdAndCategory storeId={}, facilityCategory={}", storeId, facilityCategory);
        List<StorePlatformBathFacility> list = facilityService.getListByStoreIdAndCategory(storeId, facilityCategory);
        return R.data(list);
    }

    @ApiOperation("新增设施")
    @ApiOperationSupport(order = 4)
    @PostMapping("/save")
    public R<StorePlatformBathFacility> save(@RequestBody StorePlatformBathFacility facility) {
        log.info("StorePlatformBathFacilityServiceController.save facility={}", facility);
        return facilityService.saveFacility(facility);
    }

    @ApiOperation("修改设施")
    @ApiOperationSupport(order = 5)
    @PostMapping("/update")
    public R<StorePlatformBathFacility> update(@RequestBody StorePlatformBathFacility facility) {
        log.info("StorePlatformBathFacilityServiceController.update facility={}", facility);
        return facilityService.updateFacility(facility);
    }

    @ApiOperation("新增或修改设施")
    @ApiOperationSupport(order = 6)
    @PostMapping("/saveOrUpdate")
    public R<StorePlatformBathFacility> saveOrUpdate(@RequestBody StorePlatformBathFacility facility) {
        log.info("StorePlatformBathFacilityServiceController.saveOrUpdate facility={}", facility);
        return facilityService.saveOrUpdateFacility(facility);
    }

    @ApiOperation("删除设施")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设施ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/delete")
    public R<String> delete(@RequestParam("id") Integer id) {
        log.info("StorePlatformBathFacilityServiceController.delete id={}", id);
        return facilityService.deleteFacility(id);
    }

    @ApiOperation("批量删除设施")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "设施ID列表", dataType = "List", paramType = "query", required = true)
    })
    @GetMapping("/deleteBatch")
    public R<String> deleteBatch(@RequestParam("ids") List<Integer> ids) {
        log.info("StorePlatformBathFacilityServiceController.deleteBatch ids={}", ids);
        return facilityService.deleteFacilityBatch(ids);
    }

    @ApiOperation("Excel导入洗浴汗蒸设施")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "Excel文件", dataType = "file", paramType = "form", required = true),
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/importFacility")
    public R<String> importFacility(ExcelImportVo vo) {
        log.info("StorePlatformBathFacilityServiceController.importFacility storeId={}", vo.getStoreId());
        return facilityService.importFacilityFromExcel(vo.getFile(), vo.getStoreId());
    }

    @ApiOperation("下载洗浴汗蒸导入模板")
    @ApiOperationSupport(order = 10)
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        log.info("StorePlatformBathFacilityServiceController.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);
            }
        }
    }
}
