<!-- 计量文件公共模板 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { fileListType, fileResType, fileSearchType } from '@/views/measure/file/file-interface'
import { deleteApi, exportFileApi, listPageApi, updateApi } from '@/api/measure/file'
import { getDictByCode } from '@/api/system/dict'
import { printJSON } from '@/utils/printUtils'
// import { exportExcel } from '@/utils/exportXlsx'
import { uploadApi } from '@/api/system/notice'
import { exportFile } from '@/utils/exportUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  authority: {
    type: String,
    required: true,
  },
})
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const publishTime = ref()
const effectiveTime = ref()
const searchQuery = reactive<fileSearchType>({
  fileNo: '', // 编号
  fileName: '', // 名称
  // publishTime: '', // 发布时间
  fileCode: '', // 文件号
  // effectiveTime: '', // 实施时间
  effectiveStatus: '', // 实施状态
  effectiveEndTime: '',
  effectiveStartTime: '',
  publishEndTime: '',
  publishStartTime: '',
  limit: 20,
  offset: 1,
  fileType: '', // 类型
  ids: [] as string[],
  formId: SCHEDULE.FILE_APPROVAL,
}) // 查询参数
watch(() => publishTime.value, (newVal) => {
  if (newVal) {
    searchQuery.publishStartTime = newVal[0]
    searchQuery.publishEndTime = newVal[1]
  }
  else {
    searchQuery.publishStartTime = ''
    searchQuery.publishEndTime = ''
  }
})
watch(() => effectiveTime.value, (newVal) => {
  if (newVal) {
    searchQuery.effectiveStartTime = newVal[0]
    searchQuery.effectiveEndTime = newVal[1]
  }
  else {
    searchQuery.effectiveStartTime = ''
    searchQuery.effectiveEndTime = ''
  }
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref([
  { text: '名称', value: 'fileName', align: 'center', width: '130' },
  { text: '编号', value: 'fileNo', align: 'center' },
  { text: '文件号', value: 'fileCode', align: 'center' },
  { text: '发布时间', value: 'publishTime', align: 'center', width: '180' },
  { text: '实施时间', value: 'effectiveTime', align: 'center', width: '180' },
  { text: '实施状态', value: 'effectiveStatusName', align: 'center', width: '100' },
]) // 表格

const list = ref([]) // 表格数据
// 获取类型
const fileTypeList = ref<fileResType[]>([])
const getType = async () => {
  const res = await getDictByCode('fileType')
  fileTypeList.value = res.data
  searchQuery.fileType = res.data.filter((item: fileResType) => item.name === props.name)[0].value
}
const effectiveStatusSelect = ref<fileResType[]>([])
// 获取实施状态
const getStatus = () => {
  getDictByCode('effectiveStatus').then((res) => {
    if (res.code === 200) {
      effectiveStatusSelect.value = [...res.data, { name: '全部', value: '', id: 'quanbu' }]
    }
  })
}
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  listPageApi(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows
      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({
    name: 'measureFileDetail',
    params: {
      type: 'detail',
    },
    query: {
      ...row,
      fileType: searchQuery.fileType,
      title: '详情',
      fileTypeName: props.name,
    },
  })
}
// 下载(单个)
const exportSelf = (row: fileListType) => {

}

// 废止
const abolish = (row: fileListType) => {
  ElMessageBox.confirm(
    `确认废止${row.fileName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      updateApi({ 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(() => {
      deleteApi({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  publishTime.value = ''
  searchQuery.publishStartTime = ''
  searchQuery.publishEndTime = ''
  effectiveTime.value = ''
  searchQuery.effectiveStartTime = ''
  searchQuery.effectiveEndTime = ''
  searchQuery.fileNo = ''
  searchQuery.fileName = ''
  searchQuery.fileCode = ''
  searchQuery.effectiveStatus = ''
  getList()
}
// 模板下载
const templateDownload = () => {

}
// 新增
const add = () => {
  $router.push({
    name: 'measureFileDetail',
    params: {
      type: 'add',
    },
    query: {
      fileType: searchQuery.fileType,
      title: '新建',
      fileTypeName: props.name,
    },
  })
}
// 表格被选中的行
const selectList = ref<fileListType[]>([])
// 表格多选
const multiSelect = (row: fileListType[]) => {
  selectList.value = row
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    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()
  })
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  // if (event.target.files[0].type === 'application/pdf') {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
//   }
//   else {
//     ElMessage.error('请上传pdf格式')
//   }
}
// 打印
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 batchImport = () => {
  fileRef.value.click()
}
// 传给子组件的刷新事件
// const refreshDta = () => {
//   getList()
// }
onMounted(() => {
  getStatus()
  getType().then((_) => {
    getList()
  })
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input v-model="searchQuery.fileNo" placeholder="编号" clearable class="w-50 m-2" style="width: 187px;" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.fileName" placeholder="名称" clearable class="w-50 m-2" style="width: 187px;" />
        </search-item>
        <search-item>
          <el-input v-model="searchQuery.fileCode" placeholder="文件号" clearable class="w-50 m-2" style="width: 187px;" />
        </search-item>
        <!-- <search-item>
          <el-select v-model="searchQuery.fileType" class="m-2 normal-select" placeholder="类别" clearable>
            <el-option
              v-for="item in fileTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </search-item> -->
        <search-item>
          <el-date-picker
            v-model="publishTime"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="发布开始时间"
            end-placeholder="发布结束时间"
            clearable
            style="width: 360px;"
          />
          <!-- <el-date-picker
            v-model="searchQuery.publishTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="发布时间"
          /> -->
        </search-item>
        <search-item>
          <el-date-picker
            v-model="effectiveTime"
            type="datetimerange"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="实施开始时间"
            end-placeholder="实施结束时间"
            clearable
            style="width: 360px;"
          />
          <!-- <el-date-picker
            v-model="searchQuery.effectiveTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="实施时间"
          /> -->
        </search-item>
        <search-item>
          <el-select v-model="searchQuery.effectiveStatus" class="m-2" placeholder="实施状态" clearable style="width: 187px;">
            <el-option
              v-for="item in effectiveStatusSelect"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
          <!-- <el-input v-model.trim="searchQuery.effectiveStatus" class="m-2 normal-select" placeholder="实施状态" /> -->
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <input v-show="(searchQuery.limit === 0)" ref="fileRef" type="file" multiple @change="onFileChange">
          <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 v-if="proxy.hasPerm(`/file/${authority}/export`)" icon="icon-export" title="导出" @click="exportExcelBtn" />
          <icon-button v-if="proxy.hasPerm(`/file/${authority}/print`)" icon="icon-print" title="打印" @click="printList" />
        </template>
        <!-- 表格区域 -->
        <normal-table
          id="print"
          :data="list" :total="total" :columns="columns as any"
          :is-showmulti-select="true"
          :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
          :list-loading="loadingTable"
          :is-multi="true" @change="changePage" @multi-select="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="170">
              <template #default="{ row }">
                <el-button v-if="proxy.hasPerm(`/file/${authority}/detail`)" size="small" type="primary" link @click="detail(row)">
                  查看
                </el-button>
                <el-button v-if="proxy.hasPerm(`/file/${authority}/download`)" size="small" type="primary" link @click="exportSelf(row)">
                  下载
                </el-button>
                <el-button v-if="proxy.hasPerm(`/file/${authority}/abolish`)" size="small" :type="row.effectiveStatus === '3' ? 'info' : 'primary'" link :disabled=" row.effectiveStatus === '3'" @click="abolish(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>
  </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>
