<template>
  <n-modal v-model:show="showModal" :on-after-leave="handleCloseModal" :mask-closable="false" :bordered="false">
    <n-card :title="props.modalTitle" class="w-500px rounded-16px shadow-sm">
      <template #header-extra>
        <Icon icon="ic:sharp-close" class="text-size-22px cursor-pointer" @click="showModal = false" />
      </template>
      <div>
        <n-form
          ref="formRef"
          :disabled="isView"
          label-placement="left"
          :label-width="80"
          :model="modalForm"
          :rules="rules"
        >
          <n-form-item label="角色名称" path="roleName">
            <n-input
              v-model:value="modalForm.roleName"
              maxlength="20"
              show-count
              :clearable="true"
              placeholder="请输入角色名称"
            />
          </n-form-item>

          <n-form-item label="角色描述" path="roleDesc">
            <n-input
              v-model:value="modalForm.roleDesc"
              maxlength="20"
              show-count
              :clearable="true"
              placeholder="请输入权限描述"
            />
          </n-form-item>
          <n-form-item label="角色状态" path="status">
            <n-radio-group v-model:value="modalForm.status" name="radiogroup">
              <n-space>
                <n-radio v-for="status in SYSTEM_ROLE_STATUS" :key="status.value" :value="status.value">
                  {{ status.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
          <n-form-item label="菜单权限" path="menuIds">
            <div class="max-h-200px overflow-y-scroll">
              <n-tree
                v-if="showEditTree && modalTitle !== '新增角色'"
                class="w-full"
                block-line
                :disabled="isView"
                :default-expand-all="isView"
                checkable
                cascade
                :data="menuTree"
                key-field="menuId"
                label-field="menuName"
                :default-checked-keys="defaultCheckedKeys"
                @update:checked-keys="updateCheckedKeys"
              />

              <n-tree
                v-if="showAddTree && modalTitle === '新增角色'"
                class="w-full"
                block-line
                :disabled="isView"
                checkable
                cascade
                :data="menuTree"
                key-field="menuId"
                label-field="menuName"
                @update:checked-keys="updateCheckedKeys"
              />
            </div>
          </n-form-item>
        </n-form>
      </div>
      <template v-if="!isView" #footer>
        <div class="w-full flex justify-center">
          <NButton @click="handleCloseModal">取消</NButton>
          <NButton :loading="submitLoading" class="ml-4" type="primary" @click="handleSubmit">提交</NButton>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { Icon } from '@iconify/vue';
import { fetchGetMenuList, fetchGetRoleDetail, fetchAddRole, fetchGetRoleMenuDetail, fetchEditRole } from '@/service';
import { SYSTEM_ROLE_STATUS_ENABLE, SYSTEM_ROLE_STATUS } from '@/const/system';

const emits = defineEmits(['get-role-list']);

interface Props {
  modalTitle: string;
  curEditRoleId: number;
}
const props = defineProps<Props>();

const showModal = ref(false);
const submitLoading = ref(false);
const menuIds = ref<number[]>([]);
const modalForm = ref<System.RoleForm>({
  roleName: '',
  roleDesc: '',
  // roleKey: '',
  // roleSort: 0,
  status: SYSTEM_ROLE_STATUS_ENABLE
});
const rules = ref<FormRules>({
  roleName: { required: true, message: '角色名称不能为空', trigger: ['input', 'blur'] },
  roleDesc: { required: true, message: '角色描述不能为空', trigger: ['input', 'blur'] },
  // roleSort: { required: true },
  status: { required: true, trigger: ['blur'] }
});

const roundMenuList = ref<any>([]);

/** 处理树的选中： 需要找出menuIds中是否有子节点的父节点不在menuIds中 */
const resultMenuIds = ref<any[]>([]);
function handleTreeChecked(ids: any) {
  ids.forEach((item: any) => {
    digui(item);
  });
}
function digui(id: any) {
  const flag = roundMenuList.value.find((ite: { menuId: any }) => ite.menuId === id);
  if (flag && !resultMenuIds.value.includes(flag.menuId) && flag.menuId !== 0) {
    resultMenuIds.value.push(flag.menuId);
    digui(flag.parentId);
  }
}
const formRef = ref<FormInst | null>(null);
/** 提交表单 */
async function handleSubmit() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      submitLoading.value = true;
      const apis = {
        fetchEditRole,
        fetchAddRole
      };
      const apikey = props.modalTitle === '修改角色' ? 'fetchEditRole' : 'fetchAddRole';
      const params = {
        ...modalForm.value,
        menuIds: resultMenuIds.value
      };
      handleTreeChecked(menuIds.value);
      const { data } = await apis[apikey](params);
      if (data?.ok) {
        window.$message?.success('操作成功');
        handleCloseModal();
        emits('get-role-list');
      }
    }
    submitLoading.value = false;
    return errors;
  });
}
/** 打开弹窗 */
function handleShowModal() {
  showModal.value = true;
}
const defaultCheckedKeys = ref<number[]>([]);
const showEditTree = ref(false);
const showAddTree = ref(false);

/** 关闭弹窗 */
function handleCloseModal() {
  showModal.value = false;
  modalForm.value = {
    roleName: '',
    roleDesc: '',
    // roleKey: '',
    // roleSort: 0,
    status: SYSTEM_ROLE_STATUS_ENABLE
  };
  defaultCheckedKeys.value = [];
  menuIds.value = [];
  resultMenuIds.value = [];
  showEditTree.value = false;
  showAddTree.value = false;
}

function updateCheckedKeys(v: number[]) {
  (menuIds.value as number[]) = v;
}

/** 获取用户详情 */
async function getRoleDetail<T>(roleId: T) {
  const { data } = await fetchGetRoleDetail(roleId);
  if (data.ok && data.data) {
    modalForm.value = data?.data;
  }
}

const menuTree = ref([]);
/** 获取菜单树 */
async function getMenuTree() {
  const { data } = await fetchGetMenuList();
  if (data?.ok) {
    menuTree.value = data.data;
    roundMenuTree(menuTree.value);
  }
}

/** 获取角色菜单详情 */
async function getRoleMenuDetail<T>(roleId: T) {
  const { data } = await fetchGetRoleMenuDetail(roleId);
  const menuIdArray: number[] = [];
  if (data?.ok) {
    data.data.checkedKeys.forEach((id: any) => {
      menuIdArray.push(id);
    });
    defaultCheckedKeys.value = [...menuIdArray];
    menuIds.value = [...menuIdArray];
    showEditTree.value = true;
  }
}

function roundMenuTree(menu: any) {
  menu.forEach((item: any) => {
    (roundMenuList.value as any[]).push(item);
    if (item.children) {
      roundMenuTree(item.children);
    }
  });
}

watch(showModal, val => {
  if (val) {
    showAddTree.value = true;
    getMenuTree();
    setTimeout(() => {
      if (props.curEditRoleId !== -1) {
        getRoleDetail(props.curEditRoleId);
        getRoleMenuDetail(props.curEditRoleId);
      }
    });
  }
});

const isView = computed(() => props.modalTitle === '查看角色');
defineExpose({
  handleShowModal
});
</script>
