package com.hdkj.lt.core.sys.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.lt.base.constants.DictConstants;
import com.hdkj.lt.core.bizms.modle.dto.FhzgSwitchProtectionSettingsBaseReadExcelConfig;
import com.hdkj.lt.core.bizms.modle.po.FhzgSwitchProtectionSettings;
import com.hdkj.lt.core.bizms.mp.ArgTableNameHandler;
import com.hdkj.lt.core.sys.dao.FhzgOrganSuffixMapper;
import com.hdkj.lt.core.sys.dao.SwitchProtectionSettingsMapper;
import com.hdkj.lt.core.sys.service.SwitchProtectionSettingsService;
import com.hdkj.lt.utils.poi.ExcelReadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zhangtj
* @description 针对表【fhzg_switch_protection_settings(开关设备保护定值表)】的数据库操作Service实现
* @createDate 2025-05-24 18:25:11
*/
@Service
@Slf4j
public class SwitchProtectionSettingsServiceImpl extends ServiceImpl<SwitchProtectionSettingsMapper, FhzgSwitchProtectionSettings>
    implements SwitchProtectionSettingsService {

    @Autowired
    FhzgOrganSuffixMapper fhzgOrganSuffixMapper;


    /**
     *
     * @author luorui
     * @date 2025/6/16 14:12
     * @discription  保护定值数据导入
     *
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void importData(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            JSONObject jsonObject = ExcelReadUtils.readExcel(inputStream, fileName, FhzgSwitchProtectionSettingsBaseReadExcelConfig.class);
            JSONArray array =  (JSONArray)jsonObject.get(FhzgSwitchProtectionSettingsBaseReadExcelConfig.SHEET_NAME);
            List<FhzgSwitchProtectionSettings> list = array.toJavaList(FhzgSwitchProtectionSettings.class);
            list.forEach(e -> {
                e.setCreateTime(new Date());
                e.setCreator(8L);
            });
            this.saveBatch(list);
            List<String> parentLineNameList =  list.stream().map(FhzgSwitchProtectionSettings::getParentLineName).collect(Collectors.toList());
            //补全线路psrId
            int countParentLinePsrId = baseMapper.updateParentLinePsrId(parentLineNameList);
            //补全开关psrId
            List<String> deviceNameList =  list.stream().map(FhzgSwitchProtectionSettings::getDeviceName).collect(Collectors.toList());
            //动态切换表名
            final int[] countDevicePrsId = {0};
            List<Map<String, Object>> organSuffixList = fhzgOrganSuffixMapper.getOrganSuffixList(deviceNameList);
            Map<String, List<String>> suffixs = organSuffixList.stream().collect(Collectors.groupingBy(
                    e -> String.valueOf(e.get("tab_suffix")), Collectors.mapping(e ->  String.valueOf(e.get("name")), Collectors.toList())));
            suffixs.forEach((key,val)-> {
                Integer integer = ArgTableNameHandler.setArgumentFunc(key, arg -> baseMapper.updatedDevicePrsId(arg, Arrays.asList(DictConstants.KG_PSR_TYPE.split(","))), val);
                countDevicePrsId[0] = countDevicePrsId[0] + integer.intValue();
            });
            //删除重复数据
            int countRepeated =baseMapper.deleteRepeated();
            log.info("导入保护定值数据完成，新增数据：{}条，更新线路Id：{}条，更新开关Id：{}条，删除重复开关id数据：{}条",list.size(), countParentLinePsrId, countDevicePrsId[0], countRepeated);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateBatchByPrsId(List<FhzgSwitchProtectionSettings> list) {
        baseMapper.updateBatchByPrsId(list);
    }
}




