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

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.bonus.canteen.core.common.export.api.ExportApi;
import com.bonus.canteen.core.common.page.PageVO;
import com.bonus.canteen.core.common.redis.RedisUtil;
import com.bonus.canteen.core.common.utils.TenantContextHolder;
import com.bonus.canteen.core.menu.dto.*;
import com.bonus.canteen.core.menu.service.MenuDishesService;
import com.bonus.canteen.core.menu.vo.MenuAllTypeDishesVO;
import com.bonus.canteen.core.menu.vo.MenuDishesDetailVO;
import com.bonus.canteen.core.menu.vo.MenuDishesExportVO;
import com.bonus.canteen.core.secure.filter.annotation.RequiresAuthentication;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.encrypt.RequiresGuest;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping({"/api/v2/menudishes"})
@Api(
   value = "menudishesv2",
   tags = {"pfy_菜品信息管理v2"}
)
public class MenuDishesV2Controller {
   private static final Logger log = LoggerFactory.getLogger(MenuDishesV2Controller.class);
   @Resource
   private MenuDishesService menuDishesService;
   @Resource
   protected ExportApi exportApi;

   @PostMapping({"/add"})
   @RequiresAuthentication
   @ApiOperation("新增菜品信息v2")
   @RequiresPermissions(
      value = {"recipe:menu:add"},
      logical = Logical.OR
   )
   public AjaxResult addMenuDishesV2(@RequestBody @Valid MenuDishesV2AddDTO dto) {
      return AjaxResult.success(this.menuDishesService.addMenuDishesV2(dto));
   }

   @RequiresAuthentication
   @PostMapping({"/page"})
   @ApiOperation("菜品分页信息V2")
   @RequiresPermissions(
      value = {"recipe:menu:query"},
      logical = Logical.OR
   )
   public AjaxResult getMenuDishesV2Page(@RequestBody MenuDishesV2PageDTO dto) {
      return AjaxResult.success(this.menuDishesService.getMenuDishesV2Page(dto));
   }

   @PostMapping({"/detail/{dishesId}"})
   @ApiOperation("获取指定菜品详情v2")
   public MenuDishesDetailVO getMenuDishesDetail(@PathVariable Long dishesId) {
      return this.menuDishesService.getMenuDishesDetail(dishesId);
   }

   @PostMapping({"/edit"})
   @RequiresAuthentication
   @ApiOperation("修改菜品信息v2")
   @RequiresPermissions(
      value = {"recipe:menu:edit"},
      logical = Logical.OR
   )
   public AjaxResult editMenuDishesV2(@RequestBody @Valid MenuDishesV2EditDTO dto) {
      this.menuDishesService.editMenuDishesV2(dto);
      return AjaxResult.success();
   }

   @ApiOperation("删除菜品信息")
   @PostMapping({"/remove/{dishesId}"})
   @RequiresPermissions(
      value = {"recipe:menu:remove"},
      logical = Logical.OR
   )
   @RequiresGuest
   public AjaxResult removeByDishesIdV2(@PathVariable Long dishesId) {
      this.menuDishesService.removeByDishesIdV2(dishesId);
      return AjaxResult.success();
   }

   @PostMapping({"/copy"})
   @ApiOperation("复制菜品信息")
   public AjaxResult copyMenuDishes(@RequestBody @Valid MenuDishesCopyDTO dto) {
      this.menuDishesService.copyMenuDishes(dto);
      return AjaxResult.success();
   }

   @RequiresAuthentication
   @PostMapping({"/type/dishes/list"})
   @ApiOperation("获取类别分类菜品")
   public List<MenuAllTypeDishesVO> getTypeDishesList(@RequestBody @Valid MenuTypeDishesDTO dto) {
      return this.menuDishesService.getTypeDishesList(dto);
   }

   @RequiresAuthentication
   @PostMapping({"/type/dishes/list/page"})
   @ApiOperation("获取类别分类菜品（分页版）")
   public AjaxResult getTypeDishesListByPage(@RequestBody @Valid MenuTypeDishesDTO dto) {
      return AjaxResult.success(this.menuDishesService.getTypeDishesListByPage(dto));
   }

