<template>
  <my-drawer
    :visible="visible"
    :header="title"
    size="80%"
    attach="body"
    :closeOnOverlayClick="false"
    :close-btn="true"
    @close="emit('update:visible', false)"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" labelAlign="top">
      <t-form-item label="角色名称" name="name">
        <t-input v-model="formData.name"></t-input>
      </t-form-item>

      <t-form-item label="绑定权限" required-mark>
        <privilege-edit
          v-if="visible"
          ref="privilegeSetRef"
          :menus="menus"
        ></privilege-edit>
      </t-form-item>
    </t-form>
    <template #foot>
      <div class="box-justify">
        <div></div>
        <div>
          <t-button theme="default" @click="emit('update:visible', false)"
            >取消</t-button
          >
          <t-button theme="primary" @click="submitHandler">保存</t-button>
        </div>
      </div>
    </template>
  </my-drawer>
</template>
<script setup name="EditRoleDialog">
import { ref, reactive, watch, computed, onMounted, nextTick } from 'vue';
import { getAllMenuResource, addRole, getRoleDetail } from '@/api/user';
import { MessagePlugin } from 'tdesign-vue-next';
import PrivilegeEdit from './privilege-edit.vue';

const props = defineProps({
  visible: Boolean,
  curRow: Object,
});
const emit = defineEmits(['update:visible', 'success']);

const title = computed(() => {
  return (props.curRow?.id ? '编辑' : '新增') + '角色';
});

const formRef = ref(null);
const privilegeSetRef = ref(null);
const formData = reactive({
  name: '',
  privilegeIds: [],
});
const curRoleBindIds = ref([]);
const rules = {
  name: [
    {
      required: true,
      message: '请输入角色名',
    },
  ],
};
let menus = ref([]);

onMounted(() => {
  getMenus();
});

async function getMenus() {
  const data = await getAllMenuResource();
  menus.value = (data || []).map((item) => {
    item.parentId = null;
    return item;
  });
}
const getDetail = async () => {
  let privilegeIds = [],
    dataPermissionInfo = [],
    disabledIds = [];

  let id = props.curRow?.id;
  if (id) {
    let roleDetail = await getRoleDetail({ roleId: id });
    privilegeIds = JSON.parse(roleDetail.privilegeIds || '[]').map((item) =>
      String(item)
    );
    dataPermissionInfo = roleDetail.dataPermissionInfo || [];
    formData.name = roleDetail.name;
    formData.privilegeIds = privilegeIds;
  }

  nextTick(() => {
    formRef.value.clearValidate();
    privilegeSetRef.value.buildTableData(
      privilegeIds,
      dataPermissionInfo,
      disabledIds
    );
  });
};

const submitHandler = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  const { privilegeIds } = privilegeSetRef.value.getSelectedPrivileges();
  if (!privilegeIds.length) {
    MessagePlugin.error('请设置功能权限！');
    return;
  }

  const res = await addRole({
    name: formData.name,
    privilegeIds,
    id: props.curRow?.id || undefined,
  }).catch(() => {});

  if (!res) return;

  MessagePlugin.success('操作成功');
  emit('update:visible', false);
  emit('success');
};

watch(
  () => props.visible,
  (val) => {
    if (val) getDetail();
  }
);
</script>
