<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-form :inline="true" :model="queryForm">
        <el-row>
          <el-form-item label="归属系统A">
            <el-select v-model="queryForm.aSsysId" placeholder="请选择系统" clearable allow-create filterable style="width: 180px">
              <el-option v-for="item in dsSysList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="模式名A">
            <el-input v-model="queryForm.aMdlName" placeholder="请输入模式名" clearable />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="归属系统B">
            <el-select v-model="queryForm.bSsysId" placeholder="请选择系统" clearable allow-create filterable style="width: 180px">
              <el-option v-for="item in dsSysList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="模式名B">
            <el-input v-model="queryForm.bMdlName" placeholder="请输入模式名" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="openAddDialog1">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="selectedRows1.length !== 1" @click="openEditDialog1(selectedRows1[0])">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="selectedRows1.length === 0" @click="deleteSelected1">删除</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="configList1" @selection-change="handleSelectionChange1" style="width: 100%" height="400" border stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="aSsysCd" label="所属系统A" />
      <el-table-column prop="aMdlName" label="模式名A" />
      <el-table-column prop="bSsysCd" label="所属系统B" />
      <el-table-column prop="bMdlName" label="模式名B" />
      <el-table-column prop="relaType" label="类型" />
      <el-table-column prop="ratio" label="阈值" />
      <el-table-column prop="updBy" label="更新人" />
      <el-table-column prop="updTime" label="更新时间" />
    </el-table>
    <el-dialog :title="title" v-model="open1" width="500px" append-to-body :before-close="handleClose1">
      <el-form ref="clasFormRef1" :model="form1" :rules="rules1" label-width="120px" >
        <el-form-item label="类型" prop="datatype">
          <el-input v-model="form1.relaType" autocomplete="off" />
        </el-form-item>
        <el-form-item label="阈值" prop="ratio">
          <el-input
              v-model="form1.ratio"
              :formatter="formatNumber"
              :parser="parseNumber"
              placeholder="只能输入数字"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属系统A" prop="ssysId">
          <el-select v-model="form1.aSsysId" placeholder="请选择系统" clearable allow-create filterable style="width: 350px">
            <el-option v-for="item in dsSysList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属模式A" prop="mdlName">
          <el-input v-model="form1.aMdlName" autocomplete="off"  />
        </el-form-item>
        <el-form-item label="所属系统B" prop="ssysId">
          <el-select v-model="form1.bSsysId" placeholder="请选择系统" clearable allow-create filterable style="width: 350px">
            <el-option v-for="item in dsSysList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属模式B" prop="mdlName">
          <el-input v-model="form1.bMdlName" autocomplete="off"  />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open1 = false">取消</el-button>
        <el-button type="primary" @click="submitForm1">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  deleteTableRelaLabel,
  editTableRelaLabel,
  addTableRelaLabel,
  getTableRelaLabelList,
} from "@/api/metadataConfig/metadataConfig";
import useUserStore  from '@/store/modules/user'; // 注意路径是否正确

const userStore = useUserStore(); // 正确调用
const dsSysList = userStore.dsSysList; // 访问属性
const queryForm = reactive({
  aSsysId: undefined,
  bSsysId: undefined,
  aMdlName: "",
  bMdlName: "",
});
const activeTab = ref('valueType');
const configList1 = ref([]); // 值类型参数数据
const loading = ref(false);

const open1 = ref(false); // 值类型弹窗开关
const title = ref("");

const clasFormRef1 = ref(null); // 值类型 formRef

const form1 = ref({
  relaType: "",
  ratio: null,
  aSsysId: undefined,
  bSsysId: undefined,
  aMdlName: "",
  bMdlName: "",
});

const rules1 = {
  relaType: [{ required: true, message: "请输入值类型", trigger: "blur" }],
  ratio: [{ required: true, message: "请输入阈值", trigger: "blur" }],
};

