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.StorePlatformStoreMenu;
import shop.alien.storeplatform.service.StorePlatformBarMenuService;
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("/barMenu")
@RequiredArgsConstructor
public class StorePlatformBarMenuController {

    private final StorePlatformBarMenuService barMenuService;

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

    @ApiOperation("根据门店ID查询菜单列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getListByStoreId")
    public R<List<StorePlatformStoreMenu>> getListByStoreId(@RequestParam("storeId") Integer storeId) {
        log.info("StorePlatformBarMenuController.getListByStoreId storeId={}", storeId);
        List<StorePlatformStoreMenu> list = barMenuService.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 = "dishMenuType", value = "菜单类型：1-菜单，2-酒水", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dishType", value = "是否推荐, 0:非推荐, 1:推荐", dataType = "String", paramType = "query")
    })
    @GetMapping("/getListByStoreIdAndType")
    public R<List<StorePlatformStoreMenu>> getListByStoreIdAndType(
            @RequestParam("storeId") Integer storeId,
            @RequestParam(value = "dishMenuType", required = false) String dishMenuType,
            @RequestParam(value = "dishType", required = false) String dishType) {
        log.info("StorePlatformBarMenuController.getListByStoreIdAndType storeId={}, dishMenuType={}, dishType={}", storeId, dishMenuType, dishType);
        List<StorePlatformStoreMenu> list = barMenuService.getListByStoreIdAndType(storeId, dishMenuType, dishType);
        return R.data(list);
    }

    @ApiOperation("新增菜单")
    @ApiOperationSupport(order = 4)
    @PostMapping("/save")
    public R<StorePlatformStoreMenu> save(@RequestBody StorePlatformStoreMenu storeMenu) {
        log.info("StorePlatformBarMenuController.save storeMenu={}", storeMenu);
        return barMenuService.saveMenu(storeMenu);
    }

    @ApiOperation("修改菜单")
    @ApiOperationSupport(order = 5)
    @PostMapping("/update")
    public R<StorePlatformStoreMenu> update(@RequestBody StorePlatformStoreMenu storeMenu) {
        log.info("StorePlatformBarMenuController.update storeMenu={}", storeMenu);
        return barMenuService.updateMenu(storeMenu);
    }

    @ApiOperation("新增或修改菜单")
    @ApiOperationSupport(order = 6)
    @PostMapping("/saveOrUpdate")
    public R<StorePlatformStoreMenu> saveOrUpdate(@RequestBody StorePlatformStoreMenu storeMenu) {
        log.info("StorePlatformBarMenuController.saveOrUpdate storeMenu={}", storeMenu);
        return barMenuService.saveOrUpdateMenu(storeMenu);
    }

    @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("StorePlatformBarMenuController.delete id={}", id);
        return barMenuService.deleteMenu(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("StorePlatformBarMenuController.deleteBatch ids={}", ids);
        return barMenuService.deleteMenuBatch(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("/importMenu")
    public R<String> importMenu(ExcelImportVo vo) {
        log.info("StorePlatformBarMenuController.importMenu storeId={}", vo.getStoreId());
        return barMenuService.importMenuFromExcel(vo.getFile(), vo.getStoreId());
    }

    @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);
            }
        }
    }
}
