package cn.iocoder.yudao.module.product.controller.admin.harvestbatch;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.yudao.framework.common.enums.BlockStateEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.io.JsonFileUtils;
import cn.iocoder.yudao.framework.common.util.string.StrUtils;
import cn.iocoder.yudao.module.product.controller.admin.harvestbatch.vo.*;
import cn.iocoder.yudao.module.product.convert.harvestbatch.HarvestBatchConvert;
import cn.iocoder.yudao.module.product.dal.dataobject.harvestbatch.HarvestBatchDO;
import cn.iocoder.yudao.module.product.service.harvestbatch.HarvestBatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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 javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Api(tags = "管理后台 - 采收批次")
@RestController
@RequestMapping("/product/harvest-batch")
@Validated
public class HarvestBatchController {

    @Resource
    private HarvestBatchService harvestBatchService;

    @DeleteMapping("/delete")
    @ApiOperation("删除采收批次")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:delete')")
    public CommonResult<Boolean> deleteHarvestBatch(@RequestParam("id") Long id) {
        harvestBatchService.deleteHarvestBatch(id);
        return CommonResult.success(Boolean.TRUE);
    }

    @DeleteMapping("/deleteBatch")
    @ApiOperation("批量删除采收批次")
    @ApiImplicitParam(name = "ids", value = "ID列表", required = true, dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:delete')")
    public CommonResult<Boolean> deleteBatch(@RequestParam("ids") List<Long> ids) {
        harvestBatchService.deleteBatch(ids);
        return CommonResult.success(Boolean.TRUE);
    }

    @GetMapping("/get")
    @ApiOperation("获得采收批次")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<HarvestBatchRespVO> getHarvestBatch(@RequestParam("id") Long id) {
        return CommonResult.success(harvestBatchService.getHarvestBatchDetail(id));
    }

    @GetMapping("/getAllBatchCode")
    @ApiOperation("获得采收批次")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<List<String>> getAllBatchCode() {
        return CommonResult.success(harvestBatchService.getAllBatchCode());
    }

    @GetMapping("/getHarvestBatchByHarvesId")
    @ApiOperation("根据采收批次编号获取采收批次")
    @ApiImplicitParam(name = "harvestBatchId", value = "批次编号", required = true, example = "HABTBC20230424165426A32RGFEY", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<HarvestBatchDO> getHarvestBatchByHarvesId(@RequestParam("harvestBatchId")String harvestBatchId) {
        HarvestBatchDO harves = harvestBatchService.getHarvestBatchByHarvesId(harvestBatchId);
        return CommonResult.success(harves);
    }

    @GetMapping("/page")
    @ApiOperation("获得采收批次分页")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<PageResult<HarvestBatchRespVO>> getHarvestBatchPage(@Valid HarvestBatchPageReqVO pageVO) {
        PageResult<HarvestBatchDO> pageResult = harvestBatchService.getHarvestBatchPage(pageVO);
        return CommonResult.success(HarvestBatchConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/getHarverstBatchIdList")
    @ApiOperation("获得采收批次编号列表")
    @ApiImplicitParam(name = "count", value = "数量", required = true, example = "1", dataTypeClass = Integer.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<List<String>> getHarverstBatchIdList(@RequestParam("count") @NotNull Integer count) {
        return CommonResult.success(harvestBatchService.getHarverstBatchIdList(count));
    }


    @GetMapping("/getGoodsConfig")
    @ApiOperation("获得商品信息配置 - 溯源环节相关")
    @ApiImplicitParam(name = "id", value = "采收批次ID", required = true, example = "1", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<GoodsConfigRespVO> getGoodsConfig(@RequestParam("id") @NotNull Long id) {
        return CommonResult.success(harvestBatchService.getGoodsConfig(id));
    }

    @PostMapping("/createGoodsConfig")
    @ApiOperation("创建商品信息配置 - 溯源环节相关")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:create')")
    public CommonResult<Boolean> createGoodsConfig(@Valid @RequestBody GoodsConfigSaveReqVO createReqVO) {
        return CommonResult.success(harvestBatchService.createGoodsConfig(createReqVO));
    }

    @PutMapping("/updateGoodsConfig")
    @ApiOperation("更新商品信息配置 - 溯源环节相关")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:update')")
    public CommonResult<Boolean> updateGoodsConfig(@Valid @RequestBody GoodsConfigSaveReqVO updateReqVO) {
        harvestBatchService.updateGoodsConfig(updateReqVO);
        return CommonResult.success(Boolean.TRUE);
    }

    @GetMapping("/getLinkConfig")
    @ApiOperation("获得环节信息配置 - 溯源环节相关")
    @ApiImplicitParam(name = "id", value = "采收批次ID", required = true, example = "1", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<LinkConfigRespVO> getLinkConfig(@RequestParam("id") @NotNull Long id) {
        return CommonResult.success(harvestBatchService.getLinkConfig(id));
    }

    @PutMapping("/updateLinkConfig")
    @ApiOperation("更新环节信息配置 - 溯源环节相关")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:update')")
    public CommonResult<Boolean> updateLinkConfig(@Valid @RequestBody LinkConfigSaveReqVO updateReqVO) {
        harvestBatchService.updateLinkConfig(updateReqVO);
        return CommonResult.success(Boolean.TRUE);
    }

    @GetMapping("/getHarvestBatchByBusinessId")
    @ApiOperation("根据商户ID查询已上链的批次集合")
    @ApiImplicitParam(name = "businessInfoId", value = "商户ID", required = true, example = "1", dataTypeClass = Long.class)
    public CommonResult<List<HarvestBatchRespVO>> getHarvestBatchByBusinessId(@RequestParam("businessId") String businessId) {
        List<HarvestBatchDO> harvestBatchDOS = harvestBatchService.getHarvestBatchByBusinessId(businessId, BlockStateEnum.ACTIVATION.getBlockState());
        return CommonResult.success(HarvestBatchConvert.INSTANCE.convertList(harvestBatchDOS));
    }

    @GetMapping("/getFarmingConfig")
    @ApiOperation("获得农事活动配置 - 溯源环节相关")
    @ApiImplicitParam(name = "id", value = "采收批次ID", required = true, example = "1", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<FarmingConfigRespVO> getFarmingConfig(@RequestParam("id") @NotNull Long id) {
        return CommonResult.success(harvestBatchService.getFarmingConfig(id));
    }

    @PutMapping("/updateFarmingConfig")
    @ApiOperation("更新农事活动配置 - 溯源环节相关")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:update')")
    public CommonResult<Boolean> updateFarmingConfig(@Valid @RequestBody FarmingConfigSaveReqVO updateReqVO) {
        harvestBatchService.updateFarmingConfig(updateReqVO);
        return CommonResult.success(Boolean.TRUE);
    }

    @PostMapping("/importLinkConfig")
    @ApiOperation("导入环节配置")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:update')")
    public CommonResult<List<LinkFileVO>> importLinkConfig(@RequestParam("file") MultipartFile file) {
        List<LinkFileVO> linkFiles = JsonFileUtils.readJsonAndConvertToList(file, LinkFileVO.class);
        return CommonResult.success(linkFiles);
    }

    @GetMapping("/exportLinkConfig")
    @ApiOperation("导出环节配置")
    @ApiImplicitParam(name = "id", value = "采收批次ID", required = true, example = "1", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public void exportLinkConfig(@RequestParam("id") @NotNull Long id, HttpServletResponse response) {
        // 根据批次id获得环节配置信息
        LinkConfigRespVO linkConfig = harvestBatchService.getLinkConfig(id);
        List<LinkFileVO> linkFiles = linkConfig.getLinks().stream().map(link -> {
            LinkFileVO linkFile = new LinkFileVO();
            BeanUtil.copyProperties(link, linkFile);
            List<LinkItemFileVO> linkFileItems = link.getOperateDetails().stream().map(detail -> {
                LinkItemFileVO LinkItemFile = new LinkItemFileVO();
                BeanUtil.copyProperties(detail, LinkItemFile);
                return LinkItemFile;
            }).collect(Collectors.toList());
            linkFile.setOperateDetails(linkFileItems);
            return linkFile;
        }).collect(Collectors.toList());
        // 导出到前端
        JsonFileUtils.writeJsonFile(response, linkFiles, StrUtils.getRandomUpperString(10));
    }

    @GetMapping("/getBatchIdsByGoodsId")
    @ApiOperation("根据商品编码集合获取批次编码")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "goodsIds", value = "商品编号集合", required = true, example = "GOCD202304131028TSOC,GOCD202304131724XUXY", dataTypeClass = List.class),
        @ApiImplicitParam(name = "businessId", value = "商户ID", required = true, example = "1", dataTypeClass = Long.class)
    })
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<Map<String, List<String>>> getBatchIdsByGoodsId(@RequestParam("goodsIds") List<String> goodsIds, @RequestParam("businessId") Long businessId) {
        // 正常来说只要商品编码列表即可， 这边为了严谨，多加了个商户id进行过滤
        return CommonResult.success(harvestBatchService.getBatchIdsByGoodsId(goodsIds, businessId, null));
    }

    @GetMapping("/preview")
    @ApiOperation("获取小程序显示的预览数据")
    @ApiImplicitParam(name = "harvestBatchId", value = "批次编码", required = true, example = "HABTBC20230523105238FFGHG94N", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<PreviewRespVO> getPreviewData(@RequestParam("harvestBatchId") String harvestBatchId, @RequestParam("languageTypeId") Long languageTypeId) {
        return CommonResult.success(harvestBatchService.getPreviewData(harvestBatchId, languageTypeId));
    }

    @GetMapping("/getHarvestBatchById")
    @ApiOperation("根据采收批次ID获取采收批次信息")
    @ApiImplicitParam(name = "harvestBatchId", value = "采收批次编码", required = true, example = "1", dataTypeClass = Integer.class)
    public CommonResult<HarvestBatchDO> getHarvestBatchById(@RequestParam("harvestBatchId") String harvestBatchId) {
        return CommonResult.success(harvestBatchService.getHarvestBatchById(harvestBatchId));
    }

    @PutMapping("/freeze")
    @ApiOperation("冻结")
    @ApiImplicitParam(name = "id", value = "ID", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:freeze')")
    public CommonResult<Boolean> freeze(@RequestParam("id") Long id) {
        harvestBatchService.updateChainStatus(id, BlockStateEnum.FREEZE.getBlockState());
        return success(Boolean.TRUE);
    }

    @PutMapping("/active")
    @ApiOperation("激活")
    @ApiImplicitParam(name = "id", value = "ID", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:active')")
    public CommonResult<Boolean> active(@RequestParam("id") Long id) {
        harvestBatchService.updateChainStatus(id, BlockStateEnum.ACTIVATION.getBlockState());
        return success(Boolean.TRUE);
    }

    @GetMapping("/getHarvestBatchConfig")
    @ApiOperation("获得采收批次扫码信息配置")
    @ApiImplicitParam(name = "id", value = "采收批次ID", required = true, example = "1", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:query')")
    public CommonResult<HarvestBatchConfigRespVO> getHarvestBatchConfig(@RequestParam("id") @NotNull Long id, @RequestParam("languageTypeId") @NotNull Long languageTypeId) {
        return CommonResult.success(harvestBatchService.getHarvestBatchConfig(id, languageTypeId));
    }

    @PutMapping("/updateHarvestBatchConfig")
    @ApiOperation("更新采收批次配置")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:update')")
    public CommonResult<Boolean> updateHarvestBatchConfig(@Valid @RequestBody HarvestBatchConfigSaveReqVO updateReqVO) {
        harvestBatchService.updateHarvestBatchConfig(updateReqVO);
        return CommonResult.success(Boolean.TRUE);
    }

    @PostMapping("/initHarvestBatchConfig")
    @ApiOperation("初始化采收批次配置")
    @PreAuthorize("@ss.hasPermission('product:harvest-batch:init-config')")
    public CommonResult<Boolean> initHarvestBatchConfig() {
        harvestBatchService.initHarvestBatchConfig();
        return CommonResult.success(Boolean.TRUE);
    }

}
