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.entity.store.StoreMenu;
import shop.alien.entity.store.vo.StoreMenuVo;
import shop.alien.storeplatform.service.StoreMenuPlatformService;
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 ssk
 * @since 2024-12-05
 */
@Slf4j
@Api(tags = {"商家端-门店菜单"})
@ApiSort(4)
@CrossOrigin
@RestController
@RequestMapping("/menuPlatform")
@RequiredArgsConstructor
public class StoreMenuPlatformController {

    private final StoreMenuPlatformService storeMenuService;

    @ApiOperation("获取门店菜单")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "dishType", value = "菜品类型, 0:菜单, 1:推荐", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "phoneId", value = "消息标识", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getMenuByStoreId")
    public R<List<StoreMenuVo>> getMenuByStoreId(Integer storeId, Integer dishType, String phoneId) {
        log.info("StoreMenuController.getByStoreId?id={}&dishType={}&phoneId={}", storeId, dishType, phoneId);
        return R.data(storeMenuService.getStoreMenu(storeId, dishType, phoneId));
    }

    @ApiOperation("新增或修改门店菜单")
    @ApiOperationSupport(order = 2)
    @PostMapping("/saveOrUpdate")
    public R<String> saveOrUpdate(@RequestBody StoreMenuVo storeMenuVo) {
        log.info("StoreMenuController.saveOrUpdateMenu?storeMenu={}", storeMenuVo);
        return storeMenuService.saveOrUpdateMenus(storeMenuVo);
    }

    @ApiOperation(value = "删除门店菜单")
    @ApiOperationSupport(order = 3)
    @GetMapping("/delete")
    public R<String> delete(@RequestParam(value = "ids") List<Integer> ids, @RequestParam(value = "dishType") int dishType) {
        log.info("StoreMenuController.delete?ids={}", ids);
        return storeMenuService.deleteMenu(ids, dishType);
    }

    @ApiOperation("获取菜品详情")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "菜品id", dataType = "Integer", paramType = "query")})
    @GetMapping("/getMenuInfo")
    public R<StoreMenuVo> getMenuInfo(Integer id) {
        log.info("StoreMenuController.getMenuInfo?id={}", id);
        return R.data(storeMenuService.getMenuInfo(id));
    }

    @ApiOperation("菜品排序")
    @ApiOperationSupport(order = 5)
    @PostMapping("/getSortMenuInfo")
    public R<Boolean> getSortMenuInfo(@RequestBody StoreMenuVo storeMenuVo) {
        log.info("StoreMenuController.getSortMenuInfo?storeMenuVo={}", storeMenuVo);
        Boolean flag = storeMenuService.getSortMenuInfo(storeMenuVo);
        if (flag) {
            return R.success("已更新排序");
        } else {
            return R.fail("排序失败");
        }
    }

    @ApiOperation("保存菜品排序")
    @ApiOperationSupport(order = 6)
    @PostMapping("/saveMenuSort")
    public R<Boolean> saveMenuSort(@RequestBody List<StoreMenu> storeMenuList) {
        log.info("StoreMenuController.saveMenuSort?storeMenuList={}", storeMenuList);
        Boolean flag = storeMenuService.saveMenuSort(storeMenuList);
        if (flag) {
            return R.success("已更新排序");
        } else {
            return R.fail("排序失败");
        }
    }

    @ApiOperation("获取门店菜品推荐数量")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getMenuCountByStoreId")
    public R<StoreMenuVo> getMenuCountByStoreId(Integer storeId) {
        log.info("StoreMenuController.getMenuCountByStoreId?id={}", storeId);
        return R.data(storeMenuService.getMenuCountByStoreId(storeId));
    }

    @ApiOperation("获取用户对该菜品是否点赞")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "menuId", value = "菜品id", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getMenuLikeStatus")
    public R<Boolean> getMenuLikeStatus(String userId, Integer menuId) {
        log.info("StoreMenuController.getMenuLikeStatus?userId={}&menuId={}", userId, menuId);
        return R.data(storeMenuService.getMenuLikeStatus(userId, menuId));
    }

    @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("StoreMenuPlatformController.importMenu?storeId={}", vo.getStoreId());
        return storeMenuService.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);
            }
        }
    }
}


