<!-- 体系文件列表 -->
<script name="HistoryDocList" lang="ts" setup>
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { IDictType, IFileInfo, IListQuery } from './sysDoc-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { delFileSystem, getFileSystemList } from '@/api/resource/fileSystem'

const { proxy } = getCurrentInstance() as any
const router = useRouter()

const fileTypeDict = ref<Array<IDictType>>([])

// 查询条件
const searchQuery = ref<IListQuery>({
  fileNo: '', // 文件编号
  fileName: '', // 文件名
  fileDistributeNo: '', // 文件发放号
  fileType: '', // 文件类别
  history: '0', // 体系文件
  offset: 1,
  limit: 20,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '文件编号', value: 'fileNo', align: 'center', width: '180' },
  { text: '文件发放号', value: 'fileDistributeNo', align: 'center' },
  { text: '文件名称', value: 'fileName', align: 'center' },
  { text: '版本号', value: 'versionNo', align: 'center', width: '140' },
  { text: '类别', value: 'fileTypeName', align: 'center', width: '140' },
  { text: '实施时间', value: 'effectiveDateStr', align: 'center', width: '140' },
])
const sysFileList = ref<Array<IFileInfo>>([]) // 表格数据

// 逻辑
// 跳转到新建的页面
const addSysFile = () => {
  router.push({
    query: {
      type: 'create',
    },
    path: '/system/sysDoc/detail',
  })
}

// 详情
const detail = (row: IFileInfo) => {
  sessionStorage.setItem('sysFileInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: '/system/sysDoc/detail',
  })
}

// 编辑
const updateById = (row: IFileInfo) => {
  sessionStorage.setItem('sysFileInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'update',
      id: row.id,
    },
    path: '/system/sysDoc/detail',
  })
}

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getFileSystemList(searchQuery.value).then((response) => {
    if (response.code === 200) {
      sysFileList.value = response.data.rows.map((item: { effectiveDate: string }) => {
        return {
          ...item,
          effectiveDateStr: dayjs(item.effectiveDate).format('YYYY-MM-DD') !== 'Invalid Date' ? dayjs(item.effectiveDate).format('YYYY-MM-DD') : '',
        }
      })
      total.value = parseInt(response.data.total)
    }
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

const searchList = () => {
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData()
}

// 重置
const reset = () => {
  searchQuery.value = {
    fileNo: '', // 文件编号
    fileName: '', // 文件名
    fileDistributeNo: '', // 文件发放号
    fileType: '', // 文件类别
    history: '0', // 体系文件
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 删除
const deleteById = (row: IFileInfo) => {
  ElMessageBox.confirm(`是否删除文件 ${row.fileName}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delFileSystem({ id: row.id }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(`文件 ${row.fileName} 删除成功`)
        searchList()
      }
      else {
        ElMessage.error(`文件 ${row.fileName} 删除失败: ${res.message}`)
      }
    })
  })
}

// 获取文件类别字典值
const getFileTypeDict = () => {
  getDictByCode('bizFileType').then((res) => {
    if (res.code === 200) {
      fileTypeDict.value = res.data
      sessionStorage.setItem('bizFileType', JSON.stringify(fileTypeDict.value))
    }
  })
}
const getDict = async () => {
  getFileTypeDict()
}

onMounted(async () => {
  await getDict()
  searchList()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.fileNo" placeholder="文件编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.fileDistributeNo" placeholder="文件发放编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.fileName" placeholder="文件名称" clearable />
      </search-item>
      <search-item>
        <el-select v-model="searchQuery.fileType" placeholder="文件类别" clearable>
          <el-option v-for="item in fileTypeDict" :key="item.id" :value="item.value" :label="item.name" />
        </el-select>
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container title="体系文件列表">
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm(`/resource/system/sysDoc/add`)" icon="icon-add" title="新建" @click="addSysFile" />
      </template>

      <!-- 表格区域 -->
      <normal-table
        :data="sysFileList" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
        :list-loading="loadingTable"
        @change="changePage"
      >
        <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 fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="detail(row)">
                查看
              </el-button>
              <el-button v-if="proxy.hasPerm(`/resource/system/sysDoc/edit`)" size="small" type="primary" link @click="updateById(row)">
                编辑
              </el-button>
              <el-button v-if="proxy.hasPerm(`/resource/system/sysDoc/del`)" size="small" type="danger" link @click="deleteById(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
