<template>

  <MOSTY.PageTree :pageTitle="'角色列表'" :isShowLeftTree="false">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
      <el-divider />
      <div class="btnBox">
        <el-button type="primary" @click="addRole('add', '')">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>新增</span>
        </el-button>
      </div>

    </template>
    <template #table>
      <div style="height:calc(100vh - 380px);">
        <el-table stripe :data="tableData" border :height="'100%'" style="width: 100%" :key="keyCount">
          <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 prop="roleDesc" 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="400">
            <template #default="{ row }">
              <span class="operedit" @click="addRole('edit', row)">
                <el-icon>
                  <EditPen />
                </el-icon>修改</span>
              <span class="operedit" @click="allocationUser(row)">
                <el-icon>
                  <EditPen />
                </el-icon>管理用户</span>
              <span class="operedit" @click="privilegesHanlder(row)">
                <el-icon>
                  <EditPen />
                </el-icon>菜单权限</span>
              <!-- <el-button @click="Functionalhandel(row)" size="small">APP功能权限</el-button> -->
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="delRole(row)">
                <template #reference>
                  <span span class="operdel" size="small">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    删除</span>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="listQuery" @changeNo="handleCurrentChange" @changeSize="handleSizeChange">
          </MOSTY.Pages>
        </div>
      </div>

      <div v-if="dialogFormVisible" class="dialog">
        <MOSTY.FromPage :title="titleValue">
          <template #content>
            <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="备注" 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>
          </template>
          <template #footer>

            <el-button type="primary" :loading="buttonLoading" :disabled="disabled" @click="onSave">
              <el-icon>
                <DocumentChecked />
              </el-icon>
              <span>保存</span>
            </el-button>
            <el-button @click="closeDialog" type="primary">
              <el-icon>
                <DocumentDelete />
              </el-icon>
              <span>关闭</span>
            </el-button>
          </template>
        </MOSTY.FromPage>


      </div>
    </template>
  </MOSTY.PageTree>
  <PrivilegesDialog v-model="privilegesDialogVisible" :roleId="currentRow.id"></PrivilegesDialog>
  <FunctionalDialog v-model="FunctionalDialogVisible" :roleId="currentRowFc.id" @close="close"></FunctionalDialog>

</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import PrivilegesDialog from "./conponents/PrivilegesDialog.vue";
import FunctionalDialog from "./conponents/FunctionalDialog.vue";
import { ElMessage } from "element-plus";
import { ref, onMounted, getCurrentInstance, reactive, onUnmounted } from "vue";
const { proxy } = getCurrentInstance();
const searchArr = reactive([
  {
    showType: "input",
    prop: "roleName",
    lable: '角色名称:',
    width: '250px',
    placeholder: "请输入角色名称"
  }
]);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  total: 0

}); //查询表单
const tableData = ref([]); // 表格数据
const dialogFormVisible = ref(false); //弹窗
const titleValue = ref("新增角色");
const buttonLoading = ref(false); //按钮加载
const dialogForm = ref({}); //新增编辑表单数据
//验证
const rules = ref({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "change" }],
  roleCode: [{ required: true, message: "请输入角色编码", trigger: "change" }],
  roleDesc: [{ required: true, message: "请输入角色描述", trigger: "change" }]
});

import { deleteSysRole } from "@/api/user-manage";
const router = useRouter();
import { useRouter } from "vue-router";
const searchBox = ref(null); // 搜索盒子
const keyCount = ref(0); //tabel组件刷新值
const tableHeight = ref(); // 表格高度
const currentRow = ref({});
const currentRowFc = ref({});
const elform = ref(null);
const privilegesDialogVisible = ref(false);

onMounted(() => {
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
  getListData();
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});

// 获取数据的方法
function getListData() {
  listQuery.value.size = listQuery.value.pageSize
  listQuery.value.current = listQuery.value.pageCurrent
  getApi(listQuery.value, "/mosty-base/sysRole/selectPage").then((res) => {
    tableData.value = res.records ? res.records : [];
    listQuery.value.total = res.total;
  });
}

// 新增 - 修改
function addRole(type, row) {
  if (type == "add") {
    titleValue.value = "新增角色";
  } else {
    titleValue.value = "编辑角色";
    dialogForm.value = { ...row };
  }
  dialogFormVisible.value = true;
}

//下拉菜单点击事件
const handleClick = (e) => { };

// 提交按钮
function onSave() {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    if (dialogForm.value.id) {
      postApi(dialogForm.value, "/mosty-base/sysRole/updateSysRole")
        .then(() => {
          dialogFormVisible.value = false;
          ElMessage.success("修改成功");
          buttonLoading.value = false;
          getListData();
        })
        .catch(() => {
          buttonLoading.value = false;
        });
    } else {
      postApi(dialogForm.value, "/mosty-base/sysRole/addSysRole")
        .then(() => {
          dialogFormVisible.value = false;
          ElMessage.success("新增成功");
          buttonLoading.value = false;
          getListData();
        })
        .catch(() => {
          buttonLoading.value = false;
        });
    }
    dialogForm.value = {};
  });
}

// 查询
const onSearch = (obj) => {
  listQuery.value.roleName = obj.roleName;
  listQuery.value.pageCurrent = 1;
  getListData();
};
// 重置
const reset = () => {
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 10,
    roleName: ""
  };
  getListData();
};
// 分页改变触发
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

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

// 分配权限
const privilegesHanlder = (row) => {
  currentRow.value = { ...row };
  privilegesDialogVisible.value = true;
};
//分配功能
const FunctionalDialogVisible = ref(false);
// app权限分配
const Functionalhandel = (row) => {
  FunctionalDialogVisible.value = true;
  currentRowFc.value = { ...row };
};
//弹窗关闭
const close = () => {
  FunctionalDialogVisible.value = false;
  getListData();
};
const delRole = (row) => {
  buttonLoading.value = true;
  deleteSysRole({
    id: row.id
  })
    .then(() => {
      ElMessage.success("删除成功");
      buttonLoading.value = false;
      getListData();
    })
    .finally(() => {
      buttonLoading.value = false;
    });
};


const closeDialog = () => {

  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      dialogForm.value = {};
      dialogFormVisible.value = false;
    })
    .catch(() => {
      // catch error
    })

};

//分配用户
const allocationUser = (row) => {

  router.push({
    path: `/user/allocationUser`,
    query: {
      id: row.id
    }
  });
};

</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.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>
