<template>
  <div>
    <el-card class="box-card">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :table-events="{
          select: selectRow,
        }"
        :action-list="[
          {
            text: '添加角色',
            action: () => clickAdd(),
          },
          {
            text: '权限配置',
            action: () => openRoomModal(),
            disabled: selectData.length != 1,
          },
        ]"
        @get-list="getList"
        @clickReset="clickReset">
        <template #code="{ item }">
          <div>
            <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickCode(item)">{{ item.code }}</a>
          </div>
        </template>
      </byTable>
    </el-card>

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

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

<script setup>
import byTable from "/src/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "/src/components/byForm/index";

const { proxy } = getCurrentInstance();
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    tenantId: "000000",
  },
});
const loading = ref(false);
const config = computed(() => {
  return [
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    {
      attrs: {
        label: "角色编码",
        prop: "roleKey",
      },
    },
    {
      attrs: {
        label: "角色名称",
        prop: "roleName",
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "操作",
        width: 160,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "编辑",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickUpdate(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(() => {
                    ElMessage({ message: "删除成功", type: "success" });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
      tenantId: "000000",
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  loading.value = true;
  proxy.get("/tenantRole/list", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows.map((x) => ({
      ...x,
      isCheck: true,
    }));
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  getList("", true);
};
const formOption = reactive({
  inline: true,
  labelWidth: "100px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {},
  treeData: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "roleKey",
      label: "角色编码",
      itemType: "text",
    },
    {
      type: "input",
      prop: "roleName",
      label: "角色名称",
      itemType: "text",
    },
  ];
});
const rules = ref({
  roleKey: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});
const openDialog = ref(false);
const modalType = ref("add");
const submit = ref(null);
const clickAdd = () => {
  modalType.value = "add";
  formData.data = {
    roleKey: "",
    roleName: "",
    status: "0",
    tenantId: "000000",
    roleSort: 1,
  };
  openDialog.value = true;
};
const clickUpdate = (item) => {
  modalType.value = "edit";
  formData.data = proxy.deepClone(item);
  openDialog.value = true;
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    const method = modalType.value == "add" ? "POST" : "PUT";
    proxy.post("/tenantRole", formData.data, method).then(() => {
      ElMessage({
        message: modalType.value == "add" ? "添加成功" : "编辑成功",
        type: "success",
      });
      openDialog.value = false;
      getList();
    });
  });
};
const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};
const treeData = ref([]);
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;
};
let roomDialogVisible = ref(false);
const tree = ref(null);
const defaultProps = {
  children: "children",
  label: "label",
};
const openRoomModal = () => {
  proxy.get("/tenantRole/roleMenuTreeSelect/" + selectData.value[0].roleId).then((res) => {
    if (res.code == 200) {
      treeData.value = res.menus;
      let data = getSubset(res.menus, []);
      formData.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",
      {
        ...selectData.value[0],
        menuIds: data,
      },
      "PUT"
    )
    .then(() => {
      ElMessage({ message: "保存成功", type: "success" });
      roomDialogVisible.value = false;
    });
};
</script>

<style lang="scss" scoped>
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
</style>
