package com.zbf.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbf.common.exception.ServiceException;
import com.zbf.common.utils.DateUtils;
import com.zbf.common.utils.SecurityUtils;
import com.zbf.common.utils.StringUtils;
import com.zbf.common.utils.bean.BeanValidators;
import com.zbf.system.domain.TBasePallet;
import com.zbf.system.domain.TBaseStorageAreaLocation;
import com.zbf.system.domain.TMiStock;
import com.zbf.system.mapper.TBaseStorageAreaLocationMapper;
import com.zbf.system.mapper.TMiStockMapper;
import com.zbf.system.service.ITBaseStorageAreaLocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 库位 Service业务层处理
 *
 * @author tony
 * @date 2024-06-14
 */
@Service
public class TBaseStorageAreaLocationServiceImpl extends ServiceImpl<TBaseStorageAreaLocationMapper, TBaseStorageAreaLocation> implements ITBaseStorageAreaLocationService //修改
{
    @Resource
    private TBaseStorageAreaLocationMapper tBaseStorageAreaLocationMapper;
    @Resource
    private TMiStockMapper tMiStockMapper;
    @Autowired
    protected Validator validator;

    /**
     * 查询库位
     *
     * @param id 库位 主键
     * @return 库位
     */
    @Override
    public TBaseStorageAreaLocation selectTBaseStorageAreaLocationById(Long id) {
        return tBaseStorageAreaLocationMapper.selectTBaseStorageAreaLocationById(id);
    }

    /**
     * 查询库位 列表
     *
     * @param tBaseStorageAreaLocation 库位
     * @return 库位
     */
    @Override
    public List<TBaseStorageAreaLocation> selectTBaseStorageAreaLocationList(TBaseStorageAreaLocation tBaseStorageAreaLocation) {
        return tBaseStorageAreaLocationMapper.selectTBaseStorageAreaLocationList(tBaseStorageAreaLocation);
    }

    /**
     * 新增库位
     *
     * @param tBaseStorageAreaLocation 库位
     * @return 结果
     */
    @Override
    public int insertTBaseStorageAreaLocation(TBaseStorageAreaLocation tBaseStorageAreaLocation) {
        log.trace(String.format("新增库位信息开始：%s", tBaseStorageAreaLocation));
        tBaseStorageAreaLocation.setCreateTime(DateUtils.getNowDate());
        if(StringUtils.isBlank(tBaseStorageAreaLocation.getStatus())){
            tBaseStorageAreaLocation.setStatus("0");
        }
        tBaseStorageAreaLocation.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        //查询是否已经包含了该库位
        TBaseStorageAreaLocation tBaseStorageAreaLocation1 = new TBaseStorageAreaLocation();
        tBaseStorageAreaLocation1.setLocationId(tBaseStorageAreaLocation.getLocationId());
        List<TBaseStorageAreaLocation> tBaseStorageAreaLocations =
                tBaseStorageAreaLocationMapper.selectTBaseStorageAreaLocationList(tBaseStorageAreaLocation1);
        if (tBaseStorageAreaLocations.size() > 0) {
            throw new RuntimeException("该库位已存在，请勿重复添加");
        }
        return tBaseStorageAreaLocationMapper.insertTBaseStorageAreaLocation(tBaseStorageAreaLocation);
    }

    /**
     * 修改库位
     *
     * @param tBaseStorageAreaLocation 库位
     * @return 结果
     */
    @Override
    public int updateTBaseStorageAreaLocation(TBaseStorageAreaLocation tBaseStorageAreaLocation) {
        log.trace(String.format("更改库位信息开始：%s", tBaseStorageAreaLocation));
        tBaseStorageAreaLocation.setUpdateTime(DateUtils.getNowDate());
        TBaseStorageAreaLocation tBaseStorageAreaLocation1 = tBaseStorageAreaLocationMapper.selectTBaseStorageAreaLocationById(tBaseStorageAreaLocation.getId());
        if (!tBaseStorageAreaLocation.getStatus().equals(tBaseStorageAreaLocation1.getStatus())) {
            //查询库存
            TMiStock tMiStock = new TMiStock();
            tMiStock.setLocationId(tBaseStorageAreaLocation.getLocationId());
            QueryWrapper<TMiStock> queryWrapper = new QueryWrapper<>(tMiStock);
            List<TMiStock> tMiStocks = tMiStockMapper.selectList(queryWrapper);
            //如果1变成0
            if ("0".equals(tBaseStorageAreaLocation.getStatus())) {
                if (tMiStocks.size() > 0) {
                    throw new RuntimeException("有库存，无法设置为空闲");
                }
            } else {
                //如果0变成1
                if (tMiStocks.size() == 0) {
                    throw new RuntimeException("没有查询到库存，无法设置为占用");
                }
            }
        }
        return tBaseStorageAreaLocationMapper.updateTBaseStorageAreaLocation(tBaseStorageAreaLocation);
    }

    /**
     * 批量删除库位
     *
     * @param ids 需要删除的库位 主键
     * @return 结果
     */
    @Override
    public int deleteTBaseStorageAreaLocationByIds(Long[] ids) {
        return tBaseStorageAreaLocationMapper.deleteTBaseStorageAreaLocationByIds(ids);
    }

