<template>
  <div class="XFpdding" style="height: 400px">
    <ul>
      <li
        class="item"
        v-for="(tab, index) in tabslist1"
        :key="index"
        :class="{ active: currentTab1 === index }"
        @click="selectTab1(index)"
      >
        <img :src="tab.imgSrc" style="width: 22px;"/>
        {{ tab.name }}
      </li>
    </ul>
    <!-- 网格文件 -->
    <!-- 执行 -->
    <div
      class="eldesign classtable"
      style="margin-top: 10px;"
      v-show="currentTab1 == '0'"
    >
      <div style="display: flex;flex-direction: column;">
        <el-form-item label="网格文件：" :label-width="formLabelWidth3" style="width: 100%">
          <el-row style="width: 100%">
            <el-col :span="23">
              <el-input
                v-model="adflowvalue.gridfile"
                readonly
                :step="100"
                :min="0"
                :max="1000"
                controls-position="right"
              />
            </el-col>
            <!-- 文件上传按钮部分 -->
            <el-col :span="1" style="display: flex; align-items: center; margin-left: -35px">
              <fileUploads
                :projectId="124" 
                solverType="exampleSolver" 
                accept=".cgns"
                upId="adflow" 
                name="点击选择文件"
                :imgSrc="meshFileImgSrc"
                @upload-success="handleFileUploadSuccess"
                @update-fileName="updateFileName"
                @update-percentage="updatePercentage"
                @upload-status="getUploadStatus"
              />
            </el-col>
          </el-row>
          <!-- 进度条 -->
          <el-row v-if="showProgress" style="width: 100%; margin-top: 10px;">
            <el-col :span="20">
              <el-progress :percentage="percentage"></el-progress>
            </el-col>
            <el-col :span="4">
              <div style="line-height: 15px">{{uploadStatus}}</div>
            </el-col>
            <!-- <el-col :span="2">
              <el-button type="text" @click="fileDel" :icon="Delete" circle style="color: red; padding-bottom:25px;" />
            </el-col> -->
          </el-row>
        </el-form-item>
      <div
        style="flex-grow: 1; height:300px" 
        v-loading="isLoading"
        element-loading-text="拼命加载中...">
        <cloudChart :data="cgnsData" :height=canvasHeight />
      </div>
      </div>
    </div>
    <!-- 来流参数 v-show="currentTab=='0'"-->
    <div v-show="currentTab1 == '1'">
      <div class="eldesign classtable" style="margin-top: 10px">
        <el-table :data="inParams" border style="width: 100%; " :header-cell-class-name="headerCellClassName">
          <el-table-column type="index" width="70" label="编号" />
          <el-table-column prop="name" label="参数名称">
            <!-- <template #default="{ row }">
              <el-input v-model="row.name" @change="handleEdit(row)" />
            </template> -->
          </el-table-column>
          <el-table-column prop="value" label="参数值">
            <template #default="{ row }">
              <el-input v-model="row.value" type="number" />
            </template>
          </el-table-column>
          <el-table-column prop="flag" label="启用" width="100">
            <template v-slot="scope">
              <el-checkbox
                :false-label="0"
                :true-label="1"
                :label="false"
                v-model="scope.row.flag"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 设置参数 -->

    <div
      class="eldesign classtable"
      style="margin-top: 10px; height: 340px;overflow: auto;"
      v-show="currentTab1 == '2'"
    >
      <el-form-item label="分析对象：" :label-width="formLabelWidth1">
        <el-select
          v-model="adflowvalue.proname"
          :suffix-icon="CaretBottom"
          placeholder="请选择"
        >
          <el-option
            v-for="item in objlist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计算进程数：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.countp"
        />
      </el-form-item>
      <el-form-item label="Newton-Krylov求解：" :label-width="formLabelWidth1">
          <el-radio-group v-model="adflowvalue.NewtonKrylov">
            <el-radio :value="1" :label="1">是</el-radio>
            <el-radio :value="0" :label="0">否</el-radio>
          </el-radio-group>  
      </el-form-item>
      <el-form-item label="ANK求解：" :label-width="formLabelWidth1">
          <el-radio-group v-model="adflowvalue.ANK">
            <el-radio :value="1" :label="1">是</el-radio>
            <el-radio :value="0" :label="0">否</el-radio>
          </el-radio-group>  
      </el-form-item>
      <!-- <el-form-item label="工况条件：" :label-width="formLabelWidth1">
        <el-select
          v-model="adflowvalue.proname"
          :suffix-icon="CaretBottom"
          placeholder="请选择"
        >
          <el-option
            v-for="item in wclist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="计算维数：" :label-width="formLabelWidth1">
        <el-select
          v-model="isairfoil"
          :suffix-icon="CaretBottom"
          placeholder="请选择"
          @change="isairfoilChange"
        >
          <el-option
            v-for="item in isairfoilList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="控制方程：" :label-width="formLabelWidth1">
        <el-select
          v-model="equationtype"
          :suffix-icon="CaretBottom"
          placeholder="请选择"
        >
          <el-option
            v-for="item in equationtypelist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="升力定义方向：" :label-width="formLabelWidth1">
        <el-select
          v-model="liftindex"
          :suffix-icon="CaretBottom"
          placeholder="请选择"
        >
          <el-option
            v-for="item in liftindexlist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="特征长度(m)：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.length"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="参考温度(K)：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.temperature"
          :step="1"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="参考面积(m²)：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.area"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="力矩中心(m)：" :label-width="formLabelWidth1">
        <div style="display: flex">
          <el-input
            style="margin-right: 10px"
            v-model="adflowvalue.momx"
            :step="100"
            :min="0"
            :max="1000"
            controls-position="right"
          />
          <el-input
            style="margin-right: 10px"
            v-model="adflowvalue.momy"
            :step="100"
            :min="0"
            :max="1000"
            controls-position="right"
          />
          <el-input
            v-model="adflowvalue.momz"
            :step="100"
            :min="0"
            :max="1000"
            controls-position="right"
          />
        </div>
      </el-form-item>

      <el-form-item label="多重网格：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.mgcycle"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="计算步数：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.ncycles"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="监控变量：" :label-width="formLabelWidth1">
        <el-row>
        <el-col :span="12">
          <el-checkbox v-model="cl" :false-label="0"
          :true-label="1" label="升力系数Cl" style="height: 32px;" />
          <el-checkbox v-model="resrho" :false-label="0"
          :true-label="1" label="密度残差Resrho" style="height: 32px;" />
      
        </el-col>
        <el-col :span="12">
          <el-checkbox v-model="cd" :false-label="0"
          :true-label="1" label="阻力系数Cd" style="height: 32px;" />
          <el-checkbox v-model="cmz" :false-label="0"
          :true-label="1" label="力矩系数Cm" style="height: 32px;" />
        </el-col>
      </el-row>
      </el-form-item>
      <el-form-item label="细网格收敛残差：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.l2convergence"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="粗网格收敛残差：" :label-width="formLabelWidth1">
        <el-input
          v-model="adflowvalue.l2convergencecoarse"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="输出物面信息：" :label-width="formLabelWidth1">
          <el-radio-group v-model="writetecplotsurfacesolution">
            <el-radio :value="1" :label="1">是</el-radio>
            <el-radio :value="0" :label="0">否</el-radio>
          </el-radio-group>  
      </el-form-item>
      <el-form-item label="输出切面信息：" :label-width="formLabelWidth1">
          <el-radio-group v-model="writeslicesolution" @change="writeslicesolutionChange">
            <el-radio :value="1" :label="1">是</el-radio>
            <el-radio :value="0" :label="0">否</el-radio>
          </el-radio-group>  
      </el-form-item>
      <el-form-item v-show="qiemiansetshow" label="切面法相方向：" :label-width="formLabelWidth1">
        <el-select
          v-model="spandirection"
          :suffix-icon="CaretBottom"
          placeholder="请选择"
        >
          <el-option
            v-for="item in spandirectionindexlist"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="qiemiansetshow" label="切面展向位置：" :label-width="formLabelWidth1">
        <el-input
          v-model="slices"
          :step="100"
          :min="0"
          :max="1000"
          controls-position="right"
          placeholder="多个位置以逗号分隔"
        />
      </el-form-item>
    </div>
    <!-- 分析参数 v-show="currentTab=='0'"-->
    <div v-show="currentTab1 == '3'">
      <div class="eldesign classtable" style="margin-top: 10px">
        <el-table :data="outParams" border style="width: 100%; " :header-cell-class-name="headerCellClassName">
          <el-table-column type="index" width="70" label="编号" />
          <el-table-column prop="name" label="参数名称" >
          </el-table-column>
          <el-table-column prop="value" label="参数值">
            <template #default="{ row }">
              <el-input v-model="row.value" type="number" />
            </template>
          </el-table-column>
          <el-table-column prop="flag" label="启用" width="100">
            <template v-slot="scope">
              <el-checkbox
                :false-label="0"
                :true-label="1"
                :label="false"
                v-model="scope.row.flag"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script  setup>
