package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.ActSuppliesImportCleaningAcc;
import com.ruoyi.system.domain.ActSuppliesMaterialDetails;
import com.ruoyi.system.mapper.ActSuppliesCleaningRuleMapper;
import com.ruoyi.system.mapper.ActSuppliesMaterialMapper;
import com.ruoyi.system.model.SelActSuppliesDao;
import com.ruoyi.system.service.ActSuppliesMaterialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author haiwe
 * @date 2024/7/8
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ActSuppliesMaterialServiceImpl implements ActSuppliesMaterialService {
    private final ActSuppliesMaterialMapper actSuppliesMaterialMapper;
    private final ActSuppliesCleaningRuleMapper actSuppliesCleaningRuleMapper;

    @Override
    public Boolean save(List<ActSuppliesMaterialDetails> materials) {
        Jedis redis = new Jedis("192.168.111.226", 6379);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long userId = user.getUserId();
        if (redis.exists(userId + "物料save") && redis.get(userId + "物料save").equals("物料save")) {
            redis.close();
            return false;
        }
        redis.set(userId + "物料save", "物料save");
        redis.expire(userId + "物料save", 8);
        redis.close();
        Stream<ActSuppliesMaterialDetails> materialStream = materials.stream();
        //将mineId和dateColumn拼接之后进行去重
        Set<String> uniqueCombos = materialStream
                .map(material -> material.getMineId() + "_" + material.getDateColumn()) // Create comboKey
                .collect(Collectors.toSet());
        for (String uniqueCombo : uniqueCombos) {
            String[] part = uniqueCombo.split("_");
            String mineId = part[0];
            String dateColumn = part[1];
            //执行删除操作
            actSuppliesMaterialMapper.delete(mineId, dateColumn);
            actSuppliesCleaningRuleMapper.deleteByMineIdAndDateColumn(mineId, dateColumn);
        }
        List<ActSuppliesImportCleaningAcc> cleaningAccList = new ArrayList<>();
        for (ActSuppliesMaterialDetails material : materials) {
            if (material != null) { // 检查 material 是否为 null
                ActSuppliesImportCleaningAcc cleaningAcc = new ActSuppliesImportCleaningAcc();
                cleaningAcc.setId(UUID.randomUUID().toString().replace("-", ""));
                cleaningAcc.setSskId(material.getMineId() != null ? material.getMineId() : ""); // 处理可能的 null
                cleaningAcc.setHdate(material.getDateColumn() != null ? material.getDateColumn() : "");
                cleaningAcc.setNameColumn(material.getNameColumn() != null ? material.getNameColumn() : "");
                cleaningAcc.setCodeColumn(material.getCodeColumn() != null ? material.getCodeColumn() : "");
                cleaningAcc.setDepartmentColumn(material.getDepartmentColumn() != null ? material.getDepartmentColumn() : "");
                cleaningAcc.setNumberColumn(material.getNumberColumn() != null ? String.valueOf(material.getNumberColumn()) : "");
                cleaningAcc.setMoneyColumn(material.getMoneyColumn() != null ? material.getMoneyColumn().toString() : "0");
                cleaningAcc.setMoneyColumns(material.getMoney() != null ? material.getMoney().toString() : "0");
                cleaningAcc.setsOfExpenses(material.getSourceColoumn() != null ? material.getSourceColoumn() : "");
                cleaningAcc.setUnit(material.getUnit() != null ? material.getUnit() : "");
                cleaningAcc.setModel(material.getModel() != null ? material.getModel().replaceAll(" ","") : "");
                cleaningAccList.add(cleaningAcc);
            }
        }

      //actSuppliesCleaningRuleMapper.insert(cleaningAccList);

        List<SelActSuppliesDao> list = actSuppliesCleaningRuleMapper.selActSupplies();
        list.parallelStream().forEach(v -> {
            v.setSuppliesName(v.getSuppliesName().replace("研究费用", "研发费用"));
            v.setSuppliesName(v.getSuppliesName().replace("安全资金", "安全费用"));
        });
        List<SelActSuppliesDao> listOne = actSuppliesCleaningRuleMapper.selActSuppliesOne();
        materials.parallelStream().forEach(v -> v.getSourceColoumn().replace("-", ""));
        for (ActSuppliesMaterialDetails material : materials) {
            String codeColumn = material.getCodeColumn();
            if (list.parallelStream().anyMatch(v -> codeColumn.substring(0, 6).equals(v.getCode()))) {
                SelActSuppliesDao selActSuppliesDao = list.parallelStream().filter(v -> codeColumn.substring(0, 6).equals(v.getCode())).findFirst().get();
                extracted(material, selActSuppliesDao, listOne);
            } else if (list.parallelStream().anyMatch(v -> codeColumn.substring(0, 4).equals(v.getCode()))) {
                SelActSuppliesDao selActSuppliesDao = list.parallelStream().filter(v -> codeColumn.substring(0, 4).equals(v.getCode())).findFirst().get();
                extracted(material, selActSuppliesDao, listOne);
            } else if (list.parallelStream().anyMatch(v -> codeColumn.substring(0, 2).equals(v.getCode()))) {
                SelActSuppliesDao selActSuppliesDao = list.parallelStream().filter(v -> codeColumn.substring(0, 2).equals(v.getCode())).findFirst().get();
                extracted(material, selActSuppliesDao, listOne);
            } else {
                material.setGeneralLevel("其他");
                material.setGeneralTwoLevel("其他");
            }
        }

        return actSuppliesMaterialMapper.save(materials);
    }

    private void extracted(ActSuppliesMaterialDetails material, SelActSuppliesDao selActSuppliesDao, List<SelActSuppliesDao> listOne) {
        if ((selActSuppliesDao.getTwoLevel() == null || selActSuppliesDao.getTwoLevel().equals("")) && (selActSuppliesDao.getOneLevel() != null && !selActSuppliesDao.getOneLevel().equals(""))) {
            material.setGeneralLevel(selActSuppliesDao.getSuppliesName());
            material.setGeneralTwoLevel("其他");
        } else if ((selActSuppliesDao.getTwoLevel() == null || selActSuppliesDao.getTwoLevel().equals("")) && (selActSuppliesDao.getOneLevel() == null || selActSuppliesDao.getOneLevel().equals(""))) {
            material.setGeneralLevel("其他");
            material.setGeneralTwoLevel("其他");
        } else if ((selActSuppliesDao.getTwoLevel() != null && !selActSuppliesDao.getTwoLevel().equals("")) && (selActSuppliesDao.getOneLevel() != null && !selActSuppliesDao.getOneLevel().equals(""))) {
            SelActSuppliesDao dao = listOne.parallelStream().filter(v -> v.getOneLevel().equals(selActSuppliesDao.getOneLevel())).findFirst().get();
            material.setGeneralLevel(dao.getSuppliesName());
            material.setGeneralTwoLevel(selActSuppliesDao.getSuppliesName());
        }

    }
}
