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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
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.constant.MaterialTypeEnum;
import com.bonus.canteen.core.menu.dto.*;
import com.bonus.canteen.core.menu.entity.MenuMaterialRegisterPic;
import com.bonus.canteen.core.menu.service.MenuMaterialRegisterPicService;
import com.bonus.canteen.core.menu.service.MenuMaterialService;
import com.bonus.canteen.core.menu.vo.*;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.encrypt.RequiresGuest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
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/v1/menumaterial"})
@Api(
   value = "gyp_商家食材原料信息管理",
   tags = {"gyp_商家食材原料信息管理"}
)
public class MenuMaterialController {
   private static final Logger log = LoggerFactory.getLogger(MenuMaterialController.class);
   @Resource
   @Lazy
   private MenuMaterialService menuMaterialService;
   @Resource
   @Lazy
   private ExportApi exportApi;
   @Resource
   private MenuMaterialRegisterPicService menuMaterialRegisterPicService;

   @PostMapping({"/add"})
   @ApiOperation("新增商家原料")
   public AjaxResult addMenuMaterial(@RequestBody @Valid MenuMaterialAddDTO dto) {
      return AjaxResult.success(this.menuMaterialService.addMenuMaterial(dto));
   }

   @PostMapping({"/page"})
   @ApiOperation("分页获取商家原料信息")
   public AjaxResult getMenuMaterialPage(@RequestBody MenuMaterialPageDTO dto) {
      List<MenuMaterialPageVO> resultPage = this.menuMaterialService.getMenuMaterialPage(dto);
      return AjaxResult.success(PageVO.of(resultPage));
   }

   @GetMapping({"/{materialId}"})
   @RequiresGuest
   @ApiOperation("获取指定原料")
   public MenuMaterialVO getByMaterialId(@PathVariable("materialId") Long materialId) {
      return this.menuMaterialService.getMaterialByMaterialId(materialId);
   }

   @PostMapping({"/edit"})
   @ApiOperation("修改商家原料信息")
   public AjaxResult editMenuMaterial(@RequestBody @Valid MenuMaterialEditDTO dto) {
      this.menuMaterialService.editMenuMaterial(dto);
      return AjaxResult.success();
   }

   @PostMapping({"/getMenuMaterialNutrition"})
   @ApiOperation("获取原料营养信息")
   public AjaxResult getMenuMaterialNutrition(@RequestBody List<Long> dto) {
      return AjaxResult.success(this.menuMaterialService.getMenuMaterialNutrition(dto));
   }

   @PostMapping({"/remove/{materialId}"})
   @RequiresGuest
   @ApiOperation("删除指定商家原料信息")
   public AjaxResult removeByMaterialId(@PathVariable Long materialId) {
      this.menuMaterialService.removeByMaterialId(materialId);
      return AjaxResult.success();
   }

   @PostMapping({"/remove/batch"})
   @ApiOperation("批量删除指定商家原料信息")
   public AjaxResult removeBatchByMaterialId(@RequestBody List<Long> dto) {
      this.menuMaterialService.removeBatchByMaterialId(dto);
      return AjaxResult.success();
   }

   @PostMapping({"/lead/in/material"})
   @ApiOperation("菜品原料基础库导入")
   public AjaxResult leadInMaterial(@RequestBody MenuMaterialLeadInDTO dto) {
      this.menuMaterialService.leadInMaterial(dto);
      return AjaxResult.success();
   }

   @GetMapping({"/one/{dishesId}"})
   @RequiresGuest
   @ApiOperation("获取菜品所有原料信息")
   public AjaxResult getMenuMaterialById(@PathVariable("dishesId") Long dishesId) {
      List<MenuMaterialBasVO> menuMaterialBasVOList = this.menuMaterialService.getMenuMaterialById(dishesId);
      return AjaxResult.success(menuMaterialBasVOList);
   }

   @GetMapping({"/repair/material/category/{merchantId}"})
   @RequiresGuest
   @ApiOperation("修复现有原料类别以及原料编码(运维功能)")
   public AjaxResult repairMaterialCategory(@PathVariable("merchantId") Long merchantId) {
      TenantContextHolder.setTenantId(merchantId);
      this.menuMaterialService.repairMaterialCategory();
      return AjaxResult.success();
   }

   @ApiOperation("批量导入原料信息")
   @PostMapping({"/batch/import/material"})
   public AjaxResult batchImportMaterial(@RequestParam("file") MultipartFile excel) {
      if (ObjectUtil.isNull(excel)) {
         return AjaxResult.error("请选择导入文件 ^_^");
      } else {
         this.menuMaterialService.batchImportMaterial(excel);
         return AjaxResult.success();
      }
   }

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

