<template>
  <div class="container">
    <div class="settings-panel">
      <el-divider content-position="left">预处理参数</el-divider>
      <el-form v-model="preprocessingParam" label-position="right" label-width="100px">
        <el-form-item label="区块选择" class="well-param-item">
          <el-select v-model="preprocessingParam.selectedOption" placeholder="请选择区块数据" class="well-param-input"
            @change="handleProjectChange">
            <el-option v-for="item in microSeismicData" :key="item.Project_Name" :label="item.Project_Name"
              :value="item.Project_Name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="能量公式" class="well-param-item">
          <el-input v-model="preprocessingParam.calcMethod" placeholder="能量计算公式" class="well-param-input"
            :controls="false"></el-input>
        </el-form-item>
        <div style="justify-content: center;height: 40px;display: flex;vertical-align: middle;">
          <el-checkbox class="left-label" v-model="preprocessingParam.powerCalculate">指数运算</el-checkbox><el-checkbox
            v-model="preprocessingParam.needCluster">输出聚合数据</el-checkbox>
        </div>
        <el-form-item label="聚合半径" class="well-param-item">
          <el-input-number v-model="preprocessingParam.searchRange" :min="minValue" :max="maxValue" placeholder="聚合半径"
            class="well-param-input" />
        </el-form-item>
        <el-form-item label="网格尺寸" class="well-param-item">
          <el-input-number v-model="preprocessingParam.gridSize" :min="minValue" :max="maxValue" placeholder="网格尺寸"
            class="well-param-input" />
        </el-form-item>
        <el-form-item label="充填值" class="well-param-item">
          <el-input-number v-model="preprocessingParam.fillValue" :min="minValue" :max="maxValue" placeholder="充填值"
            class="well-param-input" />
        </el-form-item>
      </el-form>
      <!-- 网格化算法 -->
      <el-divider content-position="left">网格化计算参数</el-divider>
      <el-form v-model="gridAlgorithmParam" label-position="right" label-width="100px">
        <el-form-item label="网格间隔" class="well-param-item">
          <el-input-number v-model="gridAlgorithmParam.gridStep" :min="minValue" :precision="0" :step="1"
            placeholder="步长" class="well-param-input" />
          <!-- <el-input-number v-model="gridAlgorithmParam.gridStep" :min="minValue" placeholder="步长"
                      style="width: 185px;" :controls="false" /> -->
        </el-form-item>
        <el-form-item label="加密次数" class="well-param-item">
          <el-input-number v-model="gridAlgorithmParam.gridTimes" :min="minValue" :max="maxValue" placeholder="加密次数"
            class="well-param-input" />
        </el-form-item>
        <el-form-item label="平滑" class="well-param-item">
          <el-input-number v-model="gridAlgorithmParam.gridSmooth" :min="minValue" :max="maxValue" placeholder="平滑"
            class="well-param-input" />
        </el-form-item>
        <el-form-item label="等值线步长" class="well-param-item">
          <el-input-number v-model="gridAlgorithmParam.gridCurveSpace" :min="0" placeholder="等值线步长"
            class="well-param-input" />
        </el-form-item>
        <el-form-item label="等值线标注" class="well-param-item">
          <el-input-number v-model="gridAlgorithmParam.gridLabelSpace" :min="minValue" :max="maxValue"
            placeholder="等值线间隔" class="well-param-input" />
        </el-form-item>
        <el-form-item label="网格化算法" class="well-param-item">
          <el-select v-model="gridAlgorithmParam.gridAlgorithm" placeholder="选择网格化算法" class="well-param-input">
            <el-option v-for="item in gridAlgorithmOptions" :key="item.value" :label="item.text"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配色方案" class="well-param-item">
          <el-select v-model="gridAlgorithmParam.gridColor" placeholder="选择配色方案" class="well-param-input">
            <el-option v-for="item in gridColorData" :key="item.Name" :label="item.Name" :value="item.Name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="oper">
        <el-button type="primary" :icon="Finished" @click="handleCalc" :disabled="btnDisabled">网格化计算</el-button>
      </div>
    </div>
  </div>
  <!-- <ProgressBar :is-visible="progressVisible" :progress="currentProgress" :message="progressMessage"
    @hide="progressVisible = false" /> -->
  <ProgressTracker ref="progressRef" v-model="progressVisible" title="计算进度" :initialProgress="currentProgress"
    :message="progressMessage" @complete="onComplete" @manual-close="onManualClose" />
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { fetchBaseMicroSeismic } from '~/services/dataManageService'
import { GetGridColorList, ApplyScatterCalc } from '~/services/microSeismicService'
import { Finished } from "@element-plus/icons-vue";
import { emitter } from "~/utils/eventBus";
import { useSignalR } from "~/composables/useSignalR";
import { EMIT_COMMAND } from '~/utils/commandTypes'

