package com.zbf.system.service.impl;

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.StringUtils;
import com.zbf.common.utils.bean.BeanValidators;
import com.zbf.system.domain.TBasePallet;
import com.zbf.system.mapper.TBasePalletMapper;
import com.zbf.system.service.ITBasePalletService;
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.List;

/**
 * 托盘Service业务层处理
 *
 * @author sunits
 * @date 2024-06-16
 */
@Service
public class TBasePalletServiceImpl extends ServiceImpl<TBasePalletMapper, TBasePallet> implements ITBasePalletService //修改
{
    @Resource
    private TBasePalletMapper tBasePalletMapper;
    @Autowired
    protected Validator validator;

    /**
     * 查询托盘
     *
     * @param id 托盘主键
     * @return 托盘
     */
    @Override
    public TBasePallet selectTBasePalletById(Long id) {
        return tBasePalletMapper.selectTBasePalletById(id);
    }

    /**
     * 查询托盘列表
     *
     * @param tBasePallet 托盘
     * @return 托盘
     */
    @Override
    public List<TBasePallet> selectTBasePalletList(TBasePallet tBasePallet) {
        return tBasePalletMapper.selectTBasePalletList(tBasePallet);
    }

    /**
     * 新增托盘
     *
     * @param tBasePallet 托盘
     * @return 结果
     */
    @Override
    public int insertTBasePallet(TBasePallet tBasePallet) {
        tBasePallet.setCreateTime(DateUtils.getNowDate());
        //查询是否已经包含了该托盘
        TBasePallet tBasePallet1 = new TBasePallet();
        tBasePallet1.setPalletId(tBasePallet.getPalletId());
        tBasePallet.setStatus("0");
        List<TBasePallet> tBasePallets = tBasePalletMapper.selectTBasePalletList(tBasePallet1);
        if (tBasePallets.size() > 0) {
            throw new RuntimeException("该托盘已存在，请勿重复添加");
        }
        if(tBasePallet.getPalletId().startsWith("A1FB") || tBasePallet.getPalletId().startsWith("A2FA")){
            tBasePallet.setStorageId("东区中心库");
        }else if(startsWithSixDigits(tBasePallet.getPalletId())){
            tBasePallet.setStorageId("南区中心库");
        }
        return tBasePalletMapper.insertTBasePallet(tBasePallet);
    }
    public  static boolean startsWithSixDigits(String str) {
        return str.matches("^\\d{6}.*"); // 使用正则表达式检查前6位是否全为数字
    }


    /**
     * 修改托盘
     *
     * @param tBasePallet 托盘
     * @return 结果
     */
    @Override
    public int updateTBasePallet(TBasePallet tBasePallet) {
        tBasePallet.setUpdateTime(DateUtils.getNowDate());
        return tBasePalletMapper.updateTBasePallet(tBasePallet);
    }

    /**
     * 批量删除托盘
     *
     * @param ids 需要删除的托盘主键
     * @return 结果
     */
    @Override
    public int deleteTBasePalletByIds(Long[] ids) {
        return tBasePalletMapper.deleteTBasePalletByIds(ids);
    }

    /**
     * 删除托盘信息
     *
     * @param id 托盘主键
     * @return 结果
     */
    @Override
    public int deleteTBasePalletById(Long id) {
        return tBasePalletMapper.deleteTBasePalletById(id);
    }


    /**
     * 批量禁用
     *
     * @param id 托盘主键
     * @return 结果
     */
    @Override
    public int disabledTBasePalletByIds(Long[] ids) {
        return tBasePalletMapper.disabledTBasePalletByIds(ids);
    }

    /**
     * 批量启用
     *
     * @param id 托盘主键
     * @return 结果
     */
    @Override
    public int enableTBasePalletByIds(Long[] ids) {
        return tBasePalletMapper.enableTBasePalletByIds(ids);
    }



    @Override
    public int changeStatus(Long[] ids, TBasePallet tBasePallet) {
        tBasePallet.setIds(Arrays.asList(ids));
        tBasePalletMapper.updateLockStatus(tBasePallet);
        return 1;
    }
    @Override
    public String importData(List<TBasePallet> palletList, boolean updateSupport, String userName) {
        if (StringUtils.isNull(palletList) || palletList.size() == 0) {
            throw new ServiceException("导入托盘数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TBasePallet tBasePallet : palletList) {
            try {
                // 验证是否存在这个托盘
                TBasePallet old = tBasePalletMapper.selectOne(new QueryWrapper<TBasePallet>().eq("pallet_id", tBasePallet.getPalletId()));
                if (StringUtils.isNull(old)) {
                    BeanValidators.validateWithException(validator, tBasePallet);
                    tBasePallet.setUserId(userName);
                    tBasePallet.setStatus("0");
                    if(tBasePallet.getPalletId().startsWith("A1FB") || tBasePallet.getPalletId().startsWith("A2FA")){
                        tBasePallet.setStorageId("东区中心库");
                    }else if(startsWithSixDigits(tBasePallet.getPalletId())){
                        tBasePallet.setStorageId("南区中心库");
                    }
                    tBasePalletMapper.insertTBasePallet(tBasePallet);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、托盘 " + tBasePallet.getPalletId() + " 导入成功");
                } else if (updateSupport) {
                    BeanValidators.validateWithException(validator, tBasePallet);
                    tBasePallet.setUserId(tBasePallet.getUserId());
                    tBasePallet.setUpdateBy(userName);
                    tBasePalletMapper.updateTBasePallet(tBasePallet);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、托盘 " + tBasePallet.getPalletId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、托盘 " + tBasePallet.getPalletId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、托盘 " + tBasePallet.getPalletId() + " 导入失败：";
                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();
    }


}