   @PostMapping({"/import/dishes"})
   @ApiOperation("导入成功的原料信息")
   public AjaxResult importDishes(@RequestBody List<MaterialImportDTO> dto) {
      return AjaxResult.success(this.menuMaterialService.importMaterials(dto));
   }

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

   @ApiOperation("批量导入商品信息")
   @PostMapping({"/batch/import/material-product"})
   public AjaxResult batchImportMaterialProduct(@RequestParam("file") MultipartFile excel) {
      if (ObjectUtil.isNull(excel)) {
         return AjaxResult.error("请选择导入文件 ^_^");
      } else {
         this.menuMaterialService.batchImportMaterialProduct(excel);
         return AjaxResult.success();
      }
   }

   @ApiOperation("获取指定营养信息的详情")
   @PostMapping({"/nutrition/detail/{nutritionId}"})
   @RequiresGuest
   public AjaxResult getMenuNutritionDetailById(@PathVariable("nutritionId") Long nutritionId) {
      MenuNutritionDetailVO result = this.menuMaterialService.getMenuNutritionDetailById(nutritionId);
      return AjaxResult.success(result);
   }

   @ApiOperation("原料批量修改类别接口")
   @PostMapping({"/material/batch/update/category"})
   @RequiresGuest
   public void batchUpdateMaterialCategory(@RequestBody MaterialCategoryBatchUpdateDTO dto) {
      this.menuMaterialService.batchUpdateMaterialCategory(dto);
   }

   @ApiOperation("货品导出接口")
   @PostMapping({"/export/material"})
   @RequiresGuest
   public AjaxResult exportMaterial(@RequestBody MenuMaterialPageDTO dto, HttpServletResponse response) {
      try {

         if (ObjectUtil.equal(dto.getMaterialType(), MaterialTypeEnum.MATERIAL.key())) {
            this.exportApi.startExcelExportTaskByPage(
                    "原料", "原料", MenuMaterialExportVO.class, dto.getExportCols(), dto, null,
                    () -> PageVO.of(this.menuMaterialService.getMenuMaterialPage(dto)),
                    x -> BeanUtil.copyProperties(x, MenuMaterialExportVO.class)
            );
         } else if (ObjectUtil.equal(dto.getMaterialType(), MaterialTypeEnum.GOODS.key())) {
            this.exportApi.startExcelExportTaskByPage(
                    "商品", "商品", MenuMaterialProductExportVO.class, dto.getExportCols(), dto, null,
                    () -> PageVO.of(this.menuMaterialService.getMenuMaterialPage(dto)),
                    x -> BeanUtil.copyProperties(x, MenuMaterialProductExportVO.class)
            );
         } else {
            log.info("无此货品类别!");
         }


         return AjaxResult.success();
      } catch (Throwable var4) {
         throw var4;
      }
   }

   @ApiOperation("原料功能方法下拉列表")
   @PostMapping({"/material/function/list"})
   public List<MaterialFunctionListVO> listMaterialFunction(@RequestBody @Valid MaterialFunctionListDTO dto) {
      return this.menuMaterialService.listMaterialFunction(dto);
   }

   @ApiOperation("原料上传识别图")
   @PostMapping({"/upload"})
   public AjaxResult uploadImage(@RequestBody UploadImageDto dto) {
      this.menuMaterialRegisterPicService.saveImageByMaterialId(dto.getMaterialId(), dto.getImageUrls());
      return AjaxResult.success();
   }

   @PostMapping({"/getPic"})
   @ApiOperation("获取原料上传识别图")
   public AjaxResult upload(@RequestBody Long dto) {
      List<MenuMaterialRegisterPic> sysMenuMaterialRegisterPics = this.menuMaterialRegisterPicService.getByMaterialId(dto);
      return AjaxResult.success(BeanUtil.copyToList(sysMenuMaterialRegisterPics, MenuMaterialRegisterPicVo.class));
   }

   @PostMapping({"/removePic"})
   @ApiOperation("删除原料上传识别图")
   public AjaxResult removePic(@RequestBody Long dto) {
      this.menuMaterialRegisterPicService.removePicById(dto);
      return AjaxResult.success();
   }

   @PostMapping({"/material/disable"})
   @RequiresGuest
   @ApiOperation("原料禁用")
   public AjaxResult materialDisable(@RequestBody MenuMaterialDisableDTO dto) {
      this.menuMaterialService.materialDisable(dto);
      return AjaxResult.success();
   }

   @PostMapping({"/import/material"})
   @ApiOperation("原料导入")
   public AjaxResult importMaterialExcel(@RequestParam("file") MultipartFile excel) {
      return ObjectUtil.isNull(excel) ? AjaxResult.error("drp.select-import-file") :
              AjaxResult.success(this.menuMaterialService.importMaterialExcel(excel));
   }
}