// 消息提示（自动隐藏）
const { $toastMessage } = useNuxtApp();

const { connect, connectionId, sigMsg, sendMessage, on } = useSignalR();

const minValue = 0;
const maxValue = 500;
const btnDisabled = ref(false);
const microSeismicData = ref(null);
const gridColorData = ref([]);
const projId = ref(0);

const progressRef = ref(null);
// 进度条显示状态
const progressVisible = ref(false);
// 当前进度
const currentProgress = ref(0);

// 当前进度的消息
const progressMessage = ref('正在初始化...');
// 任务是否已经开始，用于按钮状态控制、任务状态监听
const taskStarted = ref(false);
// 任务ID
const taskId = ref("");

/** 地震数据预处理参数 */
const preprocessingParam = reactive({
  selectedOption: null,
  powerCalculate: false,
  needCluster: true,
  searchRange: 10,
  gridSize: 50,
  fillValue: 0,
  calcMethod: "10000+1.5*震级",
});

const gridAlgorithmParam = reactive({
  gridNum: 42,
  gridStep: 500,
  gridTimes: 1,
  gridSmooth: 8,
  gridLabelSpace: 10,
  gridCurveSpace: 500,
  gridAlgorithm: "快速网格化",
  gridColor: null,
});

const gridAlgorithmOptions = [
  { text: "快速网格化", value: "快速网格化" },
  { text: "最小张力", value: "最小张力" },
  { text: "反距离加权", value: "反距离加权" },
  { text: "自然临近", value: "自然临近" },
  { text: "最小曲率", value: "最小曲率" },
];

/** 获取区块微地震数据列表数据 */
const loadBaseMicroSeismic = async () => {
  let scattersBaseData = await fetchBaseMicroSeismic();
  if (!scattersBaseData) {
    return;
  }
  microSeismicData.value = scattersBaseData;
};

/** 加载颜色集合 */
const loadGridColorList = async () => {
  try {
    let gridColorList = await GetGridColorList("10000");
    gridColorData.value = gridColorList;
    gridAlgorithmParam.gridColor = gridColorData.value[0].Name;
  } catch (error) {
    console.error("加载配色方案失败:", error);
    this.$message.warning("加载配色方案失败");
  }
};

const handleProjectChange = async (selectedValue) => {
  selectedValue = selectedValue || preprocessingParam.selectedOption;
  if (!selectedValue || selectedValue.trim() === "") {
    $toastMessage.warning("请选择区块数据!");
    return;
  }
  try {
    const response = await fetchGridParamData(selectedValue);
    // 处理API响应
    if (response) {
      // 更新当前网格计算参数
      gridAlgorithmParam.gridNum =
        response.XStep || gridAlgorithmParam.gridNum;
      gridAlgorithmParam.gridStep =
        response.YStep || gridAlgorithmParam.gridStep;

      $toastMessage.success("数据加载成功");
    }
  } catch (error) {
    console.error("API调用失败:", error);
    $toastMessage.error("数据加载失败");
  }
};

