<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="dbSName">
        <el-input v-model="queryParams.dbSName" placeholder="请输入模式名称" clearable />
      </el-form-item>
      <el-form-item label="表名" prop="dbTName">
        <el-input v-model="queryParams.dbTName" placeholder="请输入行名称" clearable />
      </el-form-item>
      <el-form-item label="字段名" prop="dbCName">
        <el-input v-model="queryParams.dbCName" placeholder="请输入行名称" clearable />
      </el-form-item>
      <el-form-item label="用户角色" prop="objValue">
        <el-input v-model="queryParams.objValue" placeholder="请输入行名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</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:metaSecurityRow:add']"
            >新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleEdit"
               v-hasPermi="['meta:metaSecurityRow:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleRemove"
               v-hasPermi="['meta:metaSecurityRow: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="dbRName" />
      <el-table-column label="模式" align="center" prop="dbSName" />
      <el-table-column label="表名" align="center" prop="dbTName" />
      <el-table-column label="字段名" align="center" prop="dbCName" />
      <el-table-column label="控制方式" align="center" prop="ctrlType" >
        <template #default="scope">
                          <dict-tag
                :options="metasecurity_type"
                :value="scope.row.ctrlType"
              />
            </template>
        </el-table-column>
      <el-table-column label="控制值" align="center" prop="ctrlValue" />
      <el-table-column label="对象类型" align="center" prop="objType" >
        <template #default="scope">
                          <dict-tag
                :options="metasecurity_obj"
                :value="scope.row.objType"
              />
            </template>
        </el-table-column>
      <el-table-column label="对象编号" align="center" prop="objValue" >
        <template #default="scope">
    <span v-if="scope.row.objType === '0'">
      {{ getUserName(scope.row.objValue) }}
    </span>
    <span v-else-if="scope.row.objType === '1'">
      {{ getRoleName(scope.row.objValue) }}
    </span>
    <span v-else>
      {{ scope.row.objValue }}
    </span>
  </template>
      </el-table-column>
      <el-table-column label="是否停用" align="center" prop="isStop" />
      <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="dbRID">
          <el-select
                v-model="form.dbRID"
                placeholder="请选择连接"
                maxlength="30"
                @change="dataChange"
              >
                <el-option
                  v-for="dict in dbResourceOldList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
</el-form-item>
<el-form-item label="模式" prop="dbSName">
  <el-input v-model="form.dbSName" placeholder="请输入模式" />
</el-form-item>
<el-form-item label="表名" prop="dbTName">
  <el-input v-model="form.dbTName" placeholder="请输入表名" />
</el-form-item>
<el-form-item label="字段名" prop="dbCName">
  <el-input v-model="form.dbCName" placeholder="请输入字段名" />
</el-form-item>
<el-form-item label="控制方式" prop="ctrlType">
  <el-select
                v-model="form.ctrlType"
                placeholder="请输入控制方式"
                maxlength="30"
              >
                <el-option
                  v-for="dict in metasecurity_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
</el-form-item>
<el-form-item label="控制值" prop="ctrlValue">
  <el-input v-model="form.ctrlValue" placeholder="请输入控制值" />
</el-form-item>

<el-form-item label="对象类型" prop="objType">
  <el-select
                v-model="form.objType"
                placeholder="请选择对象类型"
                maxlength="30"
                @change="changeMetaSecurityObj"
              >
                <el-option
                  v-for="dict in metasecurity_obj"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
</el-form-item>
<el-form-item label="对象编号" prop="objValue">
  <el-select
                v-model="form.objValue"
                placeholder="请选择"
                :multiple="dialogTitle === '添加行配置'" 
                maxlength="30"
              >
                <el-option
                  v-for="dict in userOrRoleList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select></el-form-item>
<el-form-item label="是否停用" prop="isStop">
  <el-switch v-model="form.isStop" />
