package com.bonus.canteen.core.menu.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bonus.canteen.core.common.utils.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.menu.dto.*;
import com.bonus.canteen.core.menu.service.IMenuRecipeService;
import com.bonus.canteen.core.menu.vo.AllocRecipeStallVO;
import com.bonus.canteen.core.menu.vo.MenuDishesTypeAllVO;
import com.bonus.canteen.core.menu.vo.MenuRecipeVO;
import com.bonus.canteen.core.menu.vo.MenuRecipeDetailDateVO;
import com.bonus.canteen.core.menu.vo.*;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.GlobalConstants;
import com.bonus.common.houqin.encrypt.RequiresGuest;
import com.bonus.common.houqin.i18n.I18n;
import com.bonus.common.houqin.utils.HeaderFetchUtil;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.Logical;
import com.bonus.common.security.annotation.RequiresPermissions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.canteen.core.menu.domain.MenuRecipe;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.utils.poi.ExcelUtil;
import com.bonus.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 菜品计划信息Controller
 *
 * @author xsheng
 * @date 2025-04-03
 */
@Api(tags = "菜品计划信息接口")
@RestController
@RequestMapping("/menu_recipe")
public class MenuRecipeController extends BaseController {
    @Autowired
    private IMenuRecipeService menuRecipeService;

    /**
     * 查询菜品计划信息列表
     */
//    @ApiOperation(value = "查询菜品计划信息列表")
//    //@RequiresPermissions("menu:recipe:list")
//    @GetMapping("/list")
//    public TableDataInfo list(MenuRecipe menuRecipe) {
//        startPage();
//        List<MenuRecipeVO> list = menuRecipeService.selectMenuRecipeList(menuRecipe);
//        return getDataTable(list);
//    }

    @ApiOperation(value = "查询菜品计划信息列表")
    //@RequiresPermissions("menu:recipe:list")
    @GetMapping("/list")
    public TableDataInfo list(AllocRecipeStallDTO dto) {
        startPage();
        List<AllocRecipeStallVO> list = menuRecipeService.selectMenuRecipeListV2(dto);
        return getDataTable(list);
    }

    @PostMapping({"/getDishesList"})
    @ApiOperation("菜谱列表-获取菜品列表")
    public AjaxResult getDishesList(@RequestBody MenuRecipeParamDTO dto) {
        return this.menuRecipeService.getDishesList(dto);

    }
    /**
     * 导出菜品计划信息列表
     */
    @ApiOperation(value = "导出菜品计划信息列表")
    //@PreventRepeatSubmit
    //@RequiresPermissions("menu:recipe:export")
    @SysLog(title = "菜品计划信息", businessType = OperaType.EXPORT, logType = 1,module = "仓储管理->导出菜品计划信息")
    @PostMapping("/export")
    public void export(HttpServletResponse response, MenuRecipe menuRecipe) {
//        List<MenuRecipe> list = menuRecipeService.selectMenuRecipeList(menuRecipe);
//        ExcelUtil<MenuRecipe> util = new ExcelUtil<MenuRecipe>(MenuRecipe.class);
//        util.exportExcel(response, list, "菜品计划信息数据");

    }

    @PostMapping({"/add"})
    @ApiOperation("菜谱计划发布v2")
    public Long addMenuRecipeV2(@RequestBody @Valid MenuRecipeAddDTO dto) {
        Long recipeId = null;
        String var10000 = "yst:merchant-id:menu:recipe:edit:".replace("merchant-id", String.valueOf(GlobalConstants.TENANT_ID));
        String lockKey = var10000 + dto.getRecipeId();
        boolean succ = RedisUtil.tryLock(lockKey, 0, 300);
        if (!succ) {
            throw new ServiceException("获取锁失败，停止新增！");
        } else {
            try {
                recipeId = this.menuRecipeService.add(dto);
            } finally {
                RedisUtil.safeUnLock(lockKey);
            }

            return recipeId;
        }
    }

    @PostMapping({"/detail"})
    @ApiOperation("获取菜谱计划-菜谱详情")
    public List<MenuRecipeDetailDateVO> getDetail(@RequestBody MenuRecipeParamDTO dto) {
        return this.menuRecipeService.getDetail(dto);
    }