const selectedRows1 = ref([]);
const formatNumber = (value) => {
  if (!value) return value;
  value = value.replace(/[^\d.-]/g, ''); // 移除非数字、非小数点、非负号
  value = value.replace(/^\./, '0.');    // 以.开头转为0.
  value = value.replace(/^\-/, '-0');    // 以-开头转为-0（可选）
  value = value.replace(/(\.\d{2})\d+/, '$1'); // 限制小数点后两位
  value = value.replace(/^(-?\d+)-/, '$1');   // 防止中间出现负号
  value = value.replace(/^(-?\d+)\.(\d*)\.*/, '$1.$2'); // 防止多个小数点
  return value;
};

const parseNumber = (value) => {
  return formatNumber(value);
};
function handleSelectionChange1(val) {
  selectedRows1.value = val;
}
async function getList1() {
  loading.value = true;
  try {
    const res = await getTableRelaLabelList(queryForm);
    configList1.value = res.data || [];
    if (configList1.value.length>0) {
      for (let i = 0; i < configList1.value.length; i++) {
        configList1.value[i].aSsysCd = '*'
        if (configList1.value[i].aMdlName === ''){
          configList1.value[i].aMdlName = '*'
        }
        configList1.value[i].bSsysCd = '*'
        if (configList1.value[i].bMdlName === ''){
          configList1.value[i].bMdlName = '*'
        }
        for (let j = 0; j < dsSysList.length; j++) {
          if (configList1.value[i].aSsysId === dsSysList[j].id){
            configList1.value[i].aSsysCd = dsSysList[j].name
          }
          if (configList1.value[i].bSsysId === dsSysList[j].id){
            configList1.value[i].bSsysCd = dsSysList[j].name
          }
        }
      }
    }
  } catch (error) {
    ElMessage.error("获取值类型列表失败");
  } finally {
    loading.value = false;
  }
}

function resetQuery() {
  queryForm.aSsysId = undefined;
  queryForm.bSsysId = undefined;
  queryForm.aMdlName = "";
  queryForm.bMdlName = "";
  getList1();
}

function handleSearch() {
  getList1();
}

function openAddDialog1() {
  title.value = "新增表关系类型参数";
  open1.value = true;
  form1.value = {
    relaType: "",
    ratio: null,
    aSsysId: queryForm.aSsysId,
    bSsysId: queryForm.bSsysId,
    aMdlName: queryForm.aMdlName,
    bMdlName: queryForm.bMdlName,
  }
}

function openEditDialog1(row) {
  if (!row) {
    ElMessage.warning("请选择一条记录进行编辑");
    return;
  }
  title.value = "编辑表关系类型参数";
  Object.assign(form1.value, row);
  open1.value = true;
}

function submitForm1() {
  clasFormRef1.value.validate(async (valid) => {
    if (!valid) return;
    const submitData = { ...form1.value};
    try {
      if (title.value.includes("新增")) {
        await addTableRelaLabel(submitData);
        ElMessage.success("新增成功");
      } else {
        await editTableRelaLabel(submitData);
        ElMessage.success("编辑成功");
      }
      open1.value = false;
      await getList1();
    } catch (error) {
      ElMessage.error("操作失败，请重试");
    }
  });
}
function deleteSelected1() {
  if (selectedRows1.value.length === 0) {
    ElMessage.warning("请至少选择一条记录删除");
    return;
  }
  ElMessageBox.confirm(
    `确定删除选中的 ${selectedRows1.value.length} 条表关系类型参数吗？`,
    "提示",
    { type: "warning" }
  ).then(async () => {
    try {
      for (const row of selectedRows1.value) {
        await deleteTableRelaLabel(row.onum);
      }
      ElMessage.success("删除成功");
      await getList1();
    } catch {
      ElMessage.error("删除失败，请重试");
    }
  });
}

function handleClose1(done) {
  clasFormRef1.value.resetFields();
  done();
}

onMounted(async () => {
  await getList1();
});
</script>
<style scoped>
.app-container {
  padding: 20px;
  background: #fff;
}
</style>
