<!-- 证书模板管理列表页 -->
<script lang="ts" setup name="CertTempateList">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import addDDialog from './addDDialog.vue'
import { printJSON } from '@/utils/printUtils'
import { getPhotoUrl, templateDelete, templateExport, templatePage } from '@/api/system/tool'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportFile } from '@/utils/exportUtils'
import type { dictType } from '@/global'
import { getDictByCode } from '@/api/system/dict'
import { download } from '@/utils/download'
const createTime = ref()
const searchQuery = reactive({
  templateNo: '', // 编号
  templateName: '', // 名称
  templateCreator: '', // 负责人
  createStartTime: '',
  createEndTime: '',
  limit: 20,
  offset: 1,
  certificationType: '0',
  ids: [] as string[],
}) // 查询参数
watch(() => createTime.value, (newVal) => {
  if (newVal) {
    searchQuery.createStartTime = newVal[0]
    searchQuery.createEndTime = newVal[1]
  }
  else {
    searchQuery.createStartTime = ''
    searchQuery.createEndTime = ''
  }
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<TableColumn[]>([
  { text: '编号', value: 'templateNo', align: 'center', width: '160' },
  { text: '模板名称', value: 'templateName', align: 'center' },
  { text: '模板类型', value: 'templateTypeName', align: 'center', width: '100' },
  { text: '负责人', value: 'templateCreator', align: 'center', width: '100' },
  { text: '内容描述', value: 'templateDesc', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
]) // 表格
const list = ref([]) // 表格数据
const addRef = ref() // 添加/编辑/详情/组件
// ---------------------------------------字典--------------------------------------------
const templateTypeMap = ref([]) as any // 模板类型
// 获取字典值
async function getDict() {
  // 模板类型
  const res = await getDictByCode('certificationType')
  res.data.forEach((item: { value: string; name: string }) => {
    templateTypeMap.value[`${item.value}`] = item.name
  })
}
// ---------------------------------------------------------------------------------------------
// 获取数据列表
const getList = () => {
  loadingTable.value = true
  templatePage(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: { certificationType: string }) => {
        return {
          ...item,
          templateTypeName: `${item.certificationType}` ? templateTypeMap.value[item.certificationType] : item.certificationType, // 模板类型
        }
      })
      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 handleEdit = (type: '编辑' | '详情' | '新增', row?: any) => {
  addRef.value.initDialog({
    ...row,
    title: type,
  })
}
// 删除
const remove = (row: any) => {
  ElMessageBox.confirm(
    `确认删除${row.templateName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      templateDelete({ id: (row.id as string) }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        }
      })
    })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  createTime.value = ''
  searchQuery.createEndTime = ''
  searchQuery.createStartTime = ''
  searchQuery.templateCreator = ''
  searchQuery.templateName = ''
  searchQuery.templateNo = ''
  getList()
}

// 下载
const fileUrl = ref('')
const downRef = ref()
const exportSele = (row: any) => {
  if (row.minioFileName) {
    getPhotoUrl(row.minioFileName).then((res) => {
      fileUrl.value = res.data
      download(res.data, row.templateName as string)
    }).catch(() => {
      ElMessage.error('下载失败')
    })
  }
  else {
    ElMessage('无可下载内容')
  }
}
// 表格被选中的行
const selectList = ref([])
// 表格多选
const multiSelect = (val: any) => {
  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: { id: string }) => {
      searchQuery.ids?.push(item.id as string)
    })
  }
  templateExport(searchQuery).then((res) => {
    exportFile(res.data, '证书模板管理')
    loading.close()
    searchQuery.ids = []
  }).catch((_) => {
    loading.close()
  })
}
// 打印
function printList() {
  const selectIds = selectList.value.map((item: { id: string }) => 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, '证书模板管理')
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: { id: string }) => selectIds.includes(item.id))
    printJSON(printList, properties, '证书模板管理')
  }
  else {
    ElMessage('无可打印内容')
  }
}
onMounted(() => {
  getDict().then(() => {
    getList()
  })
})
</script>

<template>
  <!-- 布局 -->
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model="searchQuery.templateNo" placeholder="编号" clearable class="w-50 m-2 normal-input" />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.templateName" placeholder="模板名称" clearable class="w-50 m-2 normal-input" />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.templateCreator" placeholder="负责人" clearable class="w-50 m-2 normal-input" />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="创建开始时间"
          end-placeholder="创建结束时间"
          clearable
        />
      </search-item>
    </search-area>
    <table-container>
      <!-- 表头区域 -->
      <template #btns-right>
        <icon-button icon="icon-add" title="新建" @click="handleEdit('新增')" />
        <icon-button icon="icon-export" title="导出" @click="exportExcelBtn" />
        <icon-button title="打印" icon="icon-print" @click="printList" />
      </template>
      <!-- 表格区域 -->
      <normal-table
        :data="list" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }" :list-loading="loadingTable"
        :is-showmulti-select="true" :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 size="small" type="primary" link @click="handleEdit('编辑', row)">
                编辑
              </el-button>
              <el-button size="small" type="primary" link @click="handleEdit('详情', row)">
                详情
              </el-button>
              <el-button size="small" type="primary" link @click="exportSele(row)">
                下载
              </el-button>
              <el-button size="small" type="danger" link @click="remove(row)">
                删除
              </el-button>
              <a
                ref="downRef"
                :href="fileUrl" type="primary"
                target="_blank"
              />
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <add-d-dialog ref="addRef" @reset-data="getList" />
  </app-container>
</template>

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

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