import { ref, onMounted, reactive, provide, nextTick } from "vue"
import { ElMessage, ElButton, ElDialog, ElSelect } from "element-plus"
import { Edit, CaretBottom, Delete } from "@element-plus/icons-vue"
import { request, uploadFile } from "@/utils/request"
import emitter from "@/utils/emitter"
import fileUploads from "../components/fileuploads.vue";
import meshFile from "@/assets/img/meshFile.png";
import inputParams from "@/assets/img/inputParams.png";
import configParams from "@/assets/img/configParams.png";
import analysisParams from "@/assets/img/analysisParams.png";
import { da } from "element-plus/es/locale/index.mjs";
import cloudChart from "../threejsView/index.vue" // 云图
const meshFileImgSrc = new URL("@/assets/img/open.png", import.meta.url).href;
let canvasHeight = ref("300px")
let isLoading = ref(false); // 控制 loading 状态
let cgnsData = ref()
let meshFileName = ref('');
let percentage = ref(0);
let uploadStatus = ref('');
let isUploadSuccess = ref(true);
let formLabelWidth3 = ref(120)
let formLabelWidth1 = ref(180)
let formLabelWidth200 = ref(200)
let currentTab1 = ref(0)
let pid = ref()
let wid = ref()
let adid = ref()
let resrho = ref(1)
let cl = ref(1)
let cd = ref(1)
let cmz = ref(1)
let writetecplotsurfacesolution = ref(1)
let spandirection = ref('x')
let slices = ref("")
let writeslicesolution = ref(1)
let equationtype = ref("RANS")
let equationtypelist = ref([
  { label: "RANS", value: "RANS" },
  { label: "Euler", value: "Euler" }
])
let isairfoil = ref(1)
let isairfoilList = ref([
  { label: "二维", value: 1 },
  { label: "三维", value: 0 }
])
let liftindex = ref(1)
let liftindexlist = ref([
  { label: "x", value: 1 },
  { label: "y", value: 2 },
  { label: "z", value: 3 }
])
let spandirectionindexlist = ref([
  { label: "x", value: 'x' },
  { label: "y", value: 'y' },
  { label: "z", value: 'z' }
])
let inParams = ref([
  {
    code: "mach",
    value: 0.734,
    name: "马赫数Ma",
    type: 1,
    flag: 1
  },
  {
    code: "reynolds",
    value: 6.5e6,
    name: "雷诺数Re",
    type: 1,
    flag: 1
  },
  {
    code: "alpha",
    value: 2.66482,
    name: "攻角AoA",
    type: 1,
    flag: 1
  },
])

