<!-- 通知公告 -->
<script lang="ts" setup>
// import { Delete } from '@element-plus/icons-vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { Ref } from 'vue'
// import tableHeader from './tableHeader.vue'
import addNotice from './noteAdd.vue'
import noticeDetail from './noticeDetail.vue'
import type { noticeType } from './notice-interface'
import { printJSON } from '@/utils/printUtils'
import { getNoticeeApi, removeNoticeApi } from '@/api/system/notice'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportExcel } from '@/utils/exportXlsx'
// import { exportFile } from '@/utils/exportUtils'
const noticeTime = ref()
const { proxy } = getCurrentInstance() as any
const searchQuery = reactive({
  noticeNo: '', // 编号
  noticePublisher: '', // 发布人
  // noticeTime: '', // 发布时间
  noticeStartTime: '',
  noticeEndTime: '',
  noticeTitle: '', // 标题
  limit: 20,
  offset: 1,
}) // 查询参数
watch(() => noticeTime.value, (newVal) => {
  if (newVal) {
    searchQuery.noticeStartTime = `${newVal[0]} 00:00:00`
    searchQuery.noticeEndTime = `${newVal[1]} 23:59:59`
  }
  else {
    searchQuery.noticeStartTime = ''
    searchQuery.noticeEndTime = ''
  }
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns: Ref<TableColumn[]> = ref([])
columns.value = [
  {
    text: '编号',
    value: 'noticeNo',
    align: 'center',
    width: '180',
  },
  {
    text: '标题',
    value: 'noticeTitle',
    align: 'center',
  },
  {
    text: '发布人',
    value: 'noticePublisher',
    align: 'center',
    width: '150',
  },
  {
    text: '内容描述',
    value: 'noticeSketch',
    align: 'center',
  },
  {
    text: '发布时间',
    value: 'noticeTime',
    align: 'center',
    width: '200',
  },
] // 表格
const list = ref([]) // 表格数据
// 获取通知公告列表
const getNoticeList = () => {
  getNoticeeApi(searchQuery).then((res) => {
    total.value = res.data.total
    list.value = res.data.rows
  })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getNoticeList()
}

// 重置查询条件
const resetSearchQuery = () => {
  searchQuery.noticeNo = ''
  searchQuery.noticePublisher = ''
  noticeTime.value = ''
  searchQuery.noticeTitle = ''
  searchQuery.noticeStartTime = ''
  searchQuery.noticeEndTime = ''
}
// 查询
const search = () => {
  getNoticeList()
}
// 重置
const reset = () => {
  resetSearchQuery()
  search()
}
const addDialog = ref() // 添加弹窗组件
// 新建
const add = () => {
  addDialog.value.initDialog({
    title: '新建',
  })
}
// 删除
const remove = (row: noticeType) => {
  ElMessageBox.confirm(
    `确认删除${row.noticeTitle}吗`,
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    removeNoticeApi({ id: row.id }).then((res) => {
      ElMessage.success('操作成功')
      getNoticeList()
    })
  })
}
// 编辑
const update = (row: noticeType) => {
  addDialog.value.initDialog({
    title: '编辑',
    ...row,
  })
}
const detailDialog = ref() // 详情组件弹窗
// 详情
const detail = (row: noticeType) => {
  detailDialog.value.initDialog(row)
}
// 表格被选中的行
const selectList = ref<noticeType[]>([])
// 表格多选
const multiSelect = (row: noticeType[]) => {
  selectList.value = row
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  getNoticeeApi({ ...searchQuery, limit: 9999999, offset: 1 }).then((res) => {
    if (res.code === 200) {
      exportExcel({
        json: res.data.rows.map((item: noticeType, index: number) => ({ index: index + 1, noticeNo: item.noticeNo, noticeTitle: item.noticeTitle, noticePublisher: item.noticePublisher, noticeSketch: item.noticeSketch, noticeTime: item.noticeTime })),
        name: '通知公告',
        titleArr: ['序号', '编号', '标题', '发布人', '内容描述', '发布时间'],
        sheetName: 'sheet1',
      })
    }
    loading.close()
  }).catch((_) => {
    loading.close()
  })
}
// 打印
function printList() {
  const selectIds = selectList.value.map((item: noticeType) => item.id)
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (selectIds.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '通知公告')
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: noticeType) => selectIds.includes(item.id))
    printJSON(printList, properties, '通知公告')
  }
  else {
    ElMessage('无可打印内容')
  }
}
onMounted(() => {
  getNoticeList()
})
</script>

<template>
  <!-- 布局 -->
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model.trim="searchQuery.noticeNo" placeholder="请输入编号" clearable class="w-50 m-2" />
      </search-item>
      <search-item>
        <el-input v-model.trim="searchQuery.noticeTitle" placeholder="请输入标题" clearable class="w-50 m-2" />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="searchQuery.noticePublisher" placeholder="请输入发布人" clearable
          class="w-50 m-2"
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="noticeTime"
          type="datetimerange"
          format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="发布开始时间"
          end-placeholder="发布结束时间"
          clearable
        />
        <!-- <el-date-picker
          v-model="searchQuery.noticeTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="发布时间"
        /> -->
      </search-item>
      <!-- <template #btns>
        <el-button class="filter-item" type="info" :icon="Delete" :style="{ marginTop: '-10px' }" @click="reset">
          重置
        </el-button>
      </template> -->
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/sys/notice/list/add')" icon="icon-add" title="新建" @click="add" />
        <icon-button v-if="proxy.hasPerm('/sys/notice/list/export')" icon="icon-export" title="导出" @click="exportExcelBtn" />
        <icon-button v-if="proxy.hasPerm('/sys/notice/list/print')" icon="icon-print" title="打印" @click="printList" />
      </template>
      <!-- 表格区域 -->
      <normal-table
        :data="list" :total="total" :columns="columns"
        :query="searchQuery" :list-loading="loadingTable" :is-showmulti-select="true"
        :is-multi="true" @change="changePage" @multiSelect="multiSelect"
      >
        <template #preColumns>
          <el-table-column label="#" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" width="140" fixed="right">
            <template #default="{ row }">
              <el-button v-if="proxy.hasPerm('/sys/notice/list/detail')" type="primary" link size="small" @click="detail(row)">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm('/sys/notice/list/update')" type="primary" link size="small" @click="update(row)">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm('/sys/notice/list/delete')" type="danger" link size="small" @click="remove(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <add-notice ref="addDialog" @reset-data="getNoticeList" />
    <notice-detail ref="detailDialog" />
  </app-container>
</template>

<style lang="scss" scoped>
.normal-input {
  width: 180px !important;
}
</style>