    @ApiOperation("删除菜品计划")
    @PostMapping({"/deleteRecipeById"})
    public AjaxResult deleteMenuById(@RequestBody MenuRecipeParamDTO dto) {
        this.menuRecipeService.deleteRecipeById(dto.getRecipeId());
        return AjaxResult.success();
    }
    /**
     * 删除菜品计划信息
     */
    @ApiOperation(value = "删除菜品计划信息")
    //@PreventRepeatSubmit
    //@RequiresPermissions("menu:recipe:remove")
    @SysLog(title = "菜品计划信息", businessType = OperaType.DELETE, logType = 1,module = "仓储管理->删除菜品计划信息")
	@PostMapping("/del/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(menuRecipeService.deleteMenuRecipeByIds(ids));
    }



    @ApiOperation(value = "删除菜品计划信息")
    @SysLog(title = "菜品计划信息", businessType = OperaType.DELETE, logType = 1,module = "仓储管理->删除菜品计划信息")
    @PostMapping("/app/bind")
    public AjaxResult bindAppRecipe(@RequestBody @Valid MenuRecipeBindDTO dto) {
        this.menuRecipeService.bindAppRecipe(dto);
        return AjaxResult.success();
    }


    @PostMapping({"getDishesCategoryList"})
    @ApiOperation("获取类别分类菜品")
    public AjaxResult getDishesCategoryList(@RequestBody @Valid MenuTypeDishesDTO dto) {
        return AjaxResult.success(this.menuRecipeService.getDishesCategoryList(dto));
    }

    @PostMapping({"getAllDishCategories"})
    @ApiOperation("获取所有菜品类别")
    public AjaxResult getAllDishCategories() {
        List<MenuDishesTypeAllVO> resultList = this.menuRecipeService.getAllDishCategories();
        return AjaxResult.success(resultList);
    }

    @PostMapping({"/getDetailByDate"})
    @ApiOperation("获取指定日期菜谱计划菜品详情")
    public List<MenuRecipeDetailDateVO> getDetailByDate(@RequestBody MenuRecipeParamDTO dto) {
        return this.menuRecipeService.getDetailByDate(dto);
    }


    @PostMapping({"/getMenuInfoBySn"})
    @ApiOperation("根据sn获取菜谱菜品信息")
    public IssueRecipeCompressVO getMenuInfoBySn(@RequestHeader Map<String, String> headers) {
        String machineSn = HeaderFetchUtil.getMachineSn(headers);
        if (machineSn == null){
            throw new ServiceException("设备sn为空");
        }
        return this.menuRecipeService.getMenuInfoBySn(machineSn);
    }

    @PostMapping({"/getMealTimeBySn"})
    @ApiOperation("根据sn码获餐次信息")
    public DviceTimeIntervalVO intervalConfig(@RequestHeader Map<String, String> headers) {
        return this.menuRecipeService.intervalConfig(HeaderFetchUtil.getMachineSn(headers));
    }


    @PostMapping({"/recipe/import/dishes"})
    @ApiOperation("批量导入菜谱中的菜品信息")
    @Transactional
    public AjaxResult recipeImportDishes(@RequestParam("file") MultipartFile excel, @RequestParam("recipeId") Long recipeId) {
        try{
            return ObjectUtil.isNull(excel) ? AjaxResult.error("请选择导入文件 ^_^") :
                    AjaxResult.success(this.menuRecipeService.recipeImportDishes(excel, recipeId));
        }catch (Exception e){
            throw new ServiceException(e.toString());
        }
    }

    @PostMapping({"/generateRecipe"})
    @ApiOperation("定时任务")
    @Transactional
    public AjaxResult generateRecipe() {
        this.menuRecipeService.generateRecipe();
         return AjaxResult.success();
    }

//    @PostMapping({"/page"})
//    @ApiOperation("菜谱计划发布记录分页列表")
//    public Page<MenuRecipeV2PageVO> getMenuRecipeV2Page(@RequestBody MenuRecipeV2PageDTO dto) {
//        return this.menuRecipeService.getMenuRecipeV2Page(dto);
//    }
//
//    @PostMapping({"/template/detail"})
//    @ApiOperation("获取指定菜谱模版详情")
//    public List<MenuRecipeDetailDateVO> queryRecipeTemplateDate(@RequestBody QueryRecipeTemplateDateDTO dto) {
//        return this.menuRecipeService.queryRecipeTemplateDate(dto);
//    }
//
//
//    @PostMapping({"/date/detail"})
//    @ApiOperation("获取指定日期菜谱计划菜品详情")
//    public List<MenuRecipeDetailDateVO> getMenuRecipeDateDetail(@RequestBody MenuRecipeDetailDateDTO dto) {
//        return this.menuRecipeService.getMenuRecipeDateDetail(dto);
//    }

}
