<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="dbResoursName"
            placeholder="请输入字典分类"
            clearable
            prefix-icon="search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="dbResourceOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ data.name }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="字典编号" prop="dataDictNo">
            <el-input
              v-model="queryParams.dataDictNo"
              placeholder="请输入标准字典编号"
              clearable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="字典名称" prop="dataDictCnName">
            <el-input
              v-model="queryParams.dataDictCnName"
              placeholder="请输入标准字典中/英文名称"
              clearable
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['meta:metaSecurityCol:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleEdit"
              v-hasPermi="['meta:metaSecurityCol:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleRemove"
              v-hasPermi="['meta:metaSecurityCol:remove']"
              >删除</el-button
            >
          </el-col>
        </el-row>

        <!-- 表格展示 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          height="calc(100vh - 355px)"
          @row-dblclick="handleEdit"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="归属" align="center" width="200">
 
              <template #default="scope">
    <span v-if="scope.row.dataDictVest === 'company'">公司级</span>
    <span v-else-if="scope.row.dataDictVest === 'sys'">
      {{
        getSrcSysName(scope.row.srcSys)
      }}
    </span>
  </template>
          </el-table-column>
          <el-table-column label="类型" align="center">
            <template #default="{ row }">
              {{ row.dataDictType == 0 ? "基础数据" : "指标数据" }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="来源系统" width="150" align="center" prop="sysName" /> -->
          <el-table-column
            label="字典编号"
            width="150"
            align="center"
            prop="dataDictNo"
          />
          <el-table-column
            label="字典英文名"
            width="120"
            align="center"
            prop="dataDictEngName"
          >
            <template #default="{ row }">
              <el-link
                type="primary"
                :underline="true"
                @click="handleEdit(row)"
                style="cursor: pointer"
              >
                <span >{{row.dataDictEngName}}</span>
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="字典中文名"
            width="120"
            align="center"
            prop="dataDictCnName"
          />
          <el-table-column
            label="字典业务定义"
            width="120"
            align="center"
            prop="dataDictBusiMean"
          />
          <el-table-column label="数据类型" align="center" prop="dataDictDataType" />
          <el-table-column label="数据标准" align="center" prop="dataStdNo" >
            <template #default="{ row }">
              <el-link
          type="primary"
          :underline="true"
          @click="handleStdClick(row.dataStdNo)"
          style="cursor: pointer"
        >
        <span >{{row.dataStdCnName}}</span>
        </el-link>
            </template>
            </el-table-column>
          <el-table-column label="字典状态" align="center" prop="dataDictStat">
            <template #default="scope">
              <dict-tag
                :options="std_code_appr"
                :value="scope.row.dataDictStat"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="业务认责部门"
            width="120"
            align="center"
            prop="dataStdBusiOwnershipDept"
          />
          <el-table-column
            label="业务认责人员"
            width="120"
            align="center"
            prop="dataStdBusiOwnershipPrsn"
          />
          <el-table-column
            label="技术认责部门"
            width="120"
            align="center"
            prop="dataStdItOwnershipDept"
          />
          <el-table-column
            label="技术认责人员"
            width="120"
            align="center"
            prop="dataStdItOwnershipPrsn"
          />
          <el-table-column
            label="更新者"
            width="120"
            align="center"
            prop="updPrsn"
          />
          <el-table-column
            label="更新时间"
            width="120"
            align="center"
            prop="updTime"
          />
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button
                @click="handleEdit(scope.row)"
                type="text"
                icon="Edit"
              />
              <el-button
                @click="handleRemove(scope.row)"
                type="text"
                icon="Delete"
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <AddEditForm
      :data="selectedRow"
      :isEdit="isEdit"
      :stdList="stdList"
      :dbResourceOldList="dbResourceOldList"
      v-model:visible="dialogVisible"
      @refresh="getList"
    />
    <AddEditStdForm
      :data="stdRow"
      :isEdit=true
      :isShow=true
      :dbResourceOldList="dbResourceOldList"
      v-model:visible="stdVisible"
      @refresh="getList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from "vue";
import {
  listStdDict,
  addStdDict,
  getStdDict,
  updateStdDict,
  deleteStdDict,
  getStdMain,
  listStdMainSelect
} from "@/api/datastd/std"; // 更新为新的接口
import { datasourcetree } from "@/api/meta/metatask";
import AddEditForm from "./AddEditForm.vue";
import AddEditStdForm  from "../main/components/AddEditForm.vue";
const { proxy } = getCurrentInstance();
const { std_code_status, std_code_appr } = proxy.useDict(
  "std_code_status",
  "std_code_appr"
);

const queryParams = ref({
  dataDictNo: "",
  dataDictCnName: "",
  dataDictType: "",
  sysName: "",
  classId: "dict",
  sysId: "",
  pageNum: 1,
  pageSize: 10,
});
const queryStd = ref({
  dataStdNo: "",
});
const single = ref(true);
const multiple = ref(true);
const dbResoursName = ref(undefined);
const defaultProps = { children: "children", label: "name" };
const dialogVisible = ref(false);
const selectedRow = ref(null);
const stdRow = ref(null);
const isEdit = ref(false);
const tableData = ref([]);
const stdList = ref([]);
const total = ref(0);
const loading = ref(false);
const stdVisible = ref(false);
const ids = ref([]);
const cdNos = ref([]);
const getSrcSysName = (id) => {
  const match = dbResourceOldList.value.find(item => item.id == id);
  return match ? "系统级："+ match.name : id;
};
const dbResourceOptions = ref([]);
const handleStdClick = (code) => {
   var id =transCodetoId(code)
  getStdMain(id).then((response) => {
    stdRow.value = response.data;
    stdVisible.value = true;
  });

};
watch(dbResoursName, (val) => {

proxy.$refs["tree"].filter(val);


});
const transCodetoId = (dataStdNo) => {
  const match = stdList.value.find(item => item.dataStdNo === dataStdNo);
  return match ? match.onum : '';
};
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};

const handleNodeClick = (data) => {
  queryParams.value.srcSys = data.id === 99999||data.id === 10000 ? undefined : data.id;
    queryParams.value.dataDictVest=data.id === 10000 ? "company":"sys"
  handleQuery();
};

const handleSelectionChange = (selection) => {
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
  ids.value = selection.map((item) => item.onum);
  cdNos.value = selection.map((item) => item.dataDictNo);
};

const getList = async () => {
  loading.value = true;
  const response = await listStdDict(queryParams.value);
  tableData.value = response.rows;
  total.value = response.total;
  loading.value = false;
};
const getStdMainSelect = async () => {
  const response = await listStdMainSelect(queryStd);
  stdList.value = response.data;

};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryParams.value = {
    dataDictNo: "",
    dataDictCnName: "",
    dataDictType: "",
    sysName: "",
    sysId: undefined,
    pageNum: 1,
    pageSize: 10,
  };
  getList();
};

