package org.jeecg.modules.inventory.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.modules.inventory.entity.ItdmInventoryBarcode;
import org.jeecg.modules.inventory.entity.ItdmSampleInventory;
import org.jeecg.modules.inventory.service.IItdmInventoryBarcodeService;
import org.jeecg.modules.inventory.service.IItdmSampleInventoryService;
import org.jeecg.modules.inventory.util.BarcodeUtils;
import org.jeecg.modules.inventory.vo.BarcodeXialaListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 库存条码
 * @Author: jeecg-boot
 * @Date: 2023-06-26
 * @Version: V1.0
 */
@Api(tags = "库存条码")
@RestController
@RequestMapping("/inventory/itdmInventoryBarcode")
@Slf4j
public class ItdmInventoryBarcodeController extends JeecgController<ItdmInventoryBarcode, IItdmInventoryBarcodeService> {
    @Autowired
    private IItdmInventoryBarcodeService itdmInventoryBarcodeService;
    @Autowired
    private IItdmSampleInventoryService itdmSampleInventoryService;

    @Resource
    JeecgBaseConfig jeecgBaseConfig;

    /**
     * 条码下拉列表
     */
    @ApiOperation(value = "条码下拉列表", notes = "条码下拉列表")
    @GetMapping(value = "/xialaList")
    public Result<List<BarcodeXialaListVO>> xialaList() {
        List<BarcodeXialaListVO> xialaList = itdmInventoryBarcodeService.rukuBarcodeList();
        return Result.OK(xialaList);
    }


    /**
     * 分页列表查询
     *
     * @param itdmInventoryBarcode
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "库存条码-分页列表查询")
    @ApiOperation(value = "库存条码-分页列表查询", notes = "库存条码-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ItdmInventoryBarcode>> queryPageList(ItdmInventoryBarcode itdmInventoryBarcode,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        QueryWrapper<ItdmInventoryBarcode> queryWrapper = QueryGenerator.initQueryWrapper(itdmInventoryBarcode, req.getParameterMap());
        Page<ItdmInventoryBarcode> page = new Page<ItdmInventoryBarcode>(pageNo, pageSize);
        IPage<ItdmInventoryBarcode> pageList = itdmInventoryBarcodeService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param itdmInventoryBarcode
     * @return
     */
    @AutoLog(value = "库存条码-添加")
    @ApiOperation(value = "库存条码-添加", notes = "库存条码-添加")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_barcode:add")
    @PostMapping(value = "/add")
    @Transactional
    public Result<String> add(@RequestBody ItdmInventoryBarcode itdmInventoryBarcode) throws IOException {
        ItdmSampleInventory itdmSampleInventory = itdmSampleInventoryService.getById(itdmInventoryBarcode.getInventoryId());

        ItdmInventoryBarcode itdmInventoryBarcodeServiceOne = itdmInventoryBarcodeService.getOne(Wrappers.lambdaQuery(ItdmInventoryBarcode.class)
                .eq(ItdmInventoryBarcode::getInventoryId, itdmInventoryBarcode.getInventoryId()).orderByDesc(ItdmInventoryBarcode::getId).last("limit 1"));


        if (itdmInventoryBarcodeServiceOne == null) {
            itdmInventoryBarcode.setBarCode(itdmSampleInventory.getBatchNumber() + String.format("%04d", 1));

        } else {
            int start = itdmInventoryBarcodeServiceOne.getBarCode().length() - 4;

            int end = itdmInventoryBarcodeServiceOne.getBarCode().length();

            Integer l = Integer.valueOf(itdmInventoryBarcodeServiceOne.getBarCode().substring(start, end));

            itdmInventoryBarcode.setBarCode(itdmSampleInventory.getBatchNumber() + String.format("%04d", l + 1));

        }

        String fileName = "bracode" + File.separator + System.currentTimeMillis() + ".jpg";
        String filePath = jeecgBaseConfig.getPath().getUpload() + File.separator + fileName;
        FileUtil.touch(filePath);

        BufferedImage image = BarcodeUtils.insertWords(BarcodeUtils.getBarCode(itdmInventoryBarcode.getBarCode()), itdmInventoryBarcode.getBarCode());


        if (image == null) {
            throw new JeecgBootException("条码生成失败");
        }
        ImageIO.write(image, "jpg", new File(filePath));


        itdmInventoryBarcode.setImgPath(fileName);
        itdmInventoryBarcode.setDisableStatus("0");
        itdmInventoryBarcode.setUseStatus("0");
        itdmInventoryBarcode.setNum("1");
        itdmInventoryBarcodeService.save(itdmInventoryBarcode);
        return Result.OK("添加成功！");
    }


    /**
     * 编辑
     *
     * @param itdmInventoryBarcode
     * @return
     */
    @AutoLog(value = "库存条码-编辑")
    @ApiOperation(value = "库存条码-编辑", notes = "库存条码-编辑")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_barcode:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ItdmInventoryBarcode itdmInventoryBarcode) {
        itdmInventoryBarcodeService.updateById(itdmInventoryBarcode);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "库存条码-通过id删除")
    @ApiOperation(value = "库存条码-通过id删除", notes = "库存条码-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_barcode:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {


        itdmInventoryBarcodeService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "库存条码-批量删除")
    @ApiOperation(value = "库存条码-批量删除", notes = "库存条码-批量删除")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_barcode:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.itdmInventoryBarcodeService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "库存条码-通过id查询")
    @ApiOperation(value = "库存条码-通过id查询", notes = "库存条码-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ItdmInventoryBarcode> queryById(@RequestParam(name = "id", required = true) String id) {
        ItdmInventoryBarcode itdmInventoryBarcode = itdmInventoryBarcodeService.getById(id);
        if (itdmInventoryBarcode == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(itdmInventoryBarcode);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param itdmInventoryBarcode
     */
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_barcode:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ItdmInventoryBarcode itdmInventoryBarcode) {
        return super.exportXls(request, itdmInventoryBarcode, ItdmInventoryBarcode.class, "库存条码");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("itdm_inventory_barcode:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ItdmInventoryBarcode.class);
    }

}
