<template>
  <el-drawer
    v-model="isDrawer"
    :width="width"
    placement="right"
    :title="title"
    @close="handleReset"
  >
    <el-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="80"
    >
      <el-form-item label="角色编码" prop="roleCode">
        <el-input
          placeholder="请输入角色编码"
          v-model="formParams.roleCode"
          :disabled="formParams.roleId ? true : false"
        />
      </el-form-item>

      <el-form-item label="角色名称" prop="roleName">
        <el-input placeholder="请输入角色名称" v-model="formParams.roleName" />
      </el-form-item>
      <el-form-item label="角色权限" prop="permissionIds">
        <el-card shadow="hover">
          <el-space>
            <el-checkbox v-model:checked="isSpread" @change="packHandle">展开/收起</el-checkbox>
            <el-checkbox v-model="isAll" @change="handleCheckAll">全选/全不选</el-checkbox>
          </el-space>
          <el-divider />
          <el-tree
            ref="treeRef"
            show-checkbox
            node-key="key"
            :data="props.permissionList"
            check-strictly
            @check="checkedTree"
          />
        </el-card>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" placeholder="请输入备注" v-model="formParams.remark" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-space>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" :loading="subLoading" @click="formSubmit">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue';
  import { ElMessage } from 'element-plus';
  import type { formParamsType } from './types';

  import { addAdminRole, editAdminRole, roleAdminInfo } from '@/api/system/role';
  import { getTreeValues } from '@/utils/helper/treeHelper';

  const rules = {
    roleCode: {
      required: true,
      message: '角色编码不能为空',
      trigger: 'blur',
    },
    roleName: {
      required: true,
      message: '角色名称不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);

  const props = defineProps({
    title: {
      type: String,
      default: '添加角色',
    },
    width: {
      type: Number,
      default: 450,
    },
    permissionList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    roleId: null,
    roleType: null,
    roleName: '',
    roleCode: '',
    remark: '',
    permissions: [],
    permissionKeys: [],
  });

  const message = ElMessage;
  const checkedKeys = ref<number[]>([]);
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const isSpread = ref(false);
  const isAll = ref(false);
  const treeRef = ref();
  const expandedKeys = ref();

  const formParams = ref<formParamsType>(defaultValueRef());

  function treeNodeExpand(status) {
    for (var i = 0; i < treeRef.value.store._getAllNodes().length; i++) {
      treeRef.value.store._getAllNodes()[i].expanded = status;
    }
  }

  function packHandle(value) {
    if (value) {
      treeNodeExpand(true);
      expandedKeys.value = props?.permissionList?.map((item: any) => item.key as string) as [];
    } else {
      expandedKeys.value = [];
      treeNodeExpand(false);
    }
  }

  function handleCheckAll(value) {
    if (!value) {
      formParams.value.permissions = [];
      treeRef.value!.setCheckedKeys([]);
    } else {
      formParams.value.permissions = getAllIds(
        props?.permissionList as { key: number; children: [] }[],
      );
      const keys = getTreeValues(props.permissionList || [], 'key');
      treeRef.value!.setCheckedKeys(keys);
    }
  }

  function getAllIds(list: { key: number; children: [] }[] = [], ids: number[] = []) {
    for (let item of list) {
      !ids.includes(item.key) && ids.push(item.key);
      if (item.children && item.children.length) getAllIds(item.children, ids);
    }
    return ids;
  }

  function checkedTree(_, checkedInfo) {
    const keys = checkedInfo.checkedKeys;
    const halfKeys = checkedInfo.halfCheckedKeys;
    formParams.value.permissions = keys;
    checkedKeys.value = keys;
    formParams.value.permissionKeys = halfKeys;
  }

  function openDrawer(roleId?) {
    if (roleId) {
      formParams.value.roleId = roleId;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((valid) => {
      if (!valid) {
        return message.error('请填写完整信息');
      }
      if (formParams.value.roleId) {
        editAdminRole(formParams.value).then((_) => {
          message.success('编辑成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
      } else {
        formParams.value.roleType = 2;
        addAdminRole(formParams.value).then((_) => {
          message.success('添加成功');
          emit('change');
          handleReset();
          closeDrawer();
        });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
    treeRef.value!.setCheckedKeys([]);
  }

  function getInfo() {
    roleAdminInfo({ roleId: formParams.value.roleId }).then((res) => {
      const info = {
        roleId: res.id,
        roleName: res.roleName,
        roleCode: res.roleCode,
        remark: res.remark,
        permissions: res.permissionIds || [],
        permissionKeys: res.permissionKeys || [],
      };
      formParams.value = info;
      isDrawer.value = true;
      nextTick(() => {
        console.log('res.permissionIds', res.permissionIds);
        treeRef.value?.setCheckedKeys(res.permissionIds);
      });
    });
  }

  onMounted(() => {});

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
