<template>
  <div class="tenant">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      highlight-current-row
      :table-events="{
        select: select,
      }"
      :action-list="[
        {
          text: '添加角色',
          action: () => openModal(),
        },
      ]"
      @get-list="getList">
    </byTable>

    <el-dialog :title="modalType == 'add' ? '添加角色' : '编辑角色'" v-if="dialogVisible" v-model="dialogVisible" width="600" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit"> </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="权限配置" v-model="roomDialogVisible" width="500" v-loading="loadingDialog">
      <el-tree :data="treeData" show-checkbox node-key="id" :default-checked-keys="formAuthority.treeData" :props="defaultProps" ref="tree"> </el-tree>
      <template #footer>
        <el-button @click="roomDialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitTree()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const defaultProps = {
  children: "children",
  label: "label",
};
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    tenantId: useUserStore().user.tenantId,
  },
});
const loading = ref(false);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "角色编码",
        prop: "roleKey",
      },
    },
    {
      attrs: {
        label: "角色名称",
        prop: "roleName",
        align: "left",
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      renderHTML(row) {
        return [
          
          {
            attrs: {
              label: "权限配置",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              openRoomModal(row)
              
            },
          },
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                proxy
                  .post(
                    "/tenantRole/" + row.roleId,
                    {
                      id: row.roleId,
                    },
                    "delete"
                  )
                  .then((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.get("/tenantRole/list", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "roleKey",
      label: "角色编码",
    },
    {
      type: "input",
      prop: "roleName",
      label: "角色名称",
    },
  ];
});
const rules = ref({
  roleKey: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});
const openModal = (val) => {
  modalType.value = "add";
  formData.data = {
    tenantId: useUserStore().user.tenantId,
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    const method = modalType.value == "add" ? "POST" : "PUT";
    loadingDialog.value = true;
    proxy.post("/tenantRole", { ...formData.data, roleSort: 1, status: "0" }, method).then(() => {
      ElMessage({
        message: modalType.value == "add" ? "添加成功" : "编辑成功",
        type: "success",
      });
      dialogVisible.value = false;
      getList();
    });
  });
};
const getDtl = (row) => {
  formData.data = { ...row };
  modalType.value = "edit";
  dialogVisible.value = true;
};
let roomDialogVisible = ref(false);
const treeData = ref([]);
const formAuthority = reactive({
  treeData: [],
});
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
  console.log(_selection.length);
};
const getSubset = (list, data) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].children && list[i].children.length > 0) {
      getSubset(list[i].children, data);
    } else {
      data.push(list[i].id);
    }
  }
  return data;
};
const tree = ref(null);
const openRoomModal = (row) => {
  selection.value = { ...row };
  proxy.get("/tenantRole/roleMenuTreeSelect/" + row.roleId).then((res) => {
    if (res.code == 200) {
      treeData.value = res.menus;
      let data = getSubset(res.menus, []);
      formAuthority.treeData = res.checkedKeys.filter((item) => {
        return data.some((i) => item == i);
      });
      roomDialogVisible.value = true;
    }
  });
};
const noRepeat = (arr) => {
  var newArr = [...new Set(arr)];
  return newArr;
};
const submitTree = () => {
  let data = noRepeat(tree.value.getHalfCheckedKeys().concat(tree.value.getCheckedKeys()));
  proxy
    .post(
      "/tenantRole",
      {
        ...selection.value,
        menuIds: data,
      },
      "PUT"
    )
    .then(() => {
      ElMessage({
        message: "保存成功",
        type: "success",
      });
      roomDialogVisible.value = false;
    });
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
