<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">
                <!-- <i :class="getIconClass(data)"></i> -->
                <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="codeNum">
            <el-input v-model="queryParams.codeNum" placeholder="请输入标准代码编号" clearable style="width: 220px" />
          </el-form-item>
          <el-form-item label="标准代码值" prop="codeName">
            <el-input v-model="queryParams.codeName" 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" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column label="标准代码编号" align="center" prop="codeNum" />
          <el-table-column label="标准代码值" align="center" prop="codeName" />
          <el-table-column label="代码状态" align="center" prop="codeStatus">
            <template #default="scope">
              <dict-tag :options="metasecurity_ctr" :value="scope.row.codeStatus" />
            </template>
          </el-table-column>


          <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="handlePagination" />
      </el-col>
    </el-row>

    <!-- 添加或编辑标准代码对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="form" ref="formRef" label-width="120px" :rules="formRules">
        <el-form-item label="标准代码编号" prop="codeNum">
          <el-input v-model="form.codeNum" placeholder="请输入标准代码编号" />
        </el-form-item>
        <el-form-item label="标准代码值" prop="codeName">
          <el-input v-model="form.codeName" placeholder="请输入标准代码值" />
        </el-form-item>
        <el-form-item label="标准代码类型" prop="codeType">
          <el-input v-model="form.codeType" placeholder="请输入标准代码类型" />
        </el-form-item>
        <el-form-item label="代码状态" prop="codeStatus">
          <el-select v-model="form.codeStatus" placeholder="请选择代码状态">
            <el-option v-for="status in codeStatusOptions" :key="status.value" :label="status.label" :value="status.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属系统" prop="sysName">
          <el-input v-model="form.sysName" placeholder="请输入归属系统" />
        </el-form-item>
        <el-form-item label="归属系统Id" prop="sysId">
          <el-input v-model="form.sysId" placeholder="请输入归属系统Id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from 'vue';
import { listStdCode, addStdCode, getStdCode, updateStdCode, deleteStdCode } from "@/api/datastd/stdcode"; // 更新为新的接口
import { datasourcetree } from "@/api/meta/metatask";


const { proxy } = getCurrentInstance();
const { metasecurity_ctr } = proxy.useDict("metasecurity_ctr");

const queryParams = ref({
  codeNum: '',
  codeName: '',
  codeType: '',
  sysName: '',
  sysId: '',
  pageNum: 1,
  pageSize: 10
});
const single = ref(true);
const multiple = ref(true);
const dbResoursName = ref(undefined);
const defaultProps = {
  children: "children",
  label: "name"
};
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};
const handleNodeClick = (data) => {
  if (data.id === 99999) {
    queryParams.value.dbRID = "";
  } else {
    queryParams.value.dbRID = data.id;
  }
  handleQuery();
};

const dbResourceOptions = ref(undefined);
const form = ref({
  colId: '',
  codeNum: '',
  codeName: '',
  codeType: '',
  codeStatus: '',
  sysName: '',
  sysId: ''
});
const ids = ref([]);

// 获取数据列表
const getList = async () => {
  loading.value = true;
  const response = await listStdCode(queryParams.value);
  tableData.value = response.rows;
  total.value = response.total;
  loading.value = false;
};

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.colId);
  single.value = ids.value.length === 1;
  multiple.value = ids.value.length > 0;
}

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

const resetQuery = () => {
  queryParams.value = {
    codeNum: '',
    codeName: '',
    codeType: '',
    sysName: '',
    sysId: '',
    pageNum: 1,
    pageSize: 10
  };
  getList();
};

const handleAdd = () => {
  dialogTitle.value = "新增标准代码";
  form.value = {
    colId: '',
    codeNum: '',
    codeName: '',
    codeType: '',
    codeStatus: '',
    sysName: '',
    sysId: '',
  };
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogTitle.value = "编辑标准代码";
  getStdCode(row.colId).then(response => {
    form.value = response;
    dialogVisible.value = true;
  });
};

const handleRemove = (row) => {
  const idsToDelete = row ? [row.colId] : ids.value;
  deleteStdCode(idsToDelete).then(() => {
    handleQuery();
  });
};

const handleSave = () => {
  if (!form.value.codeNum || !form.value.codeName) {
    ElMessage.warning("请填写必填项");
    return;
  }

  const saveAction = form.value.colId ? updateStdCode : addStdCode;
  saveAction(form.value).then(() => {
    dialogVisible.value = false;
    handleQuery();
  });
};

const handleCancel = () => {
  dialogVisible.value = false;
};
const dbResourceOldList = ref([]);
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRules = reactive({
  codeNum: [{ required: true, message: "请输入标准代码编号", trigger: "blur" }],
  codeName: [{ required: true, message: "请输入标准代码值", trigger: "blur" }]
});
onMounted(() => {
  datasourcetree().then(response => {

    dbResourceOldList.value = response.rows;
    const childrenList = dbResourceOldList.value.map(element => ({ ...element, parentId: "99999" }));
    dbResourceOptions.value = [
    {
      id: 10000, // 新的节点 ID，可以根据需要调整
      name: "公司级代码", 
      parentId: 0, 
      children: [] // 这里可以根据需要填充子节点
    },
    { 
      id: 99999, 
      name: "系统级代码", 
      parentId: 0, 
      children: childrenList 
    },

  ];  });
  getList();
});
</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>
