<!-- 选择所依据的技术文件--（质量文件、计量规程规范） -->
<script lang="ts" setup name="SelectTechFilesDialog">
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { listPageApi as SelectTechFiles } from '@/api/measure/file'
import { SCHEDULE } from '@/utils/scheduleDict'
import { getReportList } from '@/api/business/lab/report'
import { getDictByCode } from '@/api/system/dict'
import type { fileResType } from '@/views/measure/file/file-interface'

const emits = defineEmits(['confirm'])
const dialogFormVisible = ref(false) // 控制弹窗显隐
// 查询参数
const listQuery = ref({
  fileNo: '', // 编号
  fileName: '', // 名称
  fileCode: '', // 文件号
  effectiveStatus: '', // 实施状态
  effectiveEndTime: '',
  effectiveStartTime: '',
  publishEndTime: '',
  publishStartTime: '',
  limit: 20,
  offset: 1,
  fileType: '', // 类型
  ids: [] as string[],
  formId: SCHEDULE.FILE_APPROVAL,
})
const loadingTable = ref(false) // loading
const list = ref([]) // 表格参数
const checkoutList = ref([]) // 多选表格
const total = ref(0)
const fileClass = ref('0') // 文件分类
const disabledFileType = ref(false) // 文件分类
const columns = ref<TableColumn[]>([
  { text: '文件编号', value: 'fileNo', align: 'center', width: '160' },
  { text: '文件号', value: 'fileCode', align: 'center' },
  { text: '文件名称', value: 'fileName', align: 'center' },
  { text: '文件类别', value: 'fileTypeName', align: 'center', width: '120' },
  { text: '发布时间', value: 'publishTime', align: 'center', width: '120' },
  { text: '实施时间', value: 'effectiveTime', align: 'center', width: '120' },
  { text: '实施状态', value: 'effectiveStatusName', align: 'center', width: '100' },
])

// ------------------------------------------字典---------------------------------------
// 获取类型
const qualityFileTypeList = ref([]) as any // 质量文件-文件类别
const effectiveStatusSelect = ref<fileResType[]>([])

const getDict = async () => {
  const res = await getDictByCode('fileType')
  res.data.forEach((item: { name: string }) => {
    if (item.name === '质量手册' || item.name === '程序文件'
      || item.name === '质量记录' || item.name === '操作规程'
      || item.name === '作业指导书') {
      qualityFileTypeList.value.push(item)
    }
  })
  qualityFileTypeList.value.unshift({
    name: '全部',
    value: '0',
    id: 'all',
  })
  // if (props.name !== '质量文件') {
  //   listQuery.fileType = res.data.filter((item: fileResType) => item.name === props.name)[0].value
  // }

  // 获取实施状态
  getDictByCode('effectiveStatus').then((res) => {
    if (res.code === 200) {
      effectiveStatusSelect.value = res.data
    }
  })
}
getDict()

// 查询列表
const fetchData = () => {
  loadingTable.value = true
  SelectTechFiles({ ...listQuery.value, fileType: fileClass.value === '' ? '0' : fileClass.value }).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: { fileName: string; publishTime: string;effectiveTime: string }) => {
        return {
          ...item,
          publishTime: dayjs(item.publishTime).format('YYYY-MM-DD'),
          effectiveTime: dayjs(item.effectiveTime).format('YYYY-MM-DD'),
        }
      })
      total.value = res.data.total
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
fetchData()

// 搜索
const search = () => {
  fetchData()
}
// 重置
const clearList = () => {
  listQuery.value = {
    fileNo: '', // 编号
    fileName: '', // 名称
    fileCode: '', // 文件号
    effectiveStatus: '', // 实施状态
    effectiveEndTime: '',
    effectiveStartTime: '',
    publishEndTime: '',
    publishStartTime: '',
    limit: 20,
    offset: 1,
    fileType: '', // 类型
    ids: [] as string[],
    formId: SCHEDULE.FILE_APPROVAL,
  }
  fetchData()
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData()
}
// 点击保存
const submitForm = () => {
  if (!checkoutList.value.length) {
    ElMessage.warning('请选择依据的技术文件')
  }
  else {
    emits('confirm', checkoutList.value)
    dialogFormVisible.value = false
  }
}

// 取消
const resetForm = () => {
  dialogFormVisible.value = false
  clearList()
}

// 多选选中
const handleSelectionChange = (val: any) => {
  checkoutList.value = val
}

// 文件分类变化
const changeFileClass = (val: string) => {
  listQuery.value.fileType = val
  // fetchData()
}

/**
 * 初始化弹窗
 * @param fileType 文件类型
 * @param disabledFileTypeParam 是否禁止修改文件类型
 */
const initDialog = (fileType = '0', disabledFileTypeParam = false) => {
  dialogFormVisible.value = true
  fileClass.value = fileType || ''
  disabledFileType.value = disabledFileTypeParam
  fetchData()
}
defineExpose({ initDialog })
</script>

<template>
  <el-dialog v-model="dialogFormVisible" title="选择所依据的技术文件" width="60%">
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="clearList">
      <search-item>
        <el-input v-model="listQuery.fileName" placeholder="文件名称" clearable />
      </search-item>
      <search-item>
        <el-input v-model="listQuery.fileCode" placeholder="文件号" clearable />
      </search-item>
      <search-item>
        <el-select v-model="fileClass" :disabled="disabledFileType" placeholder="文件分类" class="short-input" @change="changeFileClass">
          <el-option
            v-for="item in [{ value: '0', name: '质量文件' }, { value: '10', name: '计量规程规范' }]"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item v-if="fileClass === '0'">
        <el-select v-model="listQuery.fileType" placeholder="文件类别" clearable class="short-input">
          <el-option
            v-for="item in qualityFileTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-select v-model="listQuery.effectiveStatus" placeholder="实施状态" clearable class="short-input">
          <el-option
            v-for="item in effectiveStatusSelect"
            :key="item.id"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
    </search-area>
    <!-- 查询结果Table显示 -->
    <div style="padding: 12px;">
      <normal-table
        :data="list"
        :total="total"
        :columns="columns"
        :query="listQuery"
        is-showmulti-select
        :list-loading="loadingTable"
        :page-sizes="[20]"
        :is-multi="true"
        @change="changePage"
        @multi-select="handleSelectionChange"
      >
        <!-- 序号 -->
        <template #preColumns>
          <el-table-column label="#" width="55" align="center" fixed>
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="resetForm">
          取消
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-radio__label) {
  display: none;
}
</style>
