package com.hdkj.lt.bf.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.lt.bf.entity.*;
import com.hdkj.lt.bf.mapper.FhzgElectricalModelSectionMapper;
import com.hdkj.lt.bf.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【fhzg_electrical_model_section(配网电气模型-断面基本信息)】的数据库操作Service实现
 * @createDate 2026-05-28 10:15:41
 */
@Slf4j
@Service
public class FhzgElectricalModelSectionServiceImpl extends ServiceImpl<FhzgElectricalModelSectionMapper, FhzgElectricalModelSection>
    implements FhzgElectricalModelSectionService {

    @Autowired
    private FhzgElectricalModelNodeService nodeService;
    @Autowired
    private FhzgElectricalModelConductorService conductorService;
    @Autowired
    private FhzgElectricalModelTransformerService transformerService;
    @Autowired
    private FhzgElectricalModelSwitchService switchService;
    @Autowired
    private FhzgElectricalModelInjectionService injectionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFromJson(String jsonStr) {
        JSONObject root = JSON.parseObject(jsonStr);

        // 1. 解析并保存断面基本信息
        JSONObject sectionJson = root.getJSONObject("section_info");
        if (sectionJson == null) {
            log.warn("配网电气模型JSON中缺少section_info");
            return;
        }
        FhzgElectricalModelSection section = parseSection(sectionJson);
        this.save(section);
        String sectionId = section.getSectionId();
        log.info("配网电气模型断面保存成功, sectionId={}", sectionId);
        // 2. 解析data_objects
        JSONObject dataObjects = root.getJSONObject("data_objects");
        if (dataObjects == null) {
            log.warn("配网电气模型JSON中缺少data_objects");
            return;
        }
        // 3. 保存节点
        List<FhzgElectricalModelNode> nodes = parseNodes(dataObjects.getJSONArray("nodes"), sectionId);
        if (CollUtil.isNotEmpty(nodes)) {
            nodeService.saveBatch(nodes, 500);
            log.info("保存节点 {} 条", nodes.size());
        }
        // 4. 保存导线段
        List<FhzgElectricalModelConductor> conductors = parseConductors(dataObjects.getJSONArray("conductors"), sectionId);
        if (CollUtil.isNotEmpty(conductors)) {
            conductorService.saveBatch(conductors, 500);
            log.info("保存导线段 {} 条", conductors.size());
        }
        // 5. 保存配电变压器
        List<FhzgElectricalModelTransformer> transformers = parseTransformers(dataObjects.getJSONArray("transformers"), sectionId);
        if (CollUtil.isNotEmpty(transformers)) {
            transformerService.saveBatch(transformers, 500);
            log.info("保存配电变压器 {} 条", transformers.size());
        }
        // 6. 保存开关设备
        List<FhzgElectricalModelSwitch> switches = parseSwitches(dataObjects.getJSONArray("switches"), sectionId);
        if (CollUtil.isNotEmpty(switches)) {
            switchService.saveBatch(switches, 500);
            log.info("保存开关设备 {} 条", switches.size());
        }
        // 7. 保存注入设备
        List<FhzgElectricalModelInjection> injections = parseInjections(dataObjects.getJSONArray("injection_devices"), sectionId);
        if (CollUtil.isNotEmpty(injections)) {
            injectionService.saveBatch(injections, 500);
            log.info("保存注入设备 {} 条", injections.size());
        }
    }








    // ==================== 手动映射方法 ====================

    private FhzgElectricalModelSection parseSection(JSONObject json) {
        FhzgElectricalModelSection s = new FhzgElectricalModelSection();
        s.setSectionId(json.getString("id"));       // JSON id → entity sectionId
        s.setFeederId(json.getString("feeder_id"));
        s.setName(json.getString("name"));
        s.setBaseKv(json.getBigDecimal("base_kv"));
        s.setBaseKva(json.getBigDecimal("base_kva"));
        // time 字段为空字符串时设为null
        String time = json.getString("time");
        if (StrUtil.isNotBlank(time)) {
            s.setTime(json.getDate("time"));
        }
        return s;
    }

    private List<FhzgElectricalModelNode> parseNodes(JSONArray arr, String sectionId) {
        if (arr == null) return new ArrayList<>();
        List<FhzgElectricalModelNode> list = new ArrayList<>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject j = arr.getJSONObject(i);
            FhzgElectricalModelNode e = new FhzgElectricalModelNode();
            e.setNodeId(j.getString("id"));          // JSON id → entity nodeId
            e.setSectionId(sectionId);
            e.setName(j.getString("name"));
            e.setVoltageLevelKv(j.getBigDecimal("voltage_level_kv"));
            e.setGShuntPu(j.getBigDecimal("g_shunt_pu"));
            e.setBShuntPu(j.getBigDecimal("b_shunt_pu"));
            e.setIsActive(boolToInt(j.getBooleanValue("is_active")));
            e.setType(j.getInteger("type"));
            e.setVmPu(j.getBigDecimal("vm_pu"));
            e.setVaDeg(j.getBigDecimal("va_deg"));
            e.setPInjPu(j.getBigDecimal("p_inj_pu"));
            e.setQInjPu(j.getBigDecimal("q_inj_pu"));
            e.setFeederId(j.getString("feeder_id"));
            e.setRole(j.getString("role"));
            e.setPsrType(j.getString("psr_type"));
            e.setPsrId(j.getString("psr_id"));
            list.add(e);
        }
        return list;
    }

    private List<FhzgElectricalModelConductor> parseConductors(JSONArray arr, String sectionId) {
        if (arr == null) return new ArrayList<>();
        List<FhzgElectricalModelConductor> list = new ArrayList<>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject j = arr.getJSONObject(i);
            FhzgElectricalModelConductor e = new FhzgElectricalModelConductor();
            e.setConductorId(j.getString("id"));     // JSON id → entity conductorId
            e.setSectionId(sectionId);
            e.setName(j.getString("name"));
            e.setRPu(j.getBigDecimal("r_pu"));
            e.setXPu(j.getBigDecimal("x_pu"));
            e.setBPu(j.getBigDecimal("b_pu"));
            e.setIsActive(boolToInt(j.getBooleanValue("is_active")));
            e.setFbusId(j.getString("fbus_id"));
            e.setTbusId(j.getString("tbus_id"));
            e.setLengthM(j.getBigDecimal("length_m"));
            e.setFeederId(j.getString("feeder_id"));
            e.setRole(j.getInteger("role"));
            e.setPsrType(j.getString("psr_type"));
            e.setPsrId(j.getString("psr_id"));
            e.setIMag(j.getBigDecimal("i_mag"));
            e.setPFromPu(j.getBigDecimal("p_from_pu"));
            e.setQFromPu(j.getBigDecimal("q_from_pu"));
            e.setPToPu(j.getBigDecimal("p_to_pu"));
            e.setQToPu(j.getBigDecimal("q_to_pu"));
            list.add(e);
        }
        return list;
    }

    private List<FhzgElectricalModelTransformer> parseTransformers(JSONArray arr, String sectionId) {
        if (arr == null) return new ArrayList<>();
        List<FhzgElectricalModelTransformer> list = new ArrayList<>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject j = arr.getJSONObject(i);
            FhzgElectricalModelTransformer e = new FhzgElectricalModelTransformer();
            e.setTransformerId(j.getString("id"));   // JSON id → entity transformerId
            e.setSectionId(sectionId);
            e.setName(j.getString("name"));
            e.setRPu(j.getBigDecimal("r_pu"));
            e.setXPu(j.getBigDecimal("x_pu"));
            e.setBPu(j.getBigDecimal("b_pu"));
            e.setIsActive(boolToInt(j.getBooleanValue("is_active")));
            e.setFbusId(j.getString("fbus_id"));
            e.setTbusId(j.getString("tbus_id"));
            e.setRatioPu(j.getBigDecimal("ratio_pu"));
            e.setAngleDeg(j.getBigDecimal("angle_deg"));
            e.setRateCapacityKva(j.getBigDecimal("rate_capacity_kva"));
            e.setFeederId(j.getString("feeder_id"));
            e.setPsrType(j.getString("psr_type"));
            e.setPsrId(j.getString("psr_id"));
            e.setIMag(j.getBigDecimal("i_mag"));
            e.setPFromPu(j.getBigDecimal("p_from_pu"));
            e.setQFromPu(j.getBigDecimal("q_from_pu"));
            e.setPToPu(j.getBigDecimal("p_to_pu"));
            e.setQToPu(j.getBigDecimal("q_to_pu"));
            list.add(e);
        }
        return list;
    }

    private List<FhzgElectricalModelSwitch> parseSwitches(JSONArray arr, String sectionId) {
        if (arr == null) return new ArrayList<>();
        List<FhzgElectricalModelSwitch> list = new ArrayList<>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject j = arr.getJSONObject(i);
            FhzgElectricalModelSwitch e = new FhzgElectricalModelSwitch();
            e.setSwitchId(j.getString("id"));         // JSON id → entity switchId
            e.setSectionId(sectionId);
            e.setName(j.getString("name"));
            e.setFbusId(j.getString("fbus_id"));
            e.setTbusId(j.getString("tbus_id"));
            e.setBranchId(j.getString("branch_id"));
            e.setStatus(j.getInteger("status"));
            e.setMeasurable(boolToInt(j.getBooleanValue("measurable")));
            e.setControllable(boolToInt(j.getBooleanValue("controllable")));
            e.setFeederId(j.getString("feeder_id"));
            e.setPsrType(j.getString("psr_type"));
            e.setPsrId(j.getString("psr_id"));
            e.setIMag(j.getBigDecimal("i_mag"));
            e.setPFromPu(j.getBigDecimal("p_from_pu"));
            e.setQFromPu(j.getBigDecimal("q_from_pu"));
            e.setPToPu(j.getBigDecimal("p_to_pu"));
            e.setQToPu(j.getBigDecimal("q_to_pu"));
            list.add(e);
        }
        return list;
    }

    private List<FhzgElectricalModelInjection> parseInjections(JSONArray arr, String sectionId) {
        if (arr == null) return new ArrayList<>();
        List<FhzgElectricalModelInjection> list = new ArrayList<>();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject j = arr.getJSONObject(i);
            FhzgElectricalModelInjection e = new FhzgElectricalModelInjection();
            e.setInjectionId(j.getString("id"));      // JSON id → entity injectionId
            e.setSectionId(sectionId);
            e.setName(j.getString("name"));
            e.setBusId(j.getString("bus_id"));
            e.setInjectionType(j.getInteger("type")); // JSON type → entity injectionType
            e.setIsActive(boolToInt(j.getBooleanValue("is_active")));
            e.setControlMode(j.getInteger("control_mode"));
            e.setVmPu(j.getBigDecimal("vm_pu"));
            e.setPInjPu(j.getBigDecimal("p_inj_pu"));
            e.setQInjPu(j.getBigDecimal("q_inj_pu"));
            e.setFeederId(j.getString("feeder_id"));
            list.add(e);
        }
        return list;
    }

    /**
     * boolean → Integer (true→1, false→0)
     */
    private Integer boolToInt(Boolean val) {
        return val != null && val ? 1 : 0;
    }
}