const handleRemove = (row) => {
  const idsToDelete = row.onum ? [row.onum] : ids.value;
  const codesToDelete = row.cdNo ? [row.cdNo] : cdNos.value;
  proxy.$modal
    .confirm(
      '是否确认删除字典编号为"' + codesToDelete.toString() + '"的数据项？'
    )
    .then(function () {
      return deleteStdDict(idsToDelete.toString());
    })
    .then(() => {
      handleQuery();
      proxy.$modal.msgSuccess("提交删除审批成功！");
    })
    .catch(() => {});
};
const dbResourceOldList = ref([]);

const handleAdd = () => {
  console.log("update:visible", 111);
  isEdit.value = false;
  selectedRow.value = {
    dataDictVest: "company",
    sysId: 10000,
    sysName: "公司级",
    dataDictType: "",
    dataDictNo: "",
    dataDictEngName: "",
    dataDictCnName: "",
    dataDictBusiMean: "",
    dataDictDataType: "",
    dataStdNo: "",
    dataStdBusiOwnershipDept: "",
    dataStdBusiOwnershipPrsn: "",
    dataStdItOwnershipDept: "",
    dataStdItOwnershipPrsn: "",
  };

  // 清空选中的数据
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  const id = row.onum ? row.onum : ids.value.toString();
  getStdDict(id).then((response) => {
    selectedRow.value = response.data;
    isEdit.value = true;
    dialogVisible.value = true;
  });
};

onMounted(() => {
  datasourcetree().then((response) => {
    dbResourceOldList.value = response.rows;
    dbResourceOptions.value = [
      { id: 10000, name: "公司级字典", parentId: 0, children: [] },
      {
        id: 99999,
        name: "系统级字典",
        parentId: 0,
        children: response.rows.map((element) => ({
          ...element,
          parentId: "99999",
        })),
      },
    ];
  });
  getList();
  getStdMainSelect();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.head-container {
  margin-bottom: 0px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
}

.custom-tree-node i {
  margin-right: 8px;
}
</style>
