<template>
  <div class="p-2 auto-overflow-y">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="70px">
            <el-form-item label="岗位编码" prop="postCode">
              <el-input v-model="queryParams.postCode" placeholder="请输入岗位编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="岗位名称" prop="postName">
              <el-input v-model="queryParams.postName" placeholder="请输入岗位名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="岗位状态" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:post:add']" type="primary" plain icon="Plus" @click="openForm('add')">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:post:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:post:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:post:export']" type="warning" plain icon="Download" @click="handleExport"> 导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="postList" max-height="calc(100vh - 23.75rem)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="columns[0].visible" label="岗位编号" align="center" prop="postId" />
        <el-table-column v-if="columns[1].visible" label="岗位编码" align="center" prop="postCode" />
        <el-table-column v-if="columns[2].visible" label="岗位名称" align="center" prop="postName" />
        <el-table-column v-if="columns[3].visible" label="排序" align="center" prop="postSort" />
        <el-table-column v-if="columns[4].visible" label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="系统岗位" align="center" prop="sysData">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.sysData" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:post:edit']" link type="primary" icon="Edit" @click="openForm('update', scope.row.postId)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.sysData !== 'Y'" content="删除" placement="top">
              <el-button v-hasPermi="['system:post:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!--    弹出的详细页面，增加和修改-->
    <detail-form ref="detailFormRef" apped-to-body @success="getList" />
  </div>
</template>

<script setup name="Post" lang="ts">
import api from '@/api/system/params/post';
import { PostQuery, PostVO } from '@/api/system/params/post/types';
import DetailForm from '@/views/system/params/post/PostForm.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, sys_yes_no } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_yes_no'));

const postList = ref<PostVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
// 选中数据的是否系统数据项清单
const sysDatas = ref<Array<string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
/** 列隐藏信息 */
const columns = ref<FieldOption[]>([
  { key: 0, label: `岗位编号`, visible: false, children: [] },
  { key: 1, label: `岗位编码`, visible: true, children: [] },
  { key: 2, label: `岗位名称`, visible: true, children: [] },
  { key: 3, label: `排序`, visible: true, children: [] },
  { key: 4, label: `状态`, visible: true, children: [] },
  { key: 5, label: `系统岗位`, visible: true, children: [] },
  { key: 6, label: `创建时间`, visible: true, children: [] }
]);
/** 查询参数 */
const queryParams = reactive<PostQuery>({
  pageNum: 1,
  pageSize: 20,
  postCode: '',
  postName: '',
  status: ''
});
/** 弹出对话框，子组件引入 */
const detailFormRef = ref();
const openForm = (type: string, id?: number) => {
  detailFormRef.value.open(type, id);
};
/** 查询岗位列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.listPost(queryParams);
  postList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PostVO[]) => {
  ids.value = selection.map((item) => item.postId);
  sysDatas.value = selection.map((item) => item.sysData);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 修改按钮操作 */
const handleUpdate = async (row?: PostVO) => {
  const postId = row?.postId || ids.value[0];
  detailFormRef.value.open('edit', postId);
};
/** 删除按钮操作 */
const handleDelete = async (row?: PostVO) => {
  const isSysList = row?.sysData || sysDatas.value;
  if (isSysList.includes('Y')) {
    proxy?.$modal.alertWarning('所选数据含有系统内置岗位，请重新选择！');
    return;
  }
  const postIds = row?.postId || ids.value;
  await proxy?.$modal.confirm('是否确认删除岗位编号为[' + postIds + ']的数据项？');
  await api.delPost(postIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};
/** 岗位状态修改  */
const handleStatusChange = async (row: PostVO) => {
  let text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要[' + text + ']【' + row.postName + '】岗位吗？');
    await api.changePostStatus(row.postId, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch (err) {
    row.status = row.status === '0' ? '1' : '0';
  }
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/post/export',
    {
      ...queryParams
    },
    `post_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
