<template>
  <div>
    <div class="upload-btn">
      <el-button type="primary" @click="handleVoyage">关联航次</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="voyage_name" label="航次名称" />
      <el-table-column prop="diving_sn" label="潜次号" />
      <el-table-column prop="dataset_name" label="样品集名称" />
      <el-table-column prop="sample_name" label="样品名称" />
      <el-table-column prop="conver_area" label="覆盖面积" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="是否确认删除?"
              @confirm="handleDelete(scope.row.tsy_id)"
          >
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" title="关联航次" width="600">
      <el-cascader
          v-model="selectedValues"
          :options="cascadeData"
          :props="{ expandTrigger: 'hover' }"
          @change="handleChange"
          style="width: 100%;"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {getParam, sampleAdd, sampleDelete, sampleList, voyageReg} from "@/api/task.js"
import {InfoFilled} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

const dialogFormVisible = ref(false)
const props = defineProps({
  rescueId: {
    type: String, // 根据实际情况定义类型
    default: ''
  }
})

const VoyageSocketUrl = ref('')

// 获取系统参数列表
const getParamsList = () => {
  // 判断当前环境
  if (import.meta.env.VITE_APP_ENV === 'development') {
    // 开发环境：直接使用环境变量中的值
    VoyageSocketUrl.value = import.meta.env.VITE_APP_DS_API
    voyageList()
  } else {
    // 生产环境：通过接口获取参数
    getParam().then(res => {
      const data = res.array.find(item => item.param_name === 'VoyageSocketUrl')

      if (data?.param_value) {
        VoyageSocketUrl.value = data.param_value
      } else {
        // 备用方案：基于当前窗口位置构建URL[1](@ref)
        VoyageSocketUrl.value = `${window.location.protocol}//${window.location.hostname}:${window.location.port}/ds/`
      }

      voyageList()
    })
  }
}

const entity = ref()
const allVoyage = ref()
const tableData = ref([])
// 获取所有航次列表数据
const voyageList = () => {
  voyageReg({ baseURL: VoyageSocketUrl.value }).then(res => {
    entity.value = res.entity
    allVoyage.value = res.entity.VoyageArray
    cascadeData.value = convertToCascadeData(res.entity)
  })
}

// 查询已关联航次数据
const dataList = () => {
  sampleList({ rescue_id: props.rescueId }).then(res => {
    tableData.value = res.array
  })
}

// 添加
const handleVoyage = () => {
  dialogFormVisible.value = true
}

// 删除
const handleDelete = (id) => {
  sampleDelete({ tsy_id: id }).then(() => {
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    dataList()
  })
}

const selectedValues = ref('')
const cascadeData = ref([])
// 处理航次数据
const convertToCascadeData = (entity) => {
  const cascadeData = [];

  // 处理一级数据：VoyageArray
  if (entity.VoyageArray && Array.isArray(entity.VoyageArray)) {
    entity.VoyageArray.forEach(voyage => {
      const voyageName = voyage.voyage_name;

      // 创建一级选项
      const firstLevelItem = {
        value: voyageName,
        label: `${voyageName} (${voyage.ship_name})`,
        children: []
      };

      // 处理二级数据：对应voyage_name下的数据集
      if (entity[voyageName] && Array.isArray(entity[voyageName])) {
        entity[voyageName].forEach(dataset => {
          const secondLevelItem = {
            value: dataset.dataset_id.toString(),
            label: dataset.dataset_name
          };
          firstLevelItem.children.push(secondLevelItem);
        });
      }

      cascadeData.push(firstLevelItem);
    });
  }

  return cascadeData;
}

const selectedDataset = ref('')

// 选择样品数据
const handleChange = (value) => {
  if (value && value.length === 2) {
    const [voyageName, datasetId] = value;
    selectedDataset.value = findDatasetById(entity.value, voyageName, datasetId);
  }
}

// 查找原始数据获取完整对象
const findDatasetById = (entity, voyageName, datasetId) => {
  if (!entity[voyageName]) return null;

  return entity[voyageName].find(dataset =>
      dataset.dataset_id.toString() === datasetId.toString()
  )
}

// 提交
const onConfirm = () => {
  if (selectedDataset.value) {
    selectedDataset.value.rescue_id = props.rescueId
    sampleAdd(selectedDataset.value).then(() => {
      ElMessage({
        message: '操作成功',
        type: 'success'
      })
      dataList()
      dialogFormVisible.value = false
      selectedValues.value = ''
      selectedDataset.value = null
    })
  }
}

onMounted(() => {
  if (props.rescueId) {
    getParamsList()
    dataList()
  }
})
</script>

<style scoped lang="scss">
.upload-btn {
  text-align: right;
  margin-bottom: 20px;
}
</style>
