package com.bs.jxc.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.bs.jxc.domain.CkCargoStock;
import com.bs.jxc.domain.CmPort;
import com.bs.jxc.domain.CmVessel;
import com.bs.jxc.service.ICkCargoStockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.CmStock;
import com.bs.jxc.service.ICmStockService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 库场管理Controller
 *
 * @author bs
 * @date 2023-07-10
 */
@Api(tags = "库场管理")
@RestController
@RequestMapping("/jxc/stock")
public class CmStockController extends BaseController {
    @Resource
    private ICmStockService cmStockService;
    @Resource
    private ICkCargoStockService ckCargoStockService;

    /**
     * 分页查询库场管理列表
     */
    @ApiOperation("分页查询库场管理列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmStock cmStock) {
        startPage();
        LambdaQueryWrapper<CmStock> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmStock);
        //queryWrapper.orderByAsc(CmStock::getStockCode).orderByAsc(CmStock::getStockName);
        List<CmStock> list = cmStockService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询库场管理列表
     */
    @ApiOperation("查询库场管理列表")
    @GetMapping("/list")
    public AjaxResult list(CmStock cmStock) {
        LambdaQueryWrapper<CmStock> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmStock);
        queryWrapper.orderByAsc(CmStock::getStockCode).orderByAsc(CmStock::getStockName);
        List<CmStock> list = cmStockService.list(queryWrapper);
        return success(list);
    }

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

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

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

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

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

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

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

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


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

    /**
     * 新增库场管理
     */
    @ApiOperation("新增库场管理")
    @Log(title = "库场管理新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmStock cmStock) {



        return toAjax(cmStockService.save(cmStock));
    }

    /**
     * 修改库场管理
     */
    @ApiOperation("修改库场管理")
    @Log(title = "库场管理修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmStock cmStock) {

        LambdaQueryWrapper<CkCargoStock> wrapper = new LambdaQueryWrapper();
        wrapper.eq(CkCargoStock::getStockId,cmStock.getId());
        wrapper.and(wp->{
            wp.eq(CkCargoStock::getCargoNum,0).or()
                    .or().gt(CkCargoStock::getCargoWt,0)
                    .or().gt(CkCargoStock::getCargoVol,0);
        });
        long count = ckCargoStockService.count(wrapper);
        if (count > 0) {
            return AjaxResult.error("该仓库下还有库存，不能修改");
        }
        return toAjax(cmStockService.updateById(cmStock));
    }

    /**
     * 删除库场管理
     */
    @ApiOperation("删除库场管理")
    @Log(title = "库场管理删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        LambdaQueryWrapper<CkCargoStock> wrapper = new LambdaQueryWrapper();
        wrapper.in(CkCargoStock::getStockId,ids);
        wrapper.and(wp->{
            wp.eq(CkCargoStock::getCargoNum,0).or()
                    .or().gt(CkCargoStock::getCargoWt,0)
                    .or().gt(CkCargoStock::getCargoVol,0);
        });
        long count = ckCargoStockService.count(wrapper);
        if (count > 0) {
            return AjaxResult.error("删除的仓库下还有库存，不能直接删除");
        }
        return toAjax(cmStockService.removeBatchByIds(ids));
    }

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



        //库场代码
        if(Validator.isNotEmpty(cmStock.getStockCode())){
            queryWrapper.like(CmStock::getStockCode,cmStock.getStockCode());
        }

        //库场名称
        if(Validator.isNotEmpty(cmStock.getStockName())){
            queryWrapper.like(CmStock::getStockName,cmStock.getStockName());
        }

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

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



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

        }

}
