<template>
  <div class="flex flex-col h-full">
    <div class="page-action">
      <t-button v-if="perm.BUTTON_Add" theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template
        >新增通知公告
      </t-button>
      <t-button
        v-if="perm.BUTTON_Cancel"
        variant="outline"
        :disabled="!selectedRowKeys.length"
        @click="handleDestroy"
      >
        <template #icon><svg-icon name="delete" color="#262626" /></template>
        作废</t-button
      >
    </div>
    <SearchForm :fields="fields" :params="params"></SearchForm>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        v-loading="tableLoading"
        :selected-row-keys="selectedRowKeys"
        @select-change="selectChange"
      >
        <template #type="{ col, row }">
          {{ noticeTypeFilter(row[col.colKey]) }}
        </template>
        <template #name="{ col, row }">
          <t-link hover="color" @click="open(row)">
            <span>{{ row.title }}</span>
            <span>
              【 {{ row.createName + '：'
              }}{{
                row.status === 'PUBLISH'
                  ? timestampFilter(row.publishTime)
                  : '暂未发布'
              }}】
            </span>
          </t-link>
        </template>
        <template #status="{ col, row }">
          <status-tag :value="row[col.colKey]" type="notice"></status-tag>
        </template>
        <template #operate="{ col, row }">
          <div class="table-operations">
            <template v-if="perm.LINK_Select">
              <t-link
                :disabled="row.status !== 'PUBLISH'"
                theme="primary"
                hover="color"
                @click="handleFeedbackView(row)"
              >
                回执查询
              </t-link>
            </template>
            <template v-if="perm.LINK_Update">
              <t-link
                :disabled="row.status === 'PUBLISH'"
                theme="primary"
                hover="color"
                @click="handleEdit(row)"
              >
                修改
              </t-link>
            </template>
            <template v-if="perm.LINK_Cancel">
              <t-link
                v-if="row.status === 'PUBLISH'"
                theme="primary"
                hover="color"
                @click="handleCancelPublish(row)"
              >
                撤销发布
              </t-link>
            </template>
            <template v-if="perm.LINK_Publish">
              <t-link
                v-if="row.status !== 'PUBLISH'"
                theme="primary"
                hover="color"
                @click="handlePublish(row)"
              >
                发布
              </t-link>
            </template>
          </div>
        </template>
      </t-table>
    </div>

    <edit-notice-dialog
      v-if="perm.LINK_Update || perm.BUTTON_Add"
      v-model:visible="showEditNoticeDialog"
      :curRow="curRow"
      @success="fetchData"
    ></edit-notice-dialog>
    <!-- NoticeMessageDialog -->
    <notice-message-dialog
      v-if="perm.LINK_Select"
      v-model:visible="showNoticeMessageDialog"
      :curRow="curRow"
    ></notice-message-dialog>
    <t-drawer
      v-model:visible="visible"
      header="通知公告"
      size="80%"
      :close-btn="true"
    >
      <h2 class="text-center notice-title">{{ curRow?.title }}</h2>
      <div class="text-center notice-subtitle"
        >创建时间：{{ timestampFilter(curRow?.createTime) }}</div
      >
      <div class="notice-content" v-html="curRow?.content"></div>

      <template #footer>
        <t-button theme="primary" @click="visible = false">返回</t-button>
      </template>
    </t-drawer>
  </div>
</template>

<script setup name="NoticeManage">
import { ref, reactive, computed } from 'vue';
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import { omit } from 'lodash';
import useFetchTable from '@/hooks/useFetchTable';
import EditNoticeDialog from './edit-notice-dialog.vue';
import NoticeMessageDialog from './notice-message-dialog.vue';
import {
  noticeQueryApi,
  noticeDestroyApi,
  noticePublishApi,
  noticeCancelPublishApi,
} from '@/api/system';
import { dateFormat, dictToOptionList } from '@/utils/tool';
import { NOTICE_TYPE, PUBLISH_STATUS } from '@/config/constants';
import { noticeTypeFilter, timestampFilter } from '@/utils/filter';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();
const visible = ref(false);
const showEditNoticeDialog = ref(false);
const showNoticeMessageDialog = ref(false);
const curRow = ref(null);
const selectedRowKeys = ref([]);