let outParams = ref([
  {
    code: "cl",
    value: "0.0",
    name: "升力系数Cl",
    type: 2,
    flag: 1
  },
  {
    code: "cd",
    value: "0.0",
    name: "阻力系数Cd",
    type: 2,
    flag: 1
  },
  {
    code: "cmz",
    value: "0.0",
    name: "力矩系数CmZ",
    type: 2,
    flag: 1
  },
  {
    code: " ",
    value: "0.0",
    name: "体积",
    type: 2,
    flag: 1
  }
])

let outParams1 = ref([
  {
    code: "cl",
    value: "0.0",
    name: "升力系数Cl",
    type: 2,
    flag: 1
  },
  {
    code: "cd",
    value: "0.0",
    name: "阻力系数Cd",
    type: 2,
    flag: 1
  },
  {
    code: "cmz",
    value: "0.0",
    name: "力矩系数CmZ",
    type: 2,
    flag: 1
  },
  {
    code: " ",
    value: "0.0",
    name: "体积",
    type: 2,
    flag: 1
  }
])

let outParams2 = ref([
  {
    code: "cl",
    value: "0.0",
    name: "升力系数Cl",
    type: 2,
    flag: 1
  },
  {
    code: "cd",
    value: "0.0",
    name: "阻力系数Cd",
    type: 2,
    flag: 1
  },
  {
    code: "cmx",
    value: "0.0",
    name: "力矩系数CmX",
    type: 2,
    flag: 1
  },
  {
    code: "cmy",
    value: "0.0",
    name: "力矩系数CmY",
    type: 2,
    flag: 1
  },
  {
    code: "cmz",
    value: "0.0",
    name: "力矩系数CmZ",
    type: 2,
    flag: 1
  },
  {
    code: " ",
    value: "0.0",
    name: "体积",
    type: 2,
    flag: 1
  }
])

