package org.jeecg.modules.inventory.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inventory.entity.ItdmInventoryBarcode;
import org.jeecg.modules.inventory.entity.ItdmInventoryLog;
import org.jeecg.modules.inventory.entity.ItdmSampleInventory;
import org.jeecg.modules.inventory.service.IItdmInventoryBarcodeService;
import org.jeecg.modules.inventory.service.IItdmInventoryLogService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.inventory.service.IItdmSampleInventoryService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 库存日志
 * @Author: jeecg-boot
 * @Date: 2023-06-26
 * @Version: V1.0
 */
@Api(tags = "库存日志")
@RestController
@RequestMapping("/inventory/itdmInventoryLog")
@Slf4j
public class ItdmInventoryLogController extends JeecgController<ItdmInventoryLog, IItdmInventoryLogService> {
    @Autowired
    private IItdmInventoryLogService itdmInventoryLogService;

    @Autowired
    private IItdmInventoryBarcodeService itdmInventoryBarcodeService;
    @Autowired
    private IItdmSampleInventoryService itdmSampleInventoryService;


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

    /**
     * 添加
     *
     * @param itdmInventoryLog
     * @return
     */
    @AutoLog(value = "库存日志-添加")
    @ApiOperation(value = "库存日志-添加", notes = "库存日志-添加")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_log:add")
    @PostMapping(value = "/add")
    @Transactional
    public Result<String> add(@RequestBody ItdmInventoryLog itdmInventoryLog) {
        ItdmInventoryBarcode itdmInventoryBarcode = itdmInventoryBarcodeService.getOne(Wrappers.lambdaQuery(ItdmInventoryBarcode.class)
                .eq(ItdmInventoryBarcode::getBarCode, itdmInventoryLog.getBarCode()));

        if (itdmInventoryBarcode == null) {
            throw new JeecgBootException("条码不存在");

        }
        if (itdmInventoryBarcode.getDisableStatus().equals("1")) {
            throw new JeecgBootException("条码已经被禁用");

        }


        // 库存-1
        ItdmSampleInventory itdmSampleInventory = itdmSampleInventoryService.getById(itdmInventoryBarcode.getInventoryId());

        if (Objects.equals(itdmInventoryLog.getType(), "1")) {
            itdmSampleInventory.setSampleNum(itdmSampleInventory.getSampleNum() + 1);
            if (itdmInventoryBarcode.getUseStatus().equals("1")) {
                throw new JeecgBootException("当前条码是入库状态不能再次入库");

            }

        }
        if (Objects.equals(itdmInventoryLog.getType(), "2")) {
            if (itdmSampleInventory.getSampleNum() <= 0) {
                throw new JeecgBootException("库存为0不能出库");
            }
            if (itdmInventoryBarcode.getUseStatus().equals("2")) {
                throw new JeecgBootException("当前条码是出库状态不能再次出库");

            }
            itdmSampleInventory.setSampleNum(itdmSampleInventory.getSampleNum() - 1);

        }


        itdmSampleInventoryService.updateById(itdmSampleInventory);

        itdmInventoryLog.setInventoryId(itdmInventoryBarcode.getInventoryId());
        itdmInventoryBarcode.setUseStatus(itdmInventoryLog.getType());
        itdmInventoryBarcodeService.updateById(itdmInventoryBarcode);

        itdmInventoryLog.setUseTime(new Date());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        itdmInventoryLog.setWarehouseBy(user.getUsername());
        itdmInventoryLog.setNum("1");
        itdmInventoryLogService.save(itdmInventoryLog);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param itdmInventoryLog
     * @return
     */
    @AutoLog(value = "库存日志-编辑")
    @ApiOperation(value = "库存日志-编辑", notes = "库存日志-编辑")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_log:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ItdmInventoryLog itdmInventoryLog) {
        itdmInventoryLogService.updateById(itdmInventoryLog);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "库存日志-通过id删除")
    @ApiOperation(value = "库存日志-通过id删除", notes = "库存日志-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_log:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        itdmInventoryLogService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "库存日志-批量删除")
    @ApiOperation(value = "库存日志-批量删除", notes = "库存日志-批量删除")
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_log:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.itdmInventoryLogService.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<ItdmInventoryLog> queryById(@RequestParam(name = "id", required = true) String id) {
        ItdmInventoryLog itdmInventoryLog = itdmInventoryLogService.getById(id);
        if (itdmInventoryLog == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(itdmInventoryLog);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param itdmInventoryLog
     */
    //@RequiresPermissions("org.jeecg.modules:itdm_inventory_log:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ItdmInventoryLog itdmInventoryLog) {
        return super.exportXls(request, itdmInventoryLog, ItdmInventoryLog.class, "库存日志");
    }

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

}
