<template>
  <!-- 模拟数据弹窗 -->
  <el-dialog
    v-model="visible"
    align-center
    :append-to-body="true"
    width="500"
    class="dialog_class"
    draggable
  >
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">模拟数据</h4>
      </div>
    </template>

    <el-table :data="tableSLData" border height="300" style="width: 100%">
      <el-table-column type="index" width="40" label="" />
      <el-table-column prop="name" label="属性"> </el-table-column>
      <el-table-column prop="value" label="值">
        <template #default="{ row }">
          <el-select
            v-if="row.valueType === 1"
            v-model="row.value"
            placeholder="请选择"
            class="full-width-select"
          >
            <el-option
              v-for="option in row.options"
              :key="option.val"
              :label="option.tag"
              :value="option.val"
            />
          </el-select>
          <el-input
            v-else-if="row.valueType === 2"
            v-model="row.value"
            class="full-width-input"
          />
          <el-button v-else-if="row.valueType === 3" />
          <div v-else>{{ row.valueDef }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="100">
        <template #default="{ row }">
          <el-select
            v-if="row.unitType !== '无'"
            v-model="row.unitDef"
            placeholder="请选择"
            :loading="moreOptionsLoading"
            @focus="fetchUnitsForRow(row)"
            @change="(newUnit) => handleUnitChange(row, newUnit)"
            class="full-width-select"
          >
            <el-option
              v-for="option in row.unitoptions"
              :key="option.utId"
              :label="option.value"
              :value="option.value"
            />
          </el-select>
          <div v-else>{{ row.unitType }}</div>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <span class="lastbtn">
        <el-button @click="closeDialog">{{ $t('dialog.cancel') }}</el-button>
        <el-button type="primary" @click="saveSLTabelDialog">
          {{ $t('dialog.ok') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { request, getImage } from "@/utils/request"
import { ElMessage } from "element-plus"
const visible = ref(false)
const tableSLData = ref([])

const runtype = ref('') // 用于分开不同求解运行

// 单位选项缓存
const unitOptionsCache = ref({});
// 更多选项加载状态
const moreOptionsLoading = ref(false);

let emit = defineEmits(['selectRunType']);

function openDialog(pid) {
  getSLData(pid);
  visible.value = true
}

function closeDialog() {
  visible.value = false
}

// 组件参数点击下拉框调用接口获取单位
const fetchUnitsForRow = async (row) => {
  row.prevUnitDef = row.unitDef || row.unit || "无"
  if (unitOptionsCache.value[row.unitType]) {
    row.unitoptions  = unitOptionsCache.value[row.unitType]
    if (!row.unitDef && row.unitOptions.length > 0) {
      row.unitDef = row.unitOptions[0].value
    }
    return
  }
  moreOptionsLoading.value = true;

  const params = {
    transCode: "ES0019",
    gutId: row.unitType
  }
  try {
    const res = await request(params)
    row.unitoptions  = res.rows || []
    console.log("单位选项获取成功", row.unitoptions );
    
    unitOptionsCache.value[row.unitType] = row.unitoptions 
    if (!row.unitType && row.unitoptions .length > 0) {
      row.unitDef  = row.unitoptions [0].value
    }
    moreOptionsLoading.value = false;
  } catch (err) {
    moreOptionsLoading.value = false;
    ElMessage.error(err.returnMsg || t("error.fetchFailed"))
    row.unitoptions  = []
    unitOptionsCache.value[row.unitType] = []
  } finally {
    moreOptionsLoading.value = false;
  }
}

const handleUnitChange = (row, newUnit) => {
  console.log("handleUnitChange called with row:", row, "and newUnit:", newUnit);
  
  if (!row || !row.value || isNaN(row.value)) {
    ElMessage.warning('请输入有效数值')
    return
  }

  const unitOptions = row.unitoptions
  if (!unitOptions) {
    console.error('单位选项未定义', col || row)
    ElMessage.error('单位选项未定义')
    return
  }

  const currentUnit = unitOptions.find(opt => opt.value === row.prevUnitDef)
  if (!currentUnit) {
    console.error('未找到当前单位信息', row.prevUnitDef)
    ElMessage.error('未找到当前单位信息')
    return
  }

  const targetUnit = unitOptions.find(opt => opt.value === newUnit)
  if (!targetUnit) {
    console.error('未找到目标单位信息', newUnit)
    ElMessage.error('未找到目标单位信息')
    return
  }

  const currentValue = parseFloat(row.value)
  const newValue = ((currentValue - currentUnit.utOffset) / currentUnit.factor) * targetUnit.factor + targetUnit.utOffset
  row.value = newValue.toFixed(6) // 提高精度
  row.unit = newUnit
  if (row) {
    row.prevUnitDef = newUnit
    tableSLData.value = [...tableSLData.value]
  } else {
    row.prevUnitDef = newUnit
  }
}


const getSLData = async ( pid ) => {
  const params = {
    transCode: "ES0012",
    pid: pid
  }

  try {
    const res = await request(params) // 使用 await 等待请求完成
    tableSLData.value = res.rows.map((item) => ({
      ...item,
      isVisible: true, // 默认所有行都可见
      unitDef: item.unit || item.unitDef || ""
    }))
    console.log("tableSLData.value", tableSLData.value)

    // 使用 for...of 循环以便使用 await
    for (const item of tableSLData.value) {
      if (!item.pcaId) continue

      // 并行处理 value 和 unit 的初始化
      const promises = []

      if (item.valueType === 1) {
        promises.push(getlistopt(item, "value"))
      }

      if (item.unitType !== "无") {
        // promises.push(getlistopt(item, "unit"))
      } else {
        item.unit = "无"
      }

      // 等待当前 item 的所有初始化完成
      await Promise.all(promises)
    }

    console.log("所有数据初始化完成")
  } catch (err) {
    console.error("初始化失败:", err)
    ElMessage.error("初始化失败")
  }
}

const saveSLTabelDialog = () => {
  console.log("tableSLData:", tableSLData.value)
  runtype.value = tableSLData.value.find((item)=>item.code === "SimulationType")?.value || '';
  emit('selectRunType',runtype.value);
  // dataType 为 -1 的数据
  const validItems = tableSLData.value.filter((item) => item.dataType === -1)
  const pcavals = validItems
    .map((item) => {
      const pcaId = item.pcaId ?? ""
      const value = item.value ?? ""
      const unit = item.unitDef != '' ? item.unitDef : "无"
      return `${pcaId},${value},${unit}`
    })
    .join(";")
  const params = {
    transCode: "ES0008",
    pcavals: pcavals
  }
  request(params)
    .then((res) => {
      ElMessage.success("保存成功")
      // 执行保存逻辑
      closeDialog()
    })
    .catch((err) => {
      console.error("err", err)
      ElMessage.error("保存失败")
    })
}

const getlistopt = async (item, gettype) => {
  let params = {}
  if (gettype === "value") {
    params = {
      transCode: "BES001",
      type: item.valueDef
    }
  } else {
    params = {
      transCode: "BES001",
      type: item.unitType
    }
  }

  try {
    const res = await request(params)
    // console.log("选项获取成功", res)

    if (gettype === "value") {
      if (
        item.value === undefined ||
        item.value === null ||
        item.value === ""
      ) {
        item.value = res.rows?.[0]?.val ?? ""
      }
      item.options = res.rows || []
    } else if (gettype === "unit") {
      if (item.unit === undefined || item.unit === null || item.unit === "") {
        item.unit = res.rows?.[0]?.val ?? ""
      }
      item.unitoptions = res.rows || []
    }
  } catch (err) {
    console.error("err", err)
    ElMessage.error("选项初始化失败")
  }
}

// 暴露给父组件
defineExpose({ openDialog, closeDialog })
</script>