let adflowvalue = ref({
  gridfile: "",
  fid:'',
  
  countp:'1',
  NewtonKrylov:1,
  ANK:1,
  proname: "CRM",
  temperature: '288.15',
  length: 1,
  area: 1,
  momx: 0.25,
  momy: 0,
  momz: 0,
  mgcycle: "sg",
  ncycles: 500,
  l2convergence: 1.0e-5,
  l2convergencecoarse: 1.0e-4,
})


let objlist = ref([
  {label:'CRM' , value:'CRM'},
])


let wclist = ref([{ label: "巡航工况", value: "cruise" }])
let tabslist1 = ref([
  { id: "0", name: "网格文件", imgSrc: meshFile },
  { id: "1", name: "来流参数", imgSrc: inputParams },
  { id: "2", name: "设置参数", imgSrc: configParams },
  { id: "3", name: "分析参数", imgSrc: analysisParams }
])

let websock = shallowRef(null);
let times = ref({
  lockReconnect: false, //是否真正建立连接
  timeout: 60 * 1000, //30秒一次心跳
  heartBeatInterval: 30 * 1000, // 添加心跳发送间隔(30秒发一次)
  timeoutObj: null, //心跳倒计时
  serverTimeoutObj: null, //
  timeoutnum: null, //断开重连倒计时
})

const selectTab1 = (index) => {
  currentTab1.value = index
}

const headerCellClassName = ({ column }) => {
  // console.log('列：',column.property)
  if (column.property === 'name') {
    console.log('yanse',column.property)
    return 'header-blue';
  } else if (column.property === 'value') {
    return 'header-green';
  } else if (column.property === 'flag') {
    return 'header-yellow';
  }
  return '';
};

let qiemiansetshow = ref(true)
const writeslicesolutionChange = (value) => {
  if (value === 1) {
    qiemiansetshow.value = true
  } else {
    qiemiansetshow.value = false
  } 
}


const isairfoilChange = (value) => {
  if (value === 1) {
    outParams.value = outParams1.value
  } else {
    outParams.value = outParams2.value
 }
}

const convertToStringArray = (result, Data) => {
  console.log("Data:", Data)

  // 安全检查 Data，确保它是一个数组
  if (!Array.isArray(Data)) {
    console.error("Data should be an array")
    return result // 返回原 result 或者根据需要返回其他默认值
  }

  result = Data.map((row) => {
    // 获取每一行的 `code`, `name`, `value` 和 `flag`
    const code = row.code || " "
    const name = row.name || " "
    const value =
      row.value === null || row.value === undefined || row.value === ""
        ? " "
        : row.value
    const flag =
      row.flag === null || row.flag === undefined // 仅在 null 或 undefined 时替换为空格
        ? " "
        : row.flag

    // 将字段连接为一个以逗号分隔的字符串
    return `${code},${name},${value},${flag}`
  }).join(";") // 每行之间用分号分隔

  return result
}

const getadflow = (id,nowid) => {
  pid.value = id;
  if(nowid){
    wid.value = nowid;
  }
  console.log('getadflow:',pid.value,wid.value)
  const params = {
    transCode: "MDO0049",
    pid: pid.value,
    wid: wid.value
  }
  request(params)
    .then((res) => {
      if (res.hasOwnProperty("adid")) {
        getadflowAssign(res);
        writeslicesolutionChange(writeslicesolution.value);
        console.log('adid flow:',adid.value)
        emitter.emit("adidFromadflow", adid);
        // 默认加载cgns文件
        openWebSocket(res.fid);
      }
    })
    .catch((err) => {
      ElMessage.error('ADflow初始化失败')
    })
}

