package com.ruoyi.web.v2.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.v2.entity.JsStockInfo;
import com.ruoyi.web.v2.mapper.JsStockInfoMapper;
import com.ruoyi.web.v2.model.JsOutStock;
import com.ruoyi.web.v2.model.JsStock;
import com.ruoyi.web.v2.mapper.JsOutStockMapper;
import com.ruoyi.web.v2.mapper.JsStockMapper;
import com.ruoyi.web.v2.service.IJsOutStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.util.Date;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * <p>
 * v2.0物料领用 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-23
 */
@Service
public class JsOutStockServiceImpl extends ServiceImpl<JsOutStockMapper, JsOutStock> implements IJsOutStockService {

    @Autowired
    private JsOutStockMapper jsOutStockMapper;
    @Autowired
    private JsStockMapper stockMapper;


    @Override
    public AjaxResult add(JsOutStock inStock) {
        String materialBatch = inStock.getMaterialBatch();
        QueryWrapper<JsStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_batch", materialBatch);
        JsStock jsStock = stockMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(jsStock) || "0".equals(jsStock.getStockAmount())) {
            return error("该批次可领用数量为0");
        }
        String stockAmount = jsStock.getStockAmount();
        if (Double.valueOf(inStock.getStockAmount()) > Double.valueOf(stockAmount)) {
            return error("当前批次可领用数量小于领用数量");
        }
        double v = Double.valueOf(stockAmount) - Double.valueOf(inStock.getStockAmount());
        jsStock.setStockAmount(String.valueOf(v));
        jsStock.setUpdateTime(new Date());
        stockMapper.updateById(jsStock);
        //自动填充记录中的物料编号
        inStock.setMaterialNum(jsStock.getMaterialNum());
        jsOutStockMapper.insert(inStock);
        updateJsStockInfo(inStock);
        return success();
    }

    @Autowired
    private JsStockInfoMapper jsStockInfoMapper;

    private void updateJsStockInfo(JsOutStock inStock) {
        JsStockInfo jsStockInfo = jsStockInfoMapper.selectOne(new QueryWrapper<JsStockInfo>().eq("material_name", inStock.getMaterialName()).orderByDesc("id").last("limit 1"));
        if (ObjectUtil.isNotEmpty(jsStockInfo)){
            jsStockInfo.setCreateTime(new Date());
            jsStockInfo.setOutNum(inStock.getStockAmount());
            jsStockInfo.setLinghuoren(inStock.getSaveUser());
            jsStockInfo.setInNum("0");
            jsStockInfo.setNumber(String.format("%.2f",Double.parseDouble(jsStockInfo.getNumber())-Double.parseDouble(inStock.getStockAmount())));
            jsStockInfoMapper.insert(jsStockInfo);
        }
    }

    @Override
    public AjaxResult edit(JsOutStock outStock) {
        JsOutStock jsOutStock = jsOutStockMapper.selectById(outStock.getId());
        String materialBatch = outStock.getMaterialBatch();
        QueryWrapper<JsStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_batch", materialBatch);
        JsStock jsStock = stockMapper.selectOne(queryWrapper);
        if ("0".equals(jsStock.getStockAmount())) {
            return error("该批次可领用数量为0");
        }
        String stockAmount = jsStock.getStockAmount();
        if (Double.valueOf(outStock.getStockAmount()) > Double.valueOf(stockAmount)+Double.valueOf(jsOutStock.getStockAmount())) {
            return error("可领用数量小于领用数量");
        }
        jsStock.setStockAmount(String.valueOf(Double.valueOf(stockAmount)+Double.valueOf(jsOutStock.getStockAmount()) - Double.valueOf(outStock.getStockAmount())));
        jsStock.setUpdateTime(new Date());
        stockMapper.updateById(jsStock);
        jsOutStockMapper.updateById(outStock);

        outStock.setStockAmount(String.format("%.2f", Double.valueOf(outStock.getStockAmount())- Double.valueOf(jsStock.getStockAmount()) ));
        updateJsStockInfo(outStock);
        return success();
    }

    @Override
    public AjaxResult delete(String ids) {
        return null;
    }

    @Override
    public AjaxResult page(Integer pageNum, Integer pageSize, String startTime, String endTime, String materialBatch,
                           String materialName, Integer materialType,  Boolean needAllFlag) {
        Page<JsOutStock> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JsOutStock> queryWrapper = new QueryWrapper<>();
//        if ("".equals(startTime) || null == startTime) {
//
//        } else {
//            queryWrapper.between("out_time",startTime+" 00:00:00", endTime+" 23:59:59");
//        }
//        queryWrapper.like(StringUtils.isNotEmpty(materialBatch), "material_batch", materialBatch)
//                .or().like(StringUtils.isNotEmpty(materialName), "material_name", materialName);
        if(!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(endTime) ) {
            queryWrapper.between("out_time", LocalDate.parse(startTime), LocalDate.parse(endTime));
        }
        if(!ObjectUtils.isEmpty(materialBatch)) {
            queryWrapper.likeLeft("material_batch", materialBatch);
        }
        if(!ObjectUtils.isEmpty(materialName)) {
            queryWrapper.like("material_name", materialName);
        }
        if (null != materialType) {
            queryWrapper.eq("material_type", materialType);
        }else if(ObjectUtils.isEmpty(needAllFlag) || needAllFlag.equals(Boolean.FALSE)) {
            //material_type=3表示该种物料是危险品，查询时默认排除危险品
            queryWrapper.ne("material_type", 3);
        }
        queryWrapper.orderByDesc("out_time");
        return success(jsOutStockMapper.selectPage(page, queryWrapper));
    }

    @Override
    public AjaxResult listAll() {
        return success(jsOutStockMapper.selectList(null));
    }
}
