<!-- 选择更改文件弹窗 -->
<script name="FileSelectDialog" lang="ts" setup>
import { ElMessage } from 'element-plus'
import type { IFileFilterQuery } from './change-interface'
import type { IFileInfo as ISysDocFileInfo } from '@/views/resource/system/sysDoc/sysDoc-interface'
import type { IFileInfo as IMethodFileInfo } from '@/views/resource/technology/method/method-interface'
import type { IDictType } from '@/commonInterface/resource-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getFileSystemList } from '@/api/resource/fileSystem'
import { getFileMethodList } from '@/api/resource/fileTechnology'

const emit = defineEmits(['recordsSelected'])

const fileCategoryDict = ref<IDictType[]>([
  { name: '体系文件', id: '1', value: '1' },
  { name: '现行测试标准检定方法', id: '2', value: '2' },
])
const fileTypeDict = ref<IDictType[]>()
const groupCodeDict = ref<IDictType[]>()

const searchQuery = ref<IFileFilterQuery>({
  category: '1',
  fileNo: '', // 文件编号
  fileName: '', // 文件名
  fileDistributeNo: '', // 文件发放号
  fileType: '', // 文件类别（字典值）
  history: '0', // 历史文件(1历史文件0体系文件)
  professionalGroup: '', // 专业组（字典值）
  offset: 1,
  limit: 10,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading
const fileList = ref<Array<ISysDocFileInfo | IMethodFileInfo>>([]) // 表格数据

const fileColumns = ref<Array<TableColumn>>([
  { text: '文件编号', value: 'fileNo', align: 'center', width: '240' },
  { text: '文件发放号', value: 'fileDistributeNo', align: 'center', width: '240' },
  { text: '文件名称', value: 'fileName', align: 'center' },
  { text: '版本号', value: 'versionNo', align: 'center', width: '180' },
]) // 表头

const fileSelected = ref<ISysDocFileInfo[] | IMethodFileInfo[]>([])

const showDialog = ref(false)

// 逻辑
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  if (searchQuery.value.category === '1') {
    getFileSystemList(searchQuery.value).then((res) => {
      if (res.code === 200) {
        fileList.value = res.data.rows
        total.value = parseInt(res.data.total)
      }
    })
  }
  else if (searchQuery.value.category === '2') {
    getFileMethodList(searchQuery.value).then((res) => {
      if (res.code === 200) {
        fileList.value = res.data.rows
        total.value = parseInt(res.data.total)
      }
    })
  }

  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(true)
}

// 重置
const reset = () => {
  searchQuery.value = {
    category: '',
    fileNo: '', // 文件编号
    fileName: '', // 文件名
    fileDistributeNo: '', // 文件发放号
    fileType: '', // 文件类别（字典值）
    history: '0', // 历史文件(1历史文件0体系文件)
    professionalGroup: '', // 专业组（字典值）
    offset: 1,
    limit: 10,
  }
  fetchData(true)
}

const fileMultiSelect = (e: any) => {
  fileSelected.value = e
}

const showRecordDialog = (show: boolean) => {
  showDialog.value = show

  fileTypeDict.value = JSON.parse(sessionStorage.getItem('bizFileType')!)
  groupCodeDict.value = JSON.parse(sessionStorage.getItem('bizGroupCode')!)

  if (show === false) {
    searchQuery.value = {
      category: '1',
      fileNo: '', // 文件编号
      fileName: '', // 文件名
      fileDistributeNo: '', // 文件发放号
      fileType: '', // 文件类别（字典值）
      history: '0', // 历史文件(1历史文件0体系文件)
      professionalGroup: '', // 专业组（字典值）
      offset: 1,
      limit: 10,
    }
  }
  else {
    searchList()
  }
}

const fileSelectConfirmed = () => {
  if (fileSelected.value.length === 0) {
    ElMessage.warning('请至少选择一行')
  }
  else {
    emit('recordsSelected', fileSelected.value, searchQuery.value.category)
    showRecordDialog(false)
  }
}

defineExpose({
  showRecordDialog,
})
</script>

<template>
  <el-dialog v-model="showDialog" title="选择文件" :append-to-body="true" :close-on-click-modal="false" width="75%">
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="searchList" @clear="reset">
      <search-item>
        <el-select v-model="searchQuery.category" placeholder="文件类型" clearable @change="searchList">
          <el-option v-for="dict in fileCategoryDict" :key="dict.id" :label="dict.name" :value="dict.value" />
        </el-select>
      </search-item>

      <search-item>
        <el-input v-model="searchQuery.fileNo" placeholder="文件编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.fileName" placeholder="文件名称" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.fileDistributeNo" placeholder="文件发放编号" clearable />
      </search-item>

      <el-select v-if="searchQuery.category === '1'" v-model="searchQuery.fileType" placeholder="体系文件类别" clearable>
        <el-option v-for="dict in fileTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
      </el-select>
      <el-select v-if="searchQuery.category === '2'" v-model="searchQuery.professionalGroup" placeholder="专业组" clearable>
        <el-option v-for="dict in groupCodeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
      </el-select>
    </search-area>

    <table-container title="文件列表">
      <normal-table
        :data="fileList" :total="total" :columns="fileColumns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
        :list-loading="loadingTable"
        :is-showmulti-select="true"
        @change="changePage"
        @multi-select="fileMultiSelect"
      >
        <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>
      </normal-table>
    </table-container>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showRecordDialog(false)">取消</el-button>
        <el-button type="primary" @click="fileSelectConfirmed">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