const getadflowAssign = (data) => {
  pid.value = data.pid
  adid.value = data.adid
  adflowvalue.value.gridfile = data.gridfile
  adflowvalue.value.fid = data.fid
  adflowvalue.value.proname = data.proname
  isairfoil.value = data.isairfoil
  writetecplotsurfacesolution.value = data.writetecplotsurfacesolution
  equationtype.value = data.equationtype
  liftindex.value = data.liftindex
  adflowvalue.value.temperature = data.temperature
  adflowvalue.value.cl = data.cl
  adflowvalue.value.cd = data.cd
  adflowvalue.value.cmz = data.cmz
  adflowvalue.value.resrho = data.resrho
  adflowvalue.value.length = data.length
  adflowvalue.value.area = data.area
  adflowvalue.value.momx = data.momx
  adflowvalue.value.momy = data.momy
  adflowvalue.value.momz = data.momz
  adflowvalue.value.mgcycle = data.mgcycle
  adflowvalue.value.ncycles = data.ncycles
  adflowvalue.value.l2convergence = data.l2convergence
  adflowvalue.value.l2convergencecoarse = data.l2convergencecoarse
  inParams.value = data.inParams
  outParams.value = data.outParams
  writeslicesolution.value = data.writeslicesolution
  spandirection.value = data.spandirection
  slices.value = data.slices
}

const getadflowsave = (id,nowid) => {
  if(nowid){
    wid.value = nowid
  }
  pid.value = id;
  const params = {
    transCode: "MDO0050",
    pid: pid.value,
    wid: wid.value,
    gridfile: adflowvalue.value.gridfile,
    fid: adflowvalue.value.fid,
    proname: adflowvalue.value.proname,
    isairfoil: isairfoil.value,
    writetecplotsurfacesolution: writetecplotsurfacesolution.value,
    equationtype: equationtype.value,
    liftindex: liftindex.value,
    temperature: adflowvalue.value.temperature,
    cl:cl.value,
    resrho:resrho.value,
    cd:cd.value,
    cmz:cmz.value,
    length: adflowvalue.value.length,
    area: adflowvalue.value.area,
    momx: adflowvalue.value.momx,
    momy: adflowvalue.value.momy,
    momz: adflowvalue.value.momz,
    mgcycle: adflowvalue.value.mgcycle,
    ncycles: adflowvalue.value.ncycles,
    l2convergence: adflowvalue.value.l2convergence,
    l2convergencecoarse: adflowvalue.value.l2convergencecoarse,
    writeslicesolution: writeslicesolution.value,
    spandirection: spandirection.value,
    slices: slices.value,
    checked: 1,
    inParams: convertToStringArray([], inParams.value),
    outParams: convertToStringArray([], outParams.value)
  }
  request(params)
    .then((res) => {
      ElMessage({
        message: '保存成功',
        type: "success"
      })
      getadflow(pid.value, wid.value);
    })
    .catch((err) => {
      ElMessage.error('保存失败')
    })
}
// 更新文件名
const updateFileName = (newValue) => {
  meshFileName.value = newValue
}

// 更新进度条
const updatePercentage = (newValue) => {
  percentage.value = newValue
}

// 控制进度条显隐
const showProgress = computed(() => percentage.value > 0 && percentage.value <= 100);

const fetchCgnsData = async (fpid) =>{
  isLoading.value = true;
  try {
    const response = await fetch('https://www.adicn.com/airopt/TransServlet', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        channelNo: 'service',
        clientToken: 'e47b87eec69545559d1e81e56626da68',
        transCode: 'MDO0061',
        userId: '5f06c8bc77234f969d13e160b54c27e3',
        fid: fpid
      }),
    });
  }catch (error) {
    isLoading.value = false;
    console.error("请求失败:", error.response || error);
  }
}

function getUrl(channelNo = 'service') {
  let url = ''
  if (channelNo == 'service') {
    url = '/TransServlet'
  } else if (channelNo == 'manager') {
    url = '/managersvr/TransServlet'
  }
  return url
}

const getCgnsData = async (fpid) =>{

  let url = import.meta.env.VITE_BASE_URL + getUrl();
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        channelNo: 'service',
        clientToken: 'e47b87eec69545559d1e81e56626da68',
        transCode: 'MDO0062',
        userId: '5f06c8bc77234f969d13e160b54c27e3',
        fid: fpid
      }),
    });
    // 解析 JSON 数据
  const data = await response.json(); //
  console.log('接口返回的数据:', data); // 正确打印数据
  cgnsData.value = data;
  isLoading.value = false;
  }catch (error) {
    isLoading.value = false;
    console.error("请求失败:", error.response || error);
  }
}

//websockct的连接
const openWebSocket = (fid) => {
  if (websock.value?.readyState === 1) return; // 避免重复创建
  const wsurl = import.meta.env.VITE_WEBSOCKET_URL + fid;
  const ws = new WebSocket(wsurl);
  websock.value = ws;
  ws.onopen = websocketonopen;
  ws.onmessage = websocketonmessage;
  ws.onerror = websocketonerror;
  ws.onclose = websocketclose;
}

