<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-form :inline="true" :model="queryForm" >
        <el-form-item label="对象类型">
          <el-select v-model="queryForm.objType" placeholder="请选择对象类型"  style="width: 180px" clearable>
            <el-option label="角色" value="0" />
            <el-option label="用户" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="对象名称">
          <el-input v-model="queryForm.objName" placeholder="请输入对象名称" style="width: 180px" 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-form>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="openAddDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="selectedRows.length !== 1"
          @click="openEditDialog(selectedRows[0])"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="selectedRows.length === 0"
          @click="deleteSelected"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="permList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      border
      stripe
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="bizName" label="业务域" />
<el-table-column prop="objType" label="对象类型">
  <template #default="{ row }">
    {{ row.objType === '0' || row.objType === 0 ? '角色' : '用户' }}
  </template>
</el-table-column>      <el-table-column prop="objName" label="对象名称" />
      <el-table-column prop="isStop" label="是否停用">
        <template #default="{ row }">
          <el-tag :type="row.isStop? 'success' : 'info'">
            {{ row.isStop  ? '运行' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="secLevelSummary" label="安全等级" />
      <el-table-column prop="createBy" label="创建者" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateBy" label="更新者" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
    </el-table>

    <pagination
       v-show="total > 0"
       :total="total"
       v-model:page="queryForm.pageNum"
       v-model:limit="queryForm.pageSize"
       @pagination="getList"
    />

    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :before-close="handleClose"
    >
      <el-form
        ref="permFormRef"
        :model="form"
        :rules="rules"
        label-width="130px"
        size="small"
      >
        <el-form-item label="业务域" prop="bizOnum">
  <el-select
    v-model="form.bizOnum"
    :multiple="isAddMode"
    placeholder="请选择业务域"
    filterable
    clearable
  >
    <el-option
      v-for="dict in bizOnumList"
      :key="dict.onum"
      :label="dict.bizName"
      :value="dict.onum"
    ></el-option>
  </el-select>
        </el-form-item>
        <el-form-item label="对象类型" prop="objType">
          <el-select v-model="form.objType" placeholder="请选择对象类型" @change="changeMetaSecurityObj"
>
            <el-option label="角色" value="0" />
            <el-option label="用户" value="1" />
          </el-select>
        </el-form-item>
                        <!-- @change="handleObjValueChange" -->

        <el-form-item label="对象名称" prop="objName">
          <el-select
                v-model="form.objName"
                placeholder="请选择"
                maxlength="30"
              >
                <el-option
                  v-for="dict in userOrRoleList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.name"
                ></el-option>
              </el-select>
        </el-form-item>

        <el-form-item label="是否停用" prop="isStop">
          <el-select v-model="form.isStop" placeholder="请选择状态">
            <el-option label="运行" :value=true />
            <el-option label="停用" :value=false />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  listBizPermiConfig,
  addBizPermiConfig,
  updateBizPermiConfig,
  listBizConfigAll,
  delBizPermiConfig
} from '@/api/metadataConfig/metadataConfig'
import { listUser} from "@/api/system/user";
import { listRole} from "@/api/system/role";
const queryForm = reactive({
  objType: '',
  objName: '',
  pageNum: 1,
  pageSize: 10
})

const permList = ref([])
const total = ref(0)
const loading = ref(false)
const open = ref(false)
const title = ref('')
// const handleObjValueChange = (selectedValues) => {
//   // 根据当前对象类型获取对应的列表
//   const sourceList = form.value.objType === '0' 
//     ? userList.value 
//     : roleList.value;

//   // 转换选中的值为名称数组
//   const names = selectedValues.map(value => {
//     const item = sourceList.find(item => item.id === value);
//     return item ? item.name : '';
//   });
// }
const roleList = ref([]);
const userList = ref([]);
const userOrRoleList = ref([]);
const bizOnumList = 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})
    });
  });
}  
const permFormRef = ref(null)

const form = reactive({
  onum: null,
  bizOnum: null,
  objType: '',
  objName: '',
  isStop: null
})
function changeMetaSecurityObj(data){
   form.objName=""
 if(data=="1"){
  userOrRoleList.value=userList.value

 }else {
  userOrRoleList.value=roleList.value

 }
}
const rules = {
  bizOnum: [{ required: true, message: '请输入业务域', trigger: 'blur' }],
  objType: [{ required: true, message: '请选择对象类型', trigger: 'change' }],
  objName: [{ required: true, message: '请输入对象名称', trigger: 'blur' }],
  isStop: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const selectedRows = ref([])

function handleSelectionChange(val) {
  selectedRows.value = val
}

async function getList() {
  loading.value = true
  try {
    console.log(queryForm,"queryForm")
    const res = await listBizPermiConfig(queryForm)
    permList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取列表失败，请重试')
  } finally {
    loading.value = false
  }
}
async function getBizList() {
  loading.value = true
  try {
    const res = await listBizConfigAll()
    bizOnumList.value = res.data || []
  } catch (error) {
    ElMessage.error('获取业务域列表失败，请重试')
  } finally {
    loading.value = false
  }
}
function resetQuery() {
  queryForm.objType = ''
  queryForm.objName = ''
  queryForm.pageNum = 1
  getList()
}

function handleSearch() {
  queryForm.pageNum = 1
  getList()
}
const isAddMode = ref(true)

function openAddDialog() {
    isAddMode.value = true

  title.value = '新增业务域权限配置'
  Object.assign(form, {
    onum: null,
    bizOnum: [],
    objType: '',
    objName: '',
    isStop: null
  })
  open.value = true
}

function openEditDialog(row) {
  if (!row) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
    isAddMode.value = false

  title.value = '编辑业务域权限配置'
  Object.assign(form, row)

  if(form.objType=="0"){
  userOrRoleList.value=roleList.value
  }else{
  userOrRoleList.value=userList.value
  }
  open.value = true
}

function submitForm() {
  permFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (title.value.includes('新增')) {
            const submitData = {
      bizOnumList: form.bizOnum,   // 传递数组
      objType: form.objType,
      objName: form.objName,
      isStop: form.isStop,
    }
        await addBizPermiConfig(submitData)
        ElMessage.success('新增成功')
      } else {
            const submitData = {
      onum: form.onum,   // 传递数组
      bizOnum: form.bizOnum,   // 传递数组
      objType: form.objType,
      objName: form.objName,
      isStop: form.isStop,
    }
        await updateBizPermiConfig(submitData)
        ElMessage.success('编辑成功')
      }
      open.value = false
      getList()
    } catch (error) {
    }
  })
}

function deleteRow(onum) {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        await delBizPermiConfig(onum)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => {})
}

function deleteSelected() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录删除')
    return
  }
  const onumStr = selectedRows.value.map(row => row.onum).join(',')
  ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        await delBizPermiConfig(onumStr)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => {})
}

function handleClose(done) {
  permFormRef.value.resetFields()
  done()
}

onMounted(() => {
   getList()
    getRoleOrUserList();
    getBizList();

})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>