    /**
     * 删除库位 信息
     *
     * @param id 库位 主键
     * @return 结果
     */
    @Override
    public int deleteTBaseStorageAreaLocationById(Long id) {
        return tBaseStorageAreaLocationMapper.deleteTBaseStorageAreaLocationById(id);
    }


    /**
     * 批量禁用
     *
     * @param ids 库位 主键
     * @return 结果
     */
    @Override
    public int disabledTBaseStorageAreaLocationByIds(Long[] ids) {
//        log.trace(String.format("删除库位信息开始：%s", ids));
        return tBaseStorageAreaLocationMapper.disabledTBaseStorageAreaLocationByIds(ids);
    }

    /**
     * 批量启用
     *
     * @param ids 库位 主键
     * @return 结果
     */
    @Override
    public int enableTBaseStorageAreaLocationByIds(Long[] ids) {
        return tBaseStorageAreaLocationMapper.enableTBaseStorageAreaLocationByIds(ids);
    }

    /**
     * 修改状态
     *
     * @param tBaseStorageAreaLocation 工序管理主键
     * @return 结果
     */
    @Override
    public int updateStatus(TBaseStorageAreaLocation tBaseStorageAreaLocation) {
        log.trace(String.format("更改库位状态开始：%s", tBaseStorageAreaLocation));
        TBaseStorageAreaLocation tBaseStorageAreaLocation2 = new TBaseStorageAreaLocation();
        tBaseStorageAreaLocation2.setLocationId(tBaseStorageAreaLocation.getLocationId());
        List<TBaseStorageAreaLocation> tBaseStorageAreaLocations = tBaseStorageAreaLocationMapper.selectTBaseStorageAreaLocationList(tBaseStorageAreaLocation2);
        if (tBaseStorageAreaLocations.size() == 0) {
            throw new RuntimeException("查询库位异常,库位ID为：" + tBaseStorageAreaLocation.getLocationId());
        }
        TBaseStorageAreaLocation tBaseStorageAreaLocation1 = tBaseStorageAreaLocations.get(0);
        if (!tBaseStorageAreaLocation.getStatus().equals(tBaseStorageAreaLocation1.getStatus())) {
            //查询库存
            TMiStock tMiStock = new TMiStock();
            tMiStock.setLocationId(tBaseStorageAreaLocation.getLocationId());
            QueryWrapper<TMiStock> queryWrapper = new QueryWrapper<>(tMiStock);
            List<TMiStock> tMiStocks = tMiStockMapper.selectList(queryWrapper);
            //如果1变成0
            if ("0".equals(tBaseStorageAreaLocation.getStatus())) {
                if (tMiStocks.size() > 0) {
                    throw new RuntimeException("有库存，无法设置为空闲");
                }
            } else {
                //如果0变成1
                if (tMiStocks.size() == 0) {
                    throw new RuntimeException("没有查询到库存，无法设置为占用");
                }
            }
        }
        return tBaseStorageAreaLocationMapper.updateTBaseStorageAreaLocation(tBaseStorageAreaLocation);
    }

    @Override
    public List<TBaseStorageAreaLocation> occupy() {
        log.trace("库位状态为占用开始====》》》》");
        List<TBaseStorageAreaLocation> result = tBaseStorageAreaLocationMapper.occupy();
        for (TBaseStorageAreaLocation areaLocation : result) {
            //有库存，库位没占用
            if ("1".equals(areaLocation.getStatus()) && "0".equals(areaLocation.getIsLock())) {
                areaLocation.setInLine("1");
            }
            //没有库存，库位被占用
            if ("0".equals(areaLocation.getStatus()) && "1".equals(areaLocation.getIsLock())) {
                areaLocation.setOutLine("1");
            }
        }
        return result;

    }

    @Override
    public String importData(List<TBaseStorageAreaLocation> locationList, boolean updateSupport, String userName) {
        if (StringUtils.isNull(locationList) || locationList.size() == 0) {
            throw new ServiceException("导入库位数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TBaseStorageAreaLocation areaLocation : locationList) {
            try {
                // 验证是否存在这个托盘
                TBaseStorageAreaLocation old = tBaseStorageAreaLocationMapper.selectOne(new QueryWrapper<TBaseStorageAreaLocation>().eq("location_id", areaLocation.getLocationId()));
                if (StringUtils.isNull(old)) {
                    BeanValidators.validateWithException(validator, areaLocation);
                    areaLocation.setStatus("0");
                    areaLocation.setCreateBy(userName);
                    areaLocation.setCreateTime(new Date());
                    tBaseStorageAreaLocationMapper.insertTBaseStorageAreaLocation(areaLocation);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、库位 " + areaLocation.getLocationId() + " 导入成功");
                } else if (updateSupport) {
                    BeanValidators.validateWithException(validator, areaLocation);
                    areaLocation.setUpdateBy(userName);
                    areaLocation.setUpdateTime(new Date());
                    tBaseStorageAreaLocationMapper.updateTBaseStorageAreaLocation(areaLocation);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、库位 " + areaLocation.getLocationId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、库位 " + areaLocation.getLocationId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、库位 " + areaLocation.getLocationId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int changeStatus(Long[] ids, TBaseStorageAreaLocation tBaseStorageAreaLocation) {
        tBaseStorageAreaLocation.setIds(Arrays.asList(ids));
        tBaseStorageAreaLocationMapper.updateLockStatus(tBaseStorageAreaLocation);
        return 1;
    }


}