</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 { listMetaSecurityRow, addMetaSecurityRow,getMetaSecurityRow, updateMetaSecurityRow, deleteMetaSecurityRow } from "@/api/meta/metasercurity";
const { proxy } = getCurrentInstance();
const { metasecurity_ctr, metasecurity_obj, metasecurity_type} = proxy.useDict("metasecurity_ctr", "metasecurity_obj", "metasecurity_type");
import { datasourcetree } from "@/api/meta/metatask";
import { listUser} from "@/api/system/user";
import { listRole} from "@/api/system/role";
const queryParams = ref({
  dbCName: '',
  dbTName: '',
  objValue: '',
  pageNum: 1,
  pageSize: 10
});
const single = ref(true);
const multiple = ref(true);
function dataChange(data) {

// 从 dbResourceOldList 中查找对应的 name
const selectedItem = dbResourceOldList.value.find(item => item.id === data);
if (selectedItem) {
// 如果找到对应的项，将 name 赋值给 form.value.dbRName
form.value.dbRName = selectedItem.name;
} else {
// 如果未找到，清空 form.value.dbRName
form.value.dbRName = '';
}
}
const dbResourceOptions = ref(undefined);
const form = ref({
  dbRName: '',       // 连接
  ctrlSystem: '',       // 连接
  dbRID: undefined,
  dbSName: '',       // 模式
  dbTName: '',       // 表名
  ctrlType: '',      // 控制方式
  ctrlValue: '',     // 固定值
  ctrlTable: '',     // 控制表
  ctrlCol: '',       // 控制字段
  objType: '',       // 对象类型
  objValue: '',      // 对象
  isStop: false      // 是否停用
});
const ids = ref([]);
const loading = ref(true);
const tableData = ref([]);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref('添加行');
const formRules = {
  dbRName: [{ required: true, message: '连接不能为空', trigger: 'blur' }],
  dbSName: [{ required: true, message: '模式不能为空', trigger: 'blur' }],
  dbTName: [{ required: true, message: '表名不能为空', trigger: 'blur' }],
  dbCName: [{ required: true, message: '字段名不能为空', trigger: 'blur' }],
  ctrlType: [{ required: true, message: '控制方式不能为空', trigger: 'blur' }],
};
const dbResourceOldList = ref([]);
const roleList = ref([]);
const userList = ref([]);
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 getIconClass = (data) => {
  let icon=""
  if (data.parentId == '0') icon= 'Monitor'; 
  if (data.parentId == '99999') icon= 'Coin'; 
  console.log(icon)
  return icon; 
};
const userOrRoleList = ref([]);
function getRoleOrUserList() {
  listRole().then(response => {
    response.rows.forEach(item => {
      roleList.value.push({id:item.roleId.toString(),name:item.roleName})
    });
  });
  listUser().then(response => {
    response.rows.forEach(item => {
      userList.value.push({id:item.userId.toString(),name:item.nickName})
    });
  });
}
function changeMetaSecurityObj(data){
 if(data=="0"){
  userOrRoleList.value=userList.value

 }else {
  userOrRoleList.value=roleList.value

 }


form.value.objValue = dialogTitle.value === '添加行配置' ? [] : '';

}
const getDeptTree = async () => {

  
  const treeResponse = await datasourcetree();
  if (treeResponse.success && treeResponse.rows.length > 0) {
    dbResourceOldList.value = treeResponse.rows;
    const childrenList = dbResourceOldList.value.map(element => ({ ...element, parentId: "99999" }));
    dbResourceOptions.value = [{ id: 99999, name: "数据源", parentId: 0, children: childrenList }];
  }
};
// 获取数据行表
const getList = async () => {
  loading.value = true;
  const response = await listMetaSecurityRow(queryParams.value);
  tableData.value = response.rows;
  total.value = response.total;
  loading.value = false;
};
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.rowId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 翻页
const handlePagination = (pageNum, pageSize) => {
  queryParams.pageNum = pageNum;
  queryParams.pageSize = pageSize;
  getList();
};

// 打开编辑对话框
const handleEdit = (row) => {
  reset();
  const rowId = row.rowId || ids.value;
  getMetaSecurityRow(rowId).then(response => {
    form.value = response.data;
    dialogVisible.value = true;
    dialogTitle.value = "编辑行配置";
  });
};

// 保存数据

function handleSave() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (form.value.rowId != undefined&&form.value.rowId !="") {
        updateMetaSecurityRow(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          dialogVisible.value = false;
          getList();
        });
      } else {
        const submitData = { ...form.value };
        submitData.objValue = submitData.objValue.join(',');
        addMetaSecurityRow(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          dialogVisible.value = false;
          getList();
        });
      }
    }
  });
}
/** 表单重置 */
function reset() {
  form.value = {
    rowId: '',
    dbRName: '',
    dbRID: undefined,
    dbSName: '',
    dbTName: '',
    dbCName: '',
    ctrlType: '',
    objType: '',
    objValue: dialogTitle.value === '添加行配置' ? [] : '', // 根据模式初始化
    isStop: false
  };
  proxy.resetForm("formRef");
}
// 删除数据
const handleRemove = async (row) => {


  const rowId = row.rowId || ids.value;
  proxy.$modal.confirm('是否确认删除ID为"' + rowId + '"的数据项？').then(function () {
    return deleteMetaSecurityRow(rowId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};
const handleAdd = () => {
  reset();
  dialogTitle.value = '添加行配置';
  dialogVisible.value = true;
  form.value.objValue = []; // 新增时初始化为空数组
};
// 根据 objValue 查找用户名称
const getUserName = (objValue) => {
  if (!objValue) return '';
  const values = objValue.split(','); // 处理多选值
  const names = values.map(value => {
    const user = userList.value.find(user => user.id === value);
    return user ? user.name : value;
  });
  return names.join(', ');
};

// 根据 objValue 查找角色名称
const getRoleName = (objValue) => {
  if (!objValue) return '';
  const values = objValue.split(','); // 处理多选值
  const names = values.map(value => {
    const role = roleList.value.find(role => role.id == value);
    return role ? role.name : value;
  });
  return names.join(', ');
};
// 取消编辑
const handleCancel = () => {
  dialogVisible.value = false;
  form.value.rowId = '';
  form.value.dbCName = '';
  form.value.ctrlType = '';
  form.value.ctrl_value = '';
  form.value.isStop = false;
};

onMounted(() => {
  getList();
  getDeptTree();
  getRoleOrUserList();
});
watch(dbResoursName, (val) => {
  if (val) {
    // Filter the department tree when dbResoursName changes
    proxy.$refs["tree"].filter(val);


  }
});
</script>
<style scoped>
/* 添加样式 */
</style>
