<template>
  <div>
    <div class="titleBox">
      <div class="title">角色列表</div>
      <div class="btnBox">
        <el-button type="primary" @click="addRole()">
          <el-icon><CirclePlus /></el-icon>
          <span>新增</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="角色名称">
          <el-input
            placeholder="请输入角色名称"
            v-model="listQuery.roleName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleFilter"> 查询 </el-button>
          <el-button @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tabBox">
      <el-table
        :data="tableData"
        border
        :height="tableHeight"
        style="width: 100%"
        :key="keyCount"
      >
        <el-table-column
          sortable
          prop="orderNo"
          label="角色编号"
          show-overflow-tooltip
          width="120px"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="roleName"
          label="角色名称"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="roleCode"
          label="角色编码"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column sortable label="状态" width="80px">
          <template #default="{ row }">
            <div>
              <el-tag size="small" type="success" v-if="row.xtZxbz === 0"
                >正常</el-tag
              >
              <el-tag size="small" type="danger" v-else-if="row.xtZxbz === 1"
                >注销</el-tag
              >
              <el-tag size="small" type="info" v-else>未知</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="roleDesc"
          label="角色描述"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column sortable prop="bz" label="备注" show-overflow-tooltip>
        </el-table-column>
        <el-table-column sortable prop="xtZhxgsj" label="更新时间">
          <template #default="{ row }">
            {{ $filters.dateFilter(row.xtZhxgsj) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="320">
          <template #default="{ row }">
            <el-button @click="updateDict(row)" size="small">修改</el-button>
            <el-button @click="allocationUser(row)" size="small"
              >管理用户</el-button
            >
            <el-button @click="privilegesHanlder(row)" size="small"
              >菜单权限</el-button
            >
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              title="确定要删除?"
              @confirm="delRole(row)"
            >
              <template #reference>
                <!-- v-permission="['removeTest','removeTest2']" -->
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ isEdit ? "修改" : "新增" }}</span>
        <div>
          <!-- 修改 -->
          <el-button
            v-if="isEdit"
            type="primary"
            size="small"
            @click="onSave"
            :loading="buttonLoading"
            >保存</el-button
          >
          <!-- 新增 -->
          <el-button
            v-else
            type="primary"
            size="small"
            @click="onAdd"
            :loading="buttonLoading"
            >保存</el-button
          >
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </div>
      </div>
      <el-form
        :rules="rules"
        ref="elform"
        inline="true"
        label-position="top"
        :model="dialogForm"
        class="mosty-from-wrap"
      >
        <el-form-item prop="roleName" class="one" label="角色名称">
          <el-input
            v-model="dialogForm.roleName"
            show-word-limit
            maxlength="20"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="one"
          prop="roleCode"
          label="角色编码"
          label-width="140px"
        >
          <el-input
            v-model="dialogForm.roleCode"
            show-word-limit
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="one"
          label="角色描述"
          prop="roleDesc"
          label-width="140px"
        >
          <el-input
            v-model="dialogForm.roleDesc"
            show-word-limit
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="one"
          label="排序号"
          prop="orderNo"
          label-width="140px"
        >
          <el-input-number
            v-model="dialogForm.orderNo"
            class="mx-4"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item
          class="one"
          label="权限范围"
          prop="dataPermissionLevel"
          label-width="140px"
        >
          <!-- <MOSTY.PackageSelect
            width="280px"
            v-model="dialogForm.dataPermissionLevel"
            dictEnum="D_ZDY_SJQX"
            clearable
            filterable
          /> -->
          <el-select
            clearable
            v-model="dialogForm.dataPermissionLevel"
            placeholder="请选择"
          >
            <el-option
              v-for="(dict, index) in D_ZDY_SJQX"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="one" label="备注" label-width="140px">
          <el-input
            v-model="dialogForm.bz"
            show-word-limit
            maxlength="200"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <PrivilegesDialog
      v-model="privilegesDialogVisible"
      :roleId="currentRow.id"
    ></PrivilegesDialog>
  </div>
</template>

<script setup>
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import PrivilegesDialog from "./conponents/PrivilegesDialog.vue";
import { ElMessage } from "element-plus";
import { ref, onMounted, getCurrentInstance, onUnmounted } from "vue";
const { proxy } = getCurrentInstance();
const { D_ZDY_SJQX } = proxy.$dict("D_ZDY_SJQX");
import {
  getRoleList,
  addSysRole,
  updateSysRole,
  deleteSysRole
} from "@/api/user-manage";
import { useRouter } from "vue-router";
const searchBox = ref(null); // 搜索盒子
const keyCount = ref(0); //tabel组件刷新值
const tableHeight = ref(); // 表格高度
//查询参数
const total = ref(0);
const page = ref(1);
const size = ref(20);
const currentRow = ref({});
const listQuery = ref({
  page: 1,
  size: 20,
  dictName: "",
  dictCode: "",
  xtZxbz: ""
});
const elform = ref(null);
//验证
const rules = ref({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "change" }],
  roleCode: [{ required: true, message: "请输入角色编码", trigger: "change" }],
  roleDesc: [{ required: true, message: "请输入角色描述", trigger: "change" }],
  orderNo: [{ required: true, message: "请输入排序号", trigger: "change" }],
  dataPermissionLevel: [
    { required: true, message: "请选择权限范围", trigger: "change" }
  ]
});
const isEdit = ref(true);
const dialogForm = ref({});
const buttonLoading = ref(false);
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  params.current = params.page;
  const res = await getRoleList(params);
  tableData.value = res?.records;
  total.value = Number(res.total);
};

const handleFilter = () => {
  listQuery.value.page = 1;
  getListData();
};
getListData();
const reset = () => {
  listQuery.value = {
    page: 1,
    size: 5,
    roleName: ""
  };
  getListData();
};
// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.size = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.page = currentPage;
  getListData();
};

/**修改字典 */
const updateDict = (row) => {
  isEdit.value = true;
  row.dataPermissionLevel = "" + row.dataPermissionLevel;
  dialogForm.value = { ...row };

  dialogFormVisible.value = true;
};

/**privileges 分配权限 */
const privilegesDialogVisible = ref(false);
const privilegesHanlder = (row) => {
  privilegesDialogVisible.value = true;
  currentRow.value = { ...row };
};

const addRole = (row) => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
};
const onSave = () => {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    updateSysRole({
      ...dialogForm.value
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("修改成功");
        buttonLoading.value = false;
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const onAdd = () => {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    addSysRole({
      ...dialogForm.value
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("操作成功");
        buttonLoading.value = false;
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const delRole = (row) => {
  buttonLoading.value = true;
  deleteSysRole({
    id: Number(row.id)
  })
    .then((res) => {
      ElMessage.success("删除成功");
      buttonLoading.value = false;
      handleFilter();
    })
    .finally(() => {
      buttonLoading.value = false;
    });
};

const closeDialog = () => {
  dialogForm.value = {};
  dialogFormVisible.value = false;
};

//分配用户
const router = useRouter();
const allocationUser = (row) => {
  //
  router.push(`/user/allocationUser/${row.id}`);
};
// 高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight  - searchBox.value.offsetHeight - 240;
};
onMounted(() => {
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";
.user-manage-container {
  .table-header-wrap {
    margin-bottom: 22px;
  }

  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
  }
}
</style>
