<script setup>
import { reactive, onMounted, watch, ref } from "vue";
import {
  addRole,
  changeRoleStatus,
  dataScope,
  delRole,
  getRole,
  listRole,
  updateRole,
  deptTreeSelect,
} from "../../../views/system/role/api";
import { getCurrentInstance } from "vue";
import {
  baseModelOptions,
  baseFilterOptions,
  basepermissOptions,
} from "./options";
const table = ref();
const bm = ref();
const { proxy } = getCurrentInstance();
const router = useRouter();
const openDataScope = ref(false);
const deptOptions = ref([]);
const state = reactive({
  baseModelOptions: baseModelOptions(),
  baseFilterOptions: baseFilterOptions(),
  basepermissOptions: basepermissOptions(),
  columnCount: 1,
  title: "用户管理",
  baseModelName: "用户",
  editBtnName: "",
  delBtnName: "",
  primaryKey: "roleId",
  deleteKey: "roleIds",
  getTableFn: listRole,
  addFn: addRole,
  editFn: updateRole,
  deleteFn: delRole,
  detailFn: getRole,
  showEditBtn: true,
  showDeleteBtn: true,
  showFilter: true,
  permission: {
    //菜单管理中添加权限
    add: "system:role:add",
    edit: "system:role:edit",
    delete: "system:role:remove",
    detail: "system:role:query",
  },
  columns: [
    { key: 2, label: '角色编号', visible: true },
    { key: 3, label: '角色名称', visible: true },
    // { key: 4, label: '权限字符', visible: true },
    { key: 5, label: '显示顺序', visible: true },
    { key: 6, label: '状态', visible: true },
    { key: 7, label: '创建时间', visible: true },
  ],
  showLoading: false,
  pageInfo: { total: 0, base: { limit: 8, current: 1 } },
  deptOptions: [],
  baseQuery: {},
  showPassword: false,
  pasData: [],
  pswTitle: "",
  beforeSubmit: (res) => {
    res.roleKey = proxy.$util.getUUID();
  },
  beforeShowEdit: (row, res) => {
    return {
      ...row,
      postIds: res.postIds,
      roleIds: res.roleIds,
    };
  },
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined,
  },
  rules: {
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [
      { required: true, message: "角色顺序不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
const editTable = (baseScope, scope) => {
  const meun = proxy.$util.getOptionByKey(state.baseModelOptions, "menuIds");
  meun.attribute.id = scope.row.roleId;
  baseScope.handleEdit(scope.$index, scope.row);
};
/** 分配数据权限操作 */
const handleDataScope = (baseScope, scope) => {
  const meun = proxy.$util.getOptionByKey(state.basepermissOptions, "menuIds");
  meun.attribute.id = scope.row.roleId;
  bm.value.setValueByKey("roleName", scope.row.roleName);
  bm.value.setValueByKey("roleKey", scope.row.roleKey);
  bm.value.setValueByKey("dataScope", scope.row.dataScope);
  meun.attribute.menuExpands = true;
  openDataScope.value = true;
};
/** 分配用户 */
const handleAuthUser = (row) => {
  router.push("/system/role-auth/user/" + row.roleId);
};
/** 根据角色ID查询部门树结构 */
const getDeptTree = (roleId) => {
  return deptTreeSelect(roleId).then((response) => {
    deptOptions.value = response.depts;
    return response;
  });
};
/** 提交按钮（数据权限） */
const submitDataScope = () => {
  const roleName = bm.value.formData;
  console.log(roleName);
};
// const dataScope = proxy.$util.getOptionByKey(state.basepermissOptions, 'dataScope')
watch(
  () => proxy.$util.getOptionByKey(state.basepermissOptions, "dataScope"),
  (newVal, oldVal) => {
    const meun = proxy.$util.getOptionByKey(
      state.basepermissOptions,
      "menuIds"
    );
    if (newVal.value == 2) {
      meun.hide = false;
    } else {
      meun.hide = true;
    }
  },
  //深度监听
  { deep: true }
);
/** 角色状态修改 */
const handleStatusChange = (row) => {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
};
onMounted(() => {});
</script>
<template>
  <div class="app-container">
    <BaseModel
      ref="bm"
      title="分配数据权限"
      :columnCount="1"
      :showModel="openDataScope"
      :width="'35%'"
      :modelOptions="state.basepermissOptions"
      @dialogClose="openDataScope = false"
      @dialogSubmit="submitDataScope"
    >
    </BaseModel>
    <BaseTablePage :tableOptions="state" ref="table">
      <template v-slot:column>
        <el-table-column v-if="state.columns[0].visible" label="角色编号" prop="roleId" width="120" />
        <el-table-column
          label="角色名称"
          prop="roleName"
          v-if="state.columns[1].visible"
          :show-overflow-tooltip="true"
          width="150"
        />
        <!-- <el-table-column
          label="权限字符"
          prop="roleKey"
          v-if="state.columns[2].visible"
          :show-overflow-tooltip="true"
          width="150"
        /> -->
        <el-table-column label="显示顺序" v-if="state.columns[2].visible" prop="roleSort" width="100" />
        <el-table-column label="状态" align="center" width="100" v-if="state.columns[3].visible">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" v-if="state.columns[4].visible" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </template>
      <template #control="baseScope">
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button
              type="text"
              v-if="scope.row.userId !== 1"
              icon="Edit"
              @click="editTable(baseScope, scope)"
              v-hasPermi="['system:user:edit']"
              >修改
            </el-button>
            <el-button
              v-if="scope.row.userId !== 1"
              type="text"
              icon="Delete"
              @click="baseScope.deleteTableData(scope.$index, scope.row)"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
            <el-button
              type="text"
              v-if="scope.row.roleId !== 1"
              icon="CircleCheck"
              @click="handleDataScope(baseScope, scope)"
              v-hasPermi="['system:role:edit']"
              >数据权限</el-button
            >
            <!-- <el-tooltip
              content="分配用户"
              placement="top"
              v-if="scope.row.roleId !== 1"
            >
              <el-button
                type="text"
                icon="User"
                @click="handleAuthUser(scope.row)"
                v-hasPermi="['system:role:edit']"
              >
              </el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </template>
    </BaseTablePage>
  </div>
</template>

<style scoped>
</style>
