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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import {
  permissionManage,
  addAuditPermission,
  delPermission
} from '@/api/system/perm';
import {
  PermQueryParam,
  PermItem,
  PermFormData
} from '@/types/api/system/perm';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: true,
  // 选中ids数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  queryParams: {
    pageNo: 1,
    pageSize: 15,
  } as PermQueryParam,
  list: [] as PermItem[],
  total: 0,
  isCreate: false,
  dialog: {
    title: '',
    visible: false
  },
  formData: {} as PermFormData,
  rules: {
    name: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
    title: [{ required: true, message: '请选择广告状态', trigger: 'blur' }],
    parentId: [{ required: true, message: '请上传广告图片', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入排序数值', trigger: 'blur' }]
  },
  topList: [] as PermItem[]
});

const {
  loading,
  multiple,
  queryParams,
  list,
  total,
  dialog,
  formData,
  rules,
  topList
} = toRefs(state);

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

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
}

function handleAdd() {
  state.dialog = {
    title: '添加权限',
    visible: true
  };
  state.isCreate = true;
  formData.value.id = null;
  formData.value.name = "";
  formData.value.title = "";
  formData.value.parentId = 0;
  formData.value.description = "";
  formData.value.sort = 0;

  permissionTop();
}

/**
 * 提交新增/编辑
 */
function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (state.formData.id) {
        addAuditPermission(state.formData).then(() => {
          ElMessage.success('修改成功');
          cancel();
          handleQuery();
          loading.value = false;
        });
      } else {
        addAuditPermission(state.formData).then(() => {
          cancel();
          ElMessage.success('添加成功');
          handleQuery();
          loading.value = false;
        });
      }
    }
  });
}

/**
 * 取消
 */
function cancel() {
  dialog.value.visible = false;
  formData.value.id = null;
  formData.value.name = "";
  formData.value.title = "";
  formData.value.parentId = 0;
  formData.value.description = "";
  formData.value.sort = 0;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 * 删除
 */
function handleDelete() {
  const ids = [state.ids].join(',');
  ElMessageBox.confirm('确认删除已选中的' + state.ids.length + '条数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(() => {
    delPermission({ ids: ids }).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  })
  .catch(() => ElMessage.info('已取消删除'));
}

/**
 * 编辑
 * @param row 
 */
const viewEdit = (row: any) => {
  state.dialog = {
    title: '编辑权限',
    visible: true
  };
  state.isCreate = false;
  formData.value.id = row.id;
  formData.value.name = row.name;
  formData.value.title = row.title;
  formData.value.parentId = row.parentId;
  formData.value.description = row.description;
  formData.value.sort = row.sort;

  permissionTop();
}

const permissionTop = () => {
  let queryTopParams = {
    pageNo: 1,
    pageSize: 500,
    parentId: 0
  } as PermQueryParam;
  permissionManage(queryTopParams).then(({ data }) => {
    state.topList = data.content
  })
}

onMounted(() => {
  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-button
          type="danger"
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      highlight-current-row
      border
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" align="center" />
      <el-table-column label="父级ID" prop="parentId" align="center" />
      <el-table-column label="权限标题" prop="title" align="center" />
      <el-table-column label="权限名称" prop="name" align="center" />
      <el-table-column label="权限描述" prop="description" align="center" />
      <el-table-column label="排序" prop="sort" align="center" />
      <el-table-column label="操作" align="center" width="160" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="viewEdit(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="500px"
      destroy-on-close
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="权限标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="权限目录" prop="parentId">
          <el-select
            v-model="formData.parentId"
            placeholder="请选择"
            clearable
            style="width: 200px"
            >
            <el-option
              :key="0"
              :value="0"
              label="作为一级目录"
              style="color: #ec0909"
              />
            <el-option
              v-for="item in topList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              />
          </el-select>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input type="textarea" v-model="formData.description" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="formData.sort" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormData">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