// 开始计算
const handleCalc = async () => {
  if (projId.value === 0) {
    $toastMessage.warning("未选择项目！");
    return;
  }

  if (!preprocessingParam.selectedOption) {
    $toastMessage.warning("未选择区块数据！");
    return;
  }

  if (!gridAlgorithmParam.gridAlgorithm) {
    $toastMessage.warning("未选择网格化算法！");
    return;
  }

  if (!gridAlgorithmParam.gridColor) {
    $toastMessage.warning("未选择配色方案！");
    return;
  }

  btnDisabled.value = true;
  progressVisible.value = true;
  try {
    let selectChunk = microSeismicData.value.find(w => w.Project_Name === preprocessingParam.selectedOption);
    const selectParam = {
      Project_Id: projId.value,
      Project_Name: preprocessingParam.selectedOption,
      Well_Name: selectChunk.Well_Name,
      connectionId: connectionId.value,
      preprocessingParam: {
        SearchRange: preprocessingParam.searchRange,
        GridSize: preprocessingParam.gridSize,
        FillValue: preprocessingParam.fillValue,
        NeedCluster: preprocessingParam.needCluster,
        PowerCalculate: preprocessingParam.powerCalculate,
        CalcMethod: preprocessingParam.calcMethod,
      },
      gridAlgorithmParam: {
        GridCount: parseInt(gridAlgorithmParam.gridNum) || 42,
        Times: gridAlgorithmParam.gridTimes,
        Smooth: gridAlgorithmParam.gridSmooth,
        LabelSpace: parseInt(gridAlgorithmParam.gridLabelSpace) || 10,
        CurveSpace: parseInt(gridAlgorithmParam.gridCurveSpace) || 500,
        Algor: gridAlgorithmParam.gridAlgorithm,
        Output: "",
        GridStep: parseInt(gridAlgorithmParam.gridStep) || 500,
        GridColor: gridAlgorithmParam.gridColor,
      },
    };
    let result = await ApplyScatterCalc(selectParam);
    if (!result) {
      $toastMessage.error("数据处理失败！");
      btnDisabled.value = false;
      return;
    }

  } catch (error) {
    console.error("数据处理失败：", error);
    $toastMessage.error("数据处理失败！");
    btnDisabled.value = false;
    return;
  } finally {
    progressVisible.value = false;
  }
};

watchEffect(() => {
  if (!sigMsg.value) {
    return;
  }

  const msg = JSON.parse(sigMsg.value);
  const prog = msg.progress;
  const smsg = msg.msg;

  currentProgress.value = prog;
  progressMessage.value = smsg;

});

const onComplete = async () => {
  btnDisabled.value = false;
  emitter.emit(EMIT_COMMAND.SEISMIC_CALC_FINISHED);
  await loadMicroSeismicResult(currentProject.Id);
};

const onManualClose = () => {
  btnDisabled.value = false;
}

onMounted(async () => {
  await loadBaseMicroSeismic();
  await loadGridColorList();
  listenSeismicParam();
});

const listenSeismicParam = () => {
  emitter.on(EMIT_COMMAND.SEISMIC_PARAM, (data) => {
    projId.value = data.projId;
    if (!checkEmpty(data.params)) {
      preprocessingParam.selectedOption = data.params.Meshing.Project_Name;
      preprocessingParam.powerCalculate = data.params.Pretreatment.PowerCalculate;
      preprocessingParam.needCluster = data.params.Pretreatment.NeedCluster;
      preprocessingParam.searchRange = data.params.Pretreatment.SearchRange;
      preprocessingParam.gridSize = data.params.Pretreatment.GridSize;
      preprocessingParam.fillValue = data.params.Pretreatment.FillValue;

      gridAlgorithmParam.gridNum = data.params.Meshing.GridCount;
      gridAlgorithmParam.gridStep = data.params.Meshing.GridStep;
      gridAlgorithmParam.gridTimes = data.params.Meshing.Times;
      gridAlgorithmParam.gridSmooth = data.params.Meshing.Smooth;
      gridAlgorithmParam.gridLabelSpace = data.params.Meshing.LableSpace;
      gridAlgorithmParam.gridCurveSpace = data.params.Meshing.CurveSpace;
      gridAlgorithmParam.gridAlgorithm = data.params.Meshing.Algor;
      gridAlgorithmParam.gridColor = data.params.Meshing.GridColor || gridColorData.value[0].Name;
    }
  });
};

onUnmounted(() => {
  emitter.off(EMIT_COMMAND.SEISMIC_PARAM);
});

</script>
<style scoped>
.container {
  background: #fff;
  width: 100%;
  /* height: 100%; */
  overflow: hidden;
}

.settings-panel {
  height: 100%;
  overflow-y: auto;
}

.well-param-item {
  height: 30px;
}

.well-param-input {
  width: 180px;
  /* height: 30px; */
}

.oper {
  display: flex;
  bottom: 20px;
  right: 20px;
  position: fixed;
  justify-content: flex-end;
  /* width: 100%; */
  z-index: 3;
}
</style>