package com.bs.jxc.controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.bs.jxc.domain.CkCargoStock;
import com.bs.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.jxc.domain.CmWarehouse;
import com.bs.jxc.service.ICmWarehouseService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 仓库信息Controller
 *
 * @author bs
 * @date 2023-08-06
 */
@Api(tags = "仓库信息")
@RestController
@RequestMapping("/jxc/warehouse")
public class CmWarehouseController extends BaseController {
    @Resource
    private ICmWarehouseService cmWarehouseService;
    @Resource
    private ISysConfigService configService;

    /**
     * 分页查询仓库信息列表
     */
    @ApiOperation("分页查询仓库信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmWarehouse cmWarehouse) {
        startPage();
        LambdaQueryWrapper<CmWarehouse> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmWarehouse);
        List<CmWarehouse> list = cmWarehouseService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 分页查询即将过期仓库信息列表
     */
    @ApiOperation("分页查询即将过期仓库信息列表")
    @GetMapping("/pageListByWarehouseWithExpire")
    public TableDataInfo pageListByWarehouseWithExpire(CmWarehouse cmWarehouse) {
        String warehouseExpiryDateWarn = configService.selectConfigByKey("warehouseExpiryDateWarn");
        if (warehouseExpiryDateWarn == null || warehouseExpiryDateWarn.isEmpty()) {
            warehouseExpiryDateWarn = "105";
        }
        startPage();
        LambdaQueryWrapper<CmWarehouse> queryWrapper = new LambdaQueryWrapper();
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);
        LocalDate expirationLimit = today.plusDays(Long.parseLong(warehouseExpiryDateWarn));
        queryWrapper.le(CmWarehouse::getValidityEnd, expirationLimit)
                .gt(CmWarehouse::getValidityEnd, yesterday);
        condition(queryWrapper,cmWarehouse);
        List<CmWarehouse> list = cmWarehouseService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询仓库信息列表
     */
    @ApiOperation("查询仓库信息列表")
    @GetMapping("/list")
    public AjaxResult list(CmWarehouse cmWarehouse) {
        LambdaQueryWrapper<CmWarehouse> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmWarehouse);
        List<CmWarehouse> list = cmWarehouseService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出仓库信息列表
     */
    @ApiOperation("导出仓库信息列表")
    @Log(title = "仓库信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmWarehouse cmWarehouse) {
        LambdaQueryWrapper<CmWarehouse> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmWarehouse);
        List<CmWarehouse> list = cmWarehouseService.list(queryWrapper);
        ExcelUtil<CmWarehouse> util = new ExcelUtil<CmWarehouse>(CmWarehouse. class);
        util.exportExcel(response, list, "仓库信息数据");
    }
    @Log(title = "仓库信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<CmWarehouse> util = new ExcelUtil<>(CmWarehouse.class);
            List<CmWarehouse> warehouseList = util.importExcel(file.getInputStream());

            // 创建 LambdaQueryWrapper 对象
            LambdaQueryWrapper<CmWarehouse> queryWrapper = new LambdaQueryWrapper<>();

            // 根据具体需求进行导入操作
            for (CmWarehouse warehouse : warehouseList) {
                // 按照业务需求构建查询条件
                queryWrapper.eq(CmWarehouse::getId, warehouse.getId()); // 示例：根据 ID 判断是否存在

                // 查询数据库中是否已存在相同记录
                Long count = cmWarehouseService.count(queryWrapper);

                if (count > 0) {
                    // 如果已存在记录，则进行更新操作
                    cmWarehouseService.update(warehouse, queryWrapper);
                } else {
                    // 如果不存在记录，则进行插入操作
                    cmWarehouseService.save(warehouse);
                }
            }

            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    @ApiOperation("导入仓库信息列表模板")
    @Log(title = "导入仓库信息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, CmWarehouse cmWarehouse) {
        // 创建一个空的仓库信息列表
        List<CmWarehouse> emptyList = new ArrayList<>();

        // 导出空列表为 Excel 文件
        ExcelUtil<CmWarehouse> util = new ExcelUtil<>(CmWarehouse.class);
        util.exportExcel(response, emptyList, "仓库信息模板");
    }


    /**
     * 获取仓库信息详细信息
     */
    @ApiOperation("获取仓库信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(cmWarehouseService.getById(id));
    }

    /**
     * 新增仓库信息
     */
    @ApiOperation("新增仓库信息")
    @Log(title = "仓库信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmWarehouse cmWarehouse) {
        CmWarehouse cmWarehouse1 = cmWarehouseService.getOne(new LambdaQueryWrapper<CmWarehouse>().eq(CmWarehouse::getStockCode,cmWarehouse.getStockCode()));
        if(cmWarehouse1!=null){
            return error("代码已经存在，请重新输入");
        }
        return toAjax(cmWarehouseService.save(cmWarehouse));
    }

    /**
     * 修改仓库信息
     */
    @ApiOperation("修改仓库信息")
    @Log(title = "仓库信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmWarehouse cmWarehouse) {
        CmWarehouse cmWarehouse1 = cmWarehouseService.getOne(new LambdaQueryWrapper<CmWarehouse>().eq(CmWarehouse::getStockCode,cmWarehouse.getStockCode()));
        if(cmWarehouse1!=null){
            return error("代码已经存在，请重新输入");
        }
        return toAjax(cmWarehouseService.updateById(cmWarehouse));
    }

    /**
     * 删除仓库信息
     */
    @ApiOperation("删除仓库信息")
    @Log(title = "仓库信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(cmWarehouseService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CmWarehouse> queryWrapper,CmWarehouse cmWarehouse){


        //仓库ID
        if(null != cmWarehouse.getId()){
            queryWrapper.eq(CmWarehouse::getId,cmWarehouse.getId());
        }

        if (Validator.isNotEmpty(cmWarehouse.getIsExpire())) {
            queryWrapper.le(CmWarehouse::getValidityEnd, new Date());
        }

        //仓库代码
        if(Validator.isNotEmpty(cmWarehouse.getStockCode())){
            queryWrapper.eq(CmWarehouse::getStockCode,cmWarehouse.getStockCode());
        }

        //仓库名称
        if(Validator.isNotEmpty(cmWarehouse.getStockName())){
            queryWrapper.like(CmWarehouse::getStockName,cmWarehouse.getStockName());
        }

        //仓库有效期起
        if(null != cmWarehouse.getValidityStart()){
            queryWrapper.eq(CmWarehouse::getValidityStart,cmWarehouse.getValidityStart());
        }

        //仓库有效期止
        if(null != cmWarehouse.getValidityEnd()){
            queryWrapper.eq(CmWarehouse::getValidityEnd,cmWarehouse.getValidityEnd());
        }

        //备注
        if(Validator.isNotEmpty(cmWarehouse.getRemark())){
            queryWrapper.eq(CmWarehouse::getRemark,cmWarehouse.getRemark());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(cmWarehouse.getDelFlag())){
            queryWrapper.eq(CmWarehouse::getDelFlag,cmWarehouse.getDelFlag());
        }

        //创建部门
        if(null != cmWarehouse.getCreateDept()){
            queryWrapper.eq(CmWarehouse::getCreateDept,cmWarehouse.getCreateDept());
        }

        //创建人
        if(null != cmWarehouse.getCreateBy()){
            queryWrapper.eq(CmWarehouse::getCreateBy,cmWarehouse.getCreateBy());
        }

        //创建时间
        if(null != cmWarehouse.getCreateTime()){
            queryWrapper.eq(CmWarehouse::getCreateTime,cmWarehouse.getCreateTime());
        }

        //修改人
        if(null != cmWarehouse.getUpdateBy()){
            queryWrapper.eq(CmWarehouse::getUpdateBy,cmWarehouse.getUpdateBy());
        }

        //修改时间
        if(null != cmWarehouse.getUpdateTime()){
            queryWrapper.eq(CmWarehouse::getUpdateTime,cmWarehouse.getUpdateTime());
        }

        //租户ID
        if(Validator.isNotEmpty(cmWarehouse.getTenantId())){
            queryWrapper.eq(CmWarehouse::getTenantId,cmWarehouse.getTenantId());
        }

        }

}
