<script lang="ts">
export default {
  name: 'role'
};
</script>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElTree, ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import {
  roleManage,
  deleteRole,
  addAuditRole,
  getAllPermission,
  queryRolePermission
} from '@/api/system/role';
import {
  RoleQueryParam,
  RoleItem,
  RolePermissionFormData
} from '@/types/api/system/role';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const treeRef = ref<InstanceType<typeof ElTree>>();

// 强制必选权限（永续合约父级50 + 交易对管理51），不可取消
const REQUIRED_PERMISSION_IDS = [50, 51];

const state = reactive({
  loading: true,
  loading2: false,
  queryParams: {
    pageNo: 1,
    pageSize: 15,
  } as RoleQueryParam,
  list: [] as RoleItem[],
  total: 0,
  isCreate: false,
  dialog: {
    title: '',
    visible: false,
    loading: false,
  },
  formData: {
    id: 0,
    role: "",
    description: "",
    permissions: ""
  } as RolePermissionFormData,
  rules: {
    role: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
  },
  firstTreeIds: [] as number[],
  ids: [] as number[],
  checked: [] as number[],
  permissionList: [] as any
});

const {
  loading,
  loading2,
  queryParams,
  list,
  total,
  isCreate,
  dialog,
  formData,
  rules,
  permissionList
} = toRefs(state);

function handleQuery() {
  state.loading = true;
  roleManage(state.queryParams).then(({ data }) => {
    state.list = data.content;
    state.total = data.totalElements;
    state.loading = false;
  });
}

function handleAdd() {
  state.dialog = {
    title: '添加角色',
    visible: true,
    loading: false
  };
  state.isCreate = true;
  formData.value.id = 0;
  formData.value.role = "";
  formData.value.description = "";
  formData.value.permissions = "";
  // 新增时默认预选强制权限，等弹窗 DOM 渲染后设置树选中
  state.checked = [...REQUIRED_PERMISSION_IDS];
  nextTick(() => setCheckedRoles([...REQUIRED_PERMISSION_IDS]));
}

/**
 * 提交新增/编辑
 */
function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading2.value = true;
      let _msg = formData.value.id > 0 ? '修改成功' : '添加成功'
      let formDataPermissions = state.checked.length > 0
        ? [...new Set(state.firstTreeIds.concat(state.checked))].join(',')
        : "";
      formData.value.permissions = formDataPermissions
      addAuditRole(state.formData).then(() => {
        cancel();
        loading2.value = false;
        ElMessage.success(_msg);
        handleQuery();
      });
    }
  });
}

/**
 * 取消
 */
function cancel() {
  dialog.value.visible = false;
  dialog.value.loading = false;
  formData.value.id = 0;
  formData.value.role = "";
  formData.value.description = "";
  formData.value.permissions = "";
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 *  删除
 */
function handleDelete(row: any) {
  ElMessageBox.confirm('确认删除角色【' + row.role + '】?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(() => {
    deleteRole({ id: row.id }).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  })
  .catch(() => ElMessage.info('已取消删除'));
}

/**
 * 修改权限
 * @param row 
 */
const handleEdit = (row: any) => {
  state.dialog = {
    title: '修改权限',
    visible: true,
    loading: true
  };
  state.isCreate = false;
  formData.value.id = row.id;
  formData.value.role = row.role;
  formData.value.description = row.description;
  formData.value.permissions = "";
  
  state.checked = [];
  queryRolePermission({ roleId: row.id }).then(({ data }) => {
    data.forEach((item: any) => {
      if (item.subMenu != null) {
        item.subMenu.forEach((citem: any) => {
          state.checked.push(citem.id)
        })
      }
    })
    // 确保强制权限始终存在
    REQUIRED_PERMISSION_IDS.forEach(id => {
      if (!state.checked.includes(id)) {
        state.checked.push(id);
      }
    });
  }).then(() => {
    setCheckedRoles(state.checked)
    state.dialog.loading = false;
  })
}

/**
 * 改变节点选中时触发
 */
const onRoleCheck = (row: any, checked: any) => {
  const keys: number[] = checked.checkedKeys;
  // 强制权限不可被取消
  REQUIRED_PERMISSION_IDS.forEach(id => {
    if (!keys.includes(id)) keys.push(id);
  });
  state.checked = keys;
  setCheckedRoles(keys);
}

/**
 * 加载权限
 */
const loadAllPermission = () => {
  getAllPermission().then(({ data }) => {
    data.forEach(item => {
      state.firstTreeIds.push(item.id)
      let firstTree = {
        id: item.id,
        label: item.title,
        disabled: REQUIRED_PERMISSION_IDS.includes(item.id),
        children: [] as any
      };
      item.subMenu.forEach(it => {
        state.ids.push(it.id)
        let secTree = {
          id: it.id,
          label: it.title,
          disabled: REQUIRED_PERMISSION_IDS.includes(it.id)
        };
        firstTree.children.push(secTree)
      })
      state.permissionList.push(firstTree);
    })
  })
}

const setCheckedRoles = (keys: any[]) => {
  treeRef.value!.setCheckedKeys(keys, false)
}

const selectAll = () => {
  state.checked = state.ids
  setCheckedRoles(state.ids)
}

const selectNull = () => {
  // 全部取消时保留强制权限
  state.checked = [...REQUIRED_PERMISSION_IDS];
  setCheckedRoles([...REQUIRED_PERMISSION_IDS]);
}

const defaultProps = {
  children: 'children',
  label: 'label',
}

onMounted(() => {
  loadAllPermission();
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="list"
      highlight-current-row
      border
      >
      <el-table-column label="ID" prop="id" min-width="80" align="center" />
      <el-table-column label="角色名称" prop="role" min-width="160" align="center" />
      <el-table-column label="备注" prop="description" min-width="200" align="center" />
      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页工具条 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 表单弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="760px"
      destroy-on-close
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="role">
          <el-input type="text" v-model="formData.role" placeholder="请输入" :readonly="!isCreate" :disabled="!isCreate" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input type="textarea" v-model="formData.description" placeholder="请输入" />
        </el-form-item>
        <el-form-item width-label="0">
            <el-button type="primary" @click="selectAll">全部选中</el-button>
            <el-button type="default" @click="selectNull">全部取消</el-button>
        </el-form-item>
        <el-form-item width-label="0" prop="permissions">
          <el-tree
            ref="treeRef"
            v-loading="dialog.loading"
            :data="permissionList"
            show-checkbox
            node-key="id"
            @check="onRoleCheck"
            highlight-current
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="loading2" @click="submitFormData">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