const fields = ref([
  {
    prop: 'status',
    label: '发布状态',
    type: 'select',
    labelWidth: 70,
    colSpan: 6,
    options: dictToOptionList(PUBLISH_STATUS),
  },
  {
    prop: 'type',
    label: '类型',
    type: 'select',
    labelWidth: 60,
    colSpan: 6,
    options: dictToOptionList(NOTICE_TYPE),
  },
  {
    prop: 'publishTime',
    label: '发布时间',
    type: 'daterange',
    labelWidth: 100,
    colSpan: 12,
    attrs: {
      clearable: true,
      valueType: 'time-stamp',
    },
  },
  {
    prop: 'query',
    label: '消息名称',
    labelWidth: 70,
    colSpan: 6,
    attrs: {
      placeholder: '消息名称模糊查询',
      clearable: true,
    },
  },
  {
    type: 'buttons',
    colSpan: 2,
    children: [
      {
        type: 'button',
        text: '搜索',
        onClick: () => {
          search();
        },
      },
    ],
  },
]);
const params = reactive({
  status: '',
  type: '',
  query: '',
  publishTime: [],
});

const computedParams = computed(() => {
  let data = omit(params, ['publishTime']);
  data.startTime = params.publishTime[0];
  data.endTime = params.publishTime[1];
  return data;
});

const columns = [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'type', title: '类型', cell: 'type', width: 120 },
  { colKey: 'title', title: '消息名称', cell: 'name' },
  { colKey: 'status', title: '发布状态', cell: 'status', width: 120 },
  { colKey: 'readCount', title: '回执进度', cell: 'readCount', width: 120 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 220,
  },
];
const {
  loading: tableLoading,
  pagination,
  tableData,
  fetchData,
  search,
  onChange,
} = useFetchTable(noticeQueryApi, {
  fetchDataHandle: () => {
    selectedRowKeys.value = [];
  },
  params: computedParams,
});

const selectChange = (value) => {
  selectedRowKeys.value = value;
};
const open = (notice) => {
  curRow.value = notice;
  visible.value = true;
};
const handleAdd = () => {
  curRow.value = null;
  showEditNoticeDialog.value = true;
};
const handleDestroy = () => {
  if (!selectedRowKeys.value.length) {
    MessagePlugin.error('请选择要作废的记录');
    return;
  }

  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要作废当前选择的所有记录吗`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await noticeDestroyApi(selectedRowKeys.value).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const handleCancelPublish = (row) => {
  const confirmDia = DialogPlugin({
    header: '撤销发布提示',
    body: `您确定要撤销发布该通知公告吗？一旦撤销发布，该通知公告信息的回执将会被清空，重新发布后该通知公告将作为新消息发布。`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await noticeCancelPublishApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
const handleFeedbackView = (row) => {
  curRow.value = row;
  showNoticeMessageDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showEditNoticeDialog.value = true;
};
const handlePublish = (row) => {
  const confirmDia = DialogPlugin({
    header: '发布提示',
    body: `您确定要发布该通知公告吗？`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await noticePublishApi(row.id).catch(() => {});
      if (!res) return;
      MessagePlugin.success('操作成功');
      fetchData();
    },
  });
};
</script>
<style lang="less" scoped>
.notice {
  .notice-title {
    color: #333;
    font-size: 20px;
  }
  .notice-subtitle {
    font-size: 13px;
    margin-top: 6px;
  }
  //.notice-content {
  //  font-size: 14px;
  //  margin-top: 10px;
  //  text-indent: 2em;
  //}
}
</style>
