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.JsInStock;
import com.ruoyi.web.v2.model.JsMaterial;
import com.ruoyi.web.v2.model.JsStock;
import com.ruoyi.web.v2.mapper.JsInStockMapper;
import com.ruoyi.web.v2.mapper.JsMaterialMapper;
import com.ruoyi.web.v2.mapper.JsStockMapper;
import com.ruoyi.web.v2.service.IJsInStockService;
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.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

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

/**
 * <p>
 * v2.0物料入库 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-23
 */
@Service
public class JsInStockServiceImpl extends ServiceImpl<JsInStockMapper, JsInStock> implements IJsInStockService {

    @Autowired
    private JsInStockMapper inStockMapper;
    @Autowired
    private JsStockMapper stockMapper;
    @Autowired
    private JsMaterialMapper materialMapper;
    @Autowired
    private JsStockInfoMapper jsStockInfoMapper;

    @Override
    public AjaxResult add(JsInStock inStock) {
        Integer materialType = inStock.getMaterialType();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(new Date());
        JsStock jsStock1 = new JsStock();
        JsMaterial jsMaterial = materialMapper.selectOne(new QueryWrapper<JsMaterial>().eq("material_type",materialType).eq("material_name",inStock.getMaterialName()));
        inStock.setMaterialNum(jsMaterial.getMaterialNum());
        JsStock jsStock = stockMapper.selectOne(new QueryWrapper<JsStock>().like("material_batch", jsMaterial.getMaterialNum()+format).orderByDesc("id").last(" limit 1"));
        if (ObjectUtil.isEmpty(jsStock)) {
            jsStock1.setMaterialBatch(jsMaterial.getMaterialNum()+format+String.format("%02d", 1));
            inStock.setMaterialBatch(jsMaterial.getMaterialNum()+format+String.format("%02d", 1));
        } else {
            String materialBatch = jsStock.getMaterialBatch();
            Integer integer = Integer.valueOf( materialBatch.substring(materialBatch.length()-2,materialBatch.length()));
            String formattedNumber = String.format("%02d", integer+1);
            jsStock1.setMaterialBatch(materialBatch.substring(0,materialBatch.length()-2)+formattedNumber);
            inStock.setMaterialBatch(materialBatch.substring(0,materialBatch.length()-2)+formattedNumber);
        }

//        if (ObjectUtil.isEmpty(jsMaterial)) {
//            String formattedNumber = String.format("%04d", 1);
//            jsMaterial.setMaterialNum(formattedNumber);
//        } else {
//            String workshopNum = jsMaterial.getMaterialNum();
//            Integer integer = Integer.valueOf(workshopNum);
//            String formattedNumber = String.format("%04d", integer+1);
//            jsMaterial.setMaterialNum(formattedNumber);
//        }

        jsStock1.setLocation(inStock.getLocation());
        jsStock1.setMaterialName(inStock.getMaterialName());
        jsStock1.setMaterialType(inStock.getMaterialType());
        jsStock1.setModel(inStock.getModel());
        jsStock1.setSaveCondition(inStock.getSaveCondition());
        jsStock1.setSaveUser(inStock.getSaveUser());
        jsStock1.setStockAmount(inStock.getStockAmount());
        jsStock1.setUnit(inStock.getUnit());
        jsStock1.setUpdateTime(new Date());
        jsStock1.setMaterialNum(jsMaterial.getMaterialNum());
        stockMapper.insert(jsStock1);

        inStockMapper.insert(inStock);
        updateJsStockInfo(inStock);
        return success();
    }

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


    @Override
    public AjaxResult edit(JsInStock inStock) {



        String materialBatch = inStock.getMaterialBatch();
        JsInStock jsInStock = inStockMapper.selectById(inStock.getId());
        QueryWrapper<JsStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_batch", materialBatch);
        JsStock jsStock = stockMapper.selectOne(queryWrapper);
        double v = Double.valueOf(jsStock.getStockAmount()) - Double.valueOf(jsInStock.getStockAmount()) + Double.valueOf(inStock.getStockAmount());
        jsStock.setStockAmount(String.valueOf(v));
        stockMapper.updateById(jsStock);
        inStockMapper.updateById(inStock);
        inStock.setStockAmount(String.format("%.2f", Double.valueOf(inStock.getStockAmount())- Double.valueOf(jsInStock.getStockAmount()) ));
        updateJsStockInfo(inStock);
        return success();
    }

    @Override
    public AjaxResult delete(String ids) {
//        String[] split = ids.split(",");
//        for (String s : split) {
//            maintenanceMapper.deleteById(s);
//        }
        return success();
    }

    @Override
    public AjaxResult page(Integer pageNum, Integer pageSize, String startTime, String endTime, String materialBatch,
                           String materialName, Integer materialType,  Boolean needAllFlag) {
        Page<JsInStock> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JsInStock> queryWrapper = new QueryWrapper<>();
//        if ("".equals(startTime) || null == startTime) {
//
//        } else {
//            queryWrapper.between("in_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("in_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("id");
        return success(inStockMapper.selectPage(page, queryWrapper));
    }

    @Override
    public AjaxResult listAll(String materialBatch) {
        return success(inStockMapper.selectOne(new QueryWrapper<JsInStock>().eq("material_batch", materialBatch)));
    }

}