// Websoket连接成功事件
const websocketonopen = (res) => {
  console.log("cgnsWebSocket连接成功", res);
  // 开启心跳
  start();
  // 调用文件解析
  fetchCgnsData(adflowvalue.value.fid);
};

// Websoket接收消息事件
const websocketonmessage = (res) => {
  try {
    const receivedData = JSON.parse(res.data);
    if (receivedData.status === 0) {
      console.log("转换成功，准备关闭");
      
      // 1. 清除所有计时器
      clearAllTimers();
      
      // 2. 解除事件监听
      websock.value.onclose = null;
      websock.value.onerror = null;
      
      // 3. 主动关闭（code 1000）
      websock.value.close(1000, "Normal closure");
      
      // 4. 置空引用
      websock.value = null;
      
      // 5. 获取数据
      getCgnsData(adflowvalue.value.fid);
      return; // 直接返回
    }
  } catch (e) {
    // 非JSON消息（如连接成功的文本提示或心跳回复）
    if (res.data === "建立服务端连接成功！") {
      console.log("WebSocket连接已建立");
    } 
    else if (res.data === "服务端已经接收到消息，msg=heartCheck") {
      console.log("心跳确认");
    }
    else {
      console.warn("未知的非JSON消息:", res.data);
    }
  }
  reset();
};

// Websoket连接错误事件
const websocketonerror = (res) => {
  console.log("连接错误", res);
  websock.close();
  reconnect();
};
// Websoket断开事件
const websocketclose = (res) => {
  console.log("断开连接", res);
  // 只有当非正常关闭时才重连（code 1000=正常关闭）
  if (res.code !== 1000) {
    reconnect();
  }
};

// 心跳包
const reconnect = () => {
  // 增加多个防护条件
  if (
    times.value.lockReconnect ||
    websock.value?.readyState === 1 ||
    !adflowvalue.value?.fid
  ) return;

  console.log("尝试重连...");
  times.value.lockReconnect = true;
  
  clearTimeout(times.value.timeoutnum);
  times.value.timeoutnum = setTimeout(() => {
    if (!websock.value || websock.value?.readyState > 1) {
      openWebSocket(adflowvalue.value.fid);
    }
    times.value.lockReconnect = false;
  }, 10000);
};

const reset = () => {
  //重置心跳
  clearTimeout(times.value.timeoutObj);
  clearTimeout(times.value.serverTimeoutObj);
  start();
}

const start = () => {
  clearTimeout(times.value.timeoutObj);
  clearTimeout(times.value.serverTimeoutObj);
  
  // 增加连接状态检查
  if (!websock.value || websock.value.readyState !== 1) return;
  
  times.value.timeoutObj = setTimeout(() => {
    if (websock.value?.readyState === 1) {
      websock.value.send("heartCheck");
      
      times.value.serverTimeoutObj = setTimeout(() => {
        if (websock.value?.readyState === 1) {
          websock.value.close(1006, "Heartbeat timeout");
        }
      }, times.value.timeout);
    }
  }, times.value.heartBeatInterval);
}

const clearAllTimers = () => {
  clearTimeout(times.value.timeoutObj);
  clearTimeout(times.value.serverTimeoutObj);
  clearTimeout(times.value.timeoutnum);
  times.value.lockReconnect = true; // 永久锁定重连
};

// 处理上传成功后的逻辑
const handleFileUploadSuccess = (newValue) => {
  //隐藏进度条
  setTimeout(() => {
    percentage.value = 0;
  }, 1000);

  adflowvalue.value.gridfile = newValue.fname;
  adflowvalue.value.fid = newValue.bfid;
  console.log("文件上传成功，bfid:", newValue.bfid, "fname:", newValue.fname)
  // 开启websocket
  openWebSocket(newValue.bfid);
}

// 更新上传状态
const getUploadStatus = (newValue) => {
  uploadStatus.value = newValue
}

const fileDel = () => {
}

// onMounted(() => {
//   emitter.on("requestGetadid", getadflow); // 监听事件
// });

// onUnmounted(() => {
//   emitter.off("requestGetadid", getadflow); // 解绑事件
// });



defineExpose({
  getadflow,
  getadflowAssign,
  getadflowsave
})
</script>


