<!-- 计量文件公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { fileListType, fileResType, fileSearchType } from '@/views/measure/file/file-interface'
import { abolish as abolishFile, batchDeleteList, deleteList, exportFileApi, listPageApi } from '@/api/measure/file'
import { getDictByCode } from '@/api/system/dict'
import { printJSON } from '@/utils/printUtils'
import FilePreviewDialog from '@/components/filePreview/filePreviewDialog.vue'
import { uploadApi } from '@/api/system/notice'
import { exportFile } from '@/utils/exportUtils'
import { getPhotoUrl } from '@/api/system/tool'
import { download } from '@/utils/download'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  authority: {
    type: String,
    required: true,
  },
})
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const tableRef = ref()
// 表格被选中的行
const selectList = ref<fileListType[]>([])
let searchQuery = reactive<fileSearchType>({
  fileNo: '', // 编号
  fileName: '', // 名称
  fileCode: '', // 文件号
  effectiveStatus: '', // 实施状态
  effectiveEndTime: '',
  effectiveStartTime: '',
  publishEndTime: '',
  publishStartTime: '',
  limit: 20,
  offset: 1,
  fileType: '', // 类型
  ids: [] as string[],
  formId: SCHEDULE.FILE_APPROVAL,
}) // 查询参数
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, `measure-file-${props.name}`, searchQuery)
})
// 重新赋值
searchQuery = reactive(renewSearchParams(`measure-file-${props.name}`) || {
  fileNo: '', // 编号
  fileName: '', // 名称
  fileCode: '', // 文件号
  effectiveStatus: '', // 实施状态
  effectiveEndTime: '',
  effectiveStartTime: '',
  publishEndTime: '',
  publishStartTime: '',
  limit: 20,
  offset: 1,
  fileType: '', // 类型
  ids: [] as string[],
  formId: SCHEDULE.FILE_APPROVAL,
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<TableColumn[]>([
  { text: '文件编号', value: 'fileNo', align: 'center', width: '160' },
  { text: '文件号', value: 'fileCode', align: 'center' },
  { text: '文件名称', value: 'fileArr', align: 'center', followLink: true },
  { 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 list = ref([]) // 表格数据
// ------------------------------------------字典---------------------------------------
// 获取类型
const fileTypeList = ref([]) as any // 质量文件-文件类别
const effectiveStatusSelect = ref<fileResType[]>([])

const getDict = async () => {
  const res = await getDictByCode('fileType')
  res.data.forEach((item: fileResType) => {
    if (item.name === '质量手册' || item.name === '程序文件'
      || item.name === '质量记录' || item.name === '操作规程'
      || item.name === '作业指导书') {
      fileTypeList.value.push(item)
    }
  })
  fileTypeList.value.unshift({
    name: '全部',
    value: '0',
    id: 'all',
  })
  if (props.name !== '质量文件') {
    searchQuery.fileType = res.data.filter((item: fileResType) => item.name === props.name)[0].value
  }
  // else {
  //   searchQuery.fileType = '0'
  // }
  // 获取实施状态
  getDictByCode('effectiveStatus').then((res) => {
    if (res.code === 200) {
      effectiveStatusSelect.value = res.data
    }
  })
}

// ---------------------------------------------------------------------------------------------
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  listPageApi({ ...searchQuery, fileType: searchQuery.fileType === '' ? '0' : searchQuery.fileType }).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: { fileName: string; publishTime: string;effectiveTime: string }) => {
        return {
          ...item,
          followLinkArr: [item.fileName],
          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
  })
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: fileListType) => {
  $router.push({
    path: `/file/${props.authority}/detail`,
    query: {
      ...row,
      fileType: searchQuery.fileType || row.fileType,
      title: '详情',
      routerName: props.name,
    },
  })
}
const exportSele = (row: fileListType) => {
  if (row.minioFilePdfName) {
    const loading = ElLoading.service({
      lock: true,
      text: '下载中请稍后',
      background: 'rgba(255, 255, 255, 0.8)',
    })
    getPhotoUrl(row.minioFilePdfName).then((res) => {
      download(res.data, `${row.fileName}_${row.minioFilePdfName}`)
      loading.close()
    }).catch(() => {
      loading.close()
      ElMessage.error('下载失败')
    })
  }
  else {
    ElMessage('无可下载内容')
  }
}

// 废止
const abolish = (row: fileListType) => {
  ElMessageBox.confirm(
    `确认废止${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      abolishFile({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          getList()
        }
      })
    })
}
// 删除
const remove = (row: fileListType) => {
  ElMessageBox.confirm(
    `确认删除${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteList({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
    })
}

// 批量删除
const batchRemove = (row: fileListType) => {
  if (!selectList.value.length) {
    ElMessage.warning('请选中')
    return false
  }
  ElMessageBox.confirm(
    '确认删除所选数据吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      const selectIds = selectList.value.map((item: fileListType) => item.id)

      batchDeleteList({ ids: selectIds }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          tableRef.value.clearMulti()
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  searchQuery.fileNo = '' // 编号
  searchQuery.fileName = '' // 名称
  searchQuery.fileCode = '' // 文件号
  searchQuery.effectiveStatus = '' // 实施状态
  searchQuery.effectiveEndTime = ''
  searchQuery.effectiveStartTime = ''
  searchQuery.publishEndTime = ''
  searchQuery.publishStartTime = ''
  searchQuery.fileType = '' // 类型
  searchQuery.limit = 20
  searchQuery.offset = 1
  getList()
}

// 新增
const add = () => {
  $router.push({
    path: `/file/${props.authority}/add`,
    query: {
      fileType: searchQuery.fileType,
      title: '新建',
      routerName: props.name,
    },
  })
}

// 表格多选
const multiSelect = (val: fileListType[]) => {
  selectList.value = val
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (selectList.value.length) {
    selectList.value.forEach((item) => {
      searchQuery.ids?.push(item.id as string)
    })
  }
  exportFileApi({ ...searchQuery, limit: undefined, offset: undefined }).then((res) => {
    exportFile(res.data, props.name)
    loading.close()
    searchQuery.ids = []
  }).catch((_) => {
    loading.close()
  })
}

// 打印
function printList() {
  const selectIds = selectList.value.map((item: fileListType) => 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, props.name)
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: fileListType) => selectIds.includes(item.id))
    printJSON(printList, properties, props.name)
  }
  else {
    ElMessage('无可打印内容')
  }
}
const refFilePreviewDlg = ref()
// 点击文件名称
const handleClickFollowLink = (row: any) => {
  console.log('点击文件名称', row.minioFilePdfName)
  if (row.minioFilePdfName.lastIndexOf('.pdf') > 0) {
    refFilePreviewDlg.value.initDialog(row.minioFilePdfName)
  }
}

onMounted(() => {
  console.log('909090909-0', proxy.hasPerm(`/file/${props.authority}/abolish`))

  getDict().then(() => { // 获取字典
    getList() // 获取表格列表
  })
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.fileName" placeholder="文件名称" clearable />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.fileCode" placeholder="文件号" clearable />
        </search-item>
        <search-item v-if="props.name === '质量文件'">
          <el-select v-model="searchQuery.fileType" placeholder="文件类别" clearable class="short-input">
            <el-option
              v-for="item in fileTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.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-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <icon-button v-if="proxy.hasPerm(`/file/${authority}/add`)" icon="icon-add" title="新建" @click="add" />
          <!-- <icon-button v-if="proxy.hasPerm(`/file/${authority}/import`)" icon="icon-import" title="批量导入" @click="batchImport" /> -->
          <!-- <icon-button v-if="proxy.hasPerm(`/file/${authority}/mould`)" icon="icon-template" title="模板下载" @click="templateDownload" /> -->
          <icon-button icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button icon="icon-print" title="打印" @click="printList" />
          <icon-button v-if="proxy.hasPerm(`/file/${authority}/delete`)" icon="icon-delete" title="批量删除" @click="batchRemove" />
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          ref="tableRef"
          :data="list" :total="total" :columns="columns"
          :is-showmulti-select="true"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          :is-multi="true" @change="changePage" @multi-select="multiSelect"
          @handleClickFollowLink="handleClickFollowLink"
        >
          <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="150" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button v-if="row.effectiveStatus === '1' && proxy.hasPerm(`/file/${authority}/abolish`)" size="small" type="info" link :disabled="row.effectiveStatus === '3'" @click="abolish(row)">
                  废止
                </el-button>
                <el-button v-if="proxy.hasPerm('/sys/tool/certificate/download') && (props.name === '规章制度' || props.name === '计量法律法规' || props.name === '计量规程规范')" size="small" type="primary" link @click="exportSele(row)">
                  下载
                </el-button>
                <el-button v-if="proxy.hasPerm(`/file/${authority}/delete`)" size="small" type="danger" link @click="remove(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
    <file-preview-dialog ref="refFilePreviewDlg" />
  </div>
</template>

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

.normal-date {
  width: 154px !important;
}

.normal-select {
  width: 154px !important;
}

:deep(.el-table__header) {
  background-color: #bbb;
}
</style>
