package com.ruoyi.ehsMaterial.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.ehsRisk.domain.EhsRisk;
import com.ruoyi.materialClass.domain.MaterialClassMaster;
import com.ruoyi.materialClass.domain.MaterialClassSub;
import com.ruoyi.materialClass.mapper.MaterialClassMasterMapper;
import com.ruoyi.materialClass.mapper.MaterialClassSubMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.common.utils.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.ehsMaterial.mapper.EhsMaterialMapper;
import com.ruoyi.ehsMaterial.domain.EhsMaterial;
import com.ruoyi.ehsMaterial.service.IEhsMaterialService;

import javax.validation.Validator;

/**
 * 物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-04
 */
@Service
public class EhsMaterialServiceImpl extends ServiceImpl<EhsMaterialMapper, EhsMaterial> implements IEhsMaterialService {

    @Autowired
    private EhsMaterialMapper ehsMaterialMapper;
    @Autowired
    private MaterialClassSubMapper materialClassSubMapper;
    @Autowired
    protected Validator validator;
    /**
     * 查询物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”
     *
     * @param materialId 物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”主键
     * @return 物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”
     */
    @Override
    public EhsMaterial selectEhsMaterialByMaterialId(Long materialId)
    {
        return ehsMaterialMapper.selectEhsMaterialByMaterialId(materialId);
    }

    /**
     * 查询物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”列表
     *
     * @param ehsMaterial 物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”
     * @return 物资信息包含  通用应急救援装备”“防汛抗旱应急救援装备”“森林防灭火应急救援装备”“救灾物资”
     */
    @Override
    public List<EhsMaterial> selectEhsMaterialList(EhsMaterial ehsMaterial)
    {
        if(SecurityUtils.getLoginUser().getUser().getDept().getParentId()!=null &&
                SecurityUtils.getLoginUser().getUser().getDept().getParentId().longValue()!=0){
            ehsMaterial.setDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId().longValue());
        }

        return ehsMaterialMapper.selectEhsMaterialList(ehsMaterial);
    }
    public List<EhsMaterial> selectEhsMateriallExportList(EhsMaterial ehsMaterial){
        if(SecurityUtils.getLoginUser().getUser().getDept().getParentId()!=null &&
                SecurityUtils.getLoginUser().getUser().getDept().getParentId().longValue()!=0){
            ehsMaterial.setDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId().longValue());
        }
        return ehsMaterialMapper.selectEhsMateriallExportList(ehsMaterial);
    }

    private LambdaQueryWrapper<EhsMaterial> buildQueryWrapper(EhsMaterial query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<EhsMaterial> lqw = Wrappers.lambdaQuery();
        lqw.eq(query.getMaterialType() != null, EhsMaterial::getMaterialType, query.getMaterialType());
        lqw.eq(query.getClassFirst() != null, EhsMaterial::getClassFirst, query.getClassFirst());
        lqw.eq(StringUtils.isNotBlank(query.getClassSecond()), EhsMaterial::getClassSecond, query.getClassSecond());
        lqw.like(StringUtils.isNotBlank(query.getMaterialName()), EhsMaterial::getMaterialName, query.getMaterialName());
        lqw.eq(StringUtils.isNotBlank(query.getMaterialSpecs()), EhsMaterial::getMaterialSpecs, query.getMaterialSpecs());
        lqw.eq(StringUtils.isNotBlank(query.getMaterialQuantity()), EhsMaterial::getMaterialQuantity, query.getMaterialQuantity());
        lqw.like(StringUtils.isNotBlank(query.getReserveLocation()), EhsMaterial::getReserveLocation, query.getReserveLocation());
        lqw.like(StringUtils.isNotBlank(query.getManagerPerson()), EhsMaterial::getManagerPerson, query.getManagerPerson());
        lqw.like(StringUtils.isNotBlank(query.getTel()), EhsMaterial::getTel, query.getTel());
        lqw.orderByDesc(EhsMaterial::getCreateTime);
        return lqw;
    }
    /**
     * 导入用户数据
     *
     * @param list  数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importMaterial(List<EhsMaterial> list,String classType, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        MaterialClassSub msm = new MaterialClassSub();
        msm.setClassMastType(classType);
        List<MaterialClassSub> mlist = materialClassSubMapper.selectMaterialClassSubList(msm);
        Map<String, String> map = mlist.stream()
                .collect(Collectors.toMap(MaterialClassSub::getClassNameSub, MaterialClassSub::getClassSubId));

        int i =0;
        for (EhsMaterial obj : list)
        {
            i++;
            try
            {
                if(StringUtils.isNotEmpty(obj.getMaterialName()) && map.containsKey(obj.getMaterialName())) {
                    BeanValidators.validateWithException(validator, obj);
                    String  SbuId = map.get(obj.getMaterialName());
                    String mSid = SbuId.split("-")[0];
                    obj.setClassSecond(mSid);
                    obj.setMaterialName(SbuId);
                    ehsMaterialMapper.insert(obj);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第 " + i + " 行记录导入成功");
                }else{
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、第 " +i + " 行记录导入失败,物资名称未找到或为空："+obj.getMaterialName();
                    failureMsg.append( msg);
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第 " +i + " 行记录导入失败：";
                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();
    }
}