   @PostMapping({"/get/dif-canteen-manage"})
   @ApiOperation("获取按食堂管理配置信息")
   public AjaxResult getDifCanteenManage() {
      return AjaxResult.success(this.menuDishesService.getDifCanteenManage());
   }

   @PostMapping({"/edit/dif-canteen-manage"})
   @ApiOperation("开启或关闭按食堂管理配置信息")
   public AjaxResult editDifCanteenManage(@RequestBody @Valid MenuDifCanteenManageEditDTO dto) {
      this.menuDishesService.editDifCanteenManage(dto);
      return AjaxResult.success();
   }

   @PostMapping({"/import/check"})
   @ApiOperation("导入之前检查数据是否可以导入")
   public AjaxResult importDishesCheck(@RequestParam("file") MultipartFile excel) {
      return AjaxResult.success(this.menuDishesService.importDishesCheck(excel));
   }

   @PostMapping({"/import/dishes"})
   @ApiOperation("导入成功的菜品信息")
   public AjaxResult importDishes(@RequestBody List<MenuDishesImportDTO> request) {
      return AjaxResult.success(this.menuDishesService.newImportDishes(request));
   }

   @ApiOperation("查询导入菜品结果")
   @GetMapping({"/import/result"})
   public AjaxResult batchImportSubResult() {
      String resultRedisKey = "yst:merchant-id:dishes:upgrade:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
      String result = RedisUtil.getString(resultRedisKey);
      if (CharSequenceUtil.isNotBlank(result)) {
         RedisUtil.delete(resultRedisKey);
         return AjaxResult.success((DishesImportCheckResult)JSONUtil.toBean(result, DishesImportCheckResult.class));
      } else {
         return AjaxResult.success();
      }
   }

   @PostMapping({"/material-cost"})
   @ApiOperation("获取原料成本")
   public Integer getDishesMaterialCost(@RequestBody @Valid List<MenuMaterialCostDTO> dto) {
      return this.menuDishesService.getDishesMaterialCost(dto);
   }

   @ApiOperation("更新所有菜品成本信息")
   @PostMapping({"/material-cost/auto-update"})
   public AjaxResult autoUpdateDishesMaterialCost() {
      this.menuDishesService.autoUpdateDishesMaterialCost();
      return AjaxResult.success();
   }

   @PostMapping({"/flow/export"})
   public AjaxResult exportMenuDishes(@RequestBody MenuDishesExportDTO dto, HttpServletResponse response) {
      this.exportApi.startExcelExportTaskByPage("菜品_套餐详情", "详情", MenuDishesExportVO.class, dto.getExportCols(),
              dto, null, () -> {
         return PageVO.of(this.menuDishesService.exportMenuDishes(dto));
      });
      return AjaxResult.success();
   }

   @ApiOperation("批量上传菜品照片")
   @PostMapping({"/upload/batch/dishes/pic"})
   public AjaxResult uploadBatchDishes(MultipartFile[] files) {
      return AjaxResult.success(this.menuDishesService.uploadBatchDishes(files));
   }

   @ApiOperation("查询导入菜品结果")
   @GetMapping({"/upload/batch/dishes/pic/result"})
   public AjaxResult batchPicResult() {
      String resultRedisKey = "yst:merchant-id:dishes:pic:batch:result".replace("merchant-id", TenantContextHolder.getTenantId().toString());
      String result = RedisUtil.getString(resultRedisKey);
      if (CharSequenceUtil.isNotBlank(result)) {
         RedisUtil.delete(resultRedisKey);
         return AjaxResult.success(JSONArray.parseArray(result, UploadDishesPicResult.class));
      } else {
         return AjaxResult.success();
      }
   }

   @ApiOperation("替换指定菜品原料并更新营养数据")
   @PostMapping({"/replace/material/dishes"})
   public AjaxResult replaceMaterialDishes(@RequestBody ReplaceMaterialDto dto) {
      this.menuDishesService.replaceMaterialDishes(dto);
      return AjaxResult.success();
   }
}
