<!-- 分包证书 -->
<script lang="ts" setup name="SubpackageCertificate">
import { reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { deleteCertificate, exportCertificate, getListPage, importCertificate } from '@/api/eqpt/subpackage/certificate'
import { getDeviceNameList, getModelAllList, getModelList } from '@/api/eqpt/device/model'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import useTemplateDownload from '@/utils/useTemplateDownload'
const { proxy } = getCurrentInstance() as any
const listQuery = reactive({
  certificateName: '',
  certificateNo: '',
  createTimeEnd: '',
  createTimeStart: '',
  equipmentName: '',
  equipmentNo: '',
  subcontractorName: '',
  equipmentModel: '',
  equipmentManufactureNo: '',
  certificateValidStart: '',
  certificateValidEnd: '',
  checkDateEnd: '',
  checkDateStart: '',
  offset: 1,
  limit: 20,
})
const datetimerange = ref()
watch(() => datetimerange.value, (newVal) => {
  listQuery.checkDateStart = ''
  listQuery.checkDateEnd = ''
  if (Array.isArray(newVal)) {
    if (newVal.length) {
      listQuery.checkDateStart = `${newVal[0]} 00:00:00`
      listQuery.checkDateEnd = `${newVal[1]} 23:59:59`
    }
  }
}, {
  deep: true,
})
const datetimerange1 = ref()
watch(() => datetimerange1.value, (newVal) => {
  listQuery.certificateValidStart = ''
  listQuery.certificateValidEnd = ''
  if (Array.isArray(newVal)) {
    if (newVal.length) {
      listQuery.certificateValidStart = `${newVal[0]} 00:00:00`
      listQuery.certificateValidEnd = `${newVal[1]} 23:59:59`
    }
  }
}, {
  deep: true,
})
const columns = ref([
  {
    text: '证书编号',
    value: 'certificateNo',
    align: 'center',
  },
  {
    text: '证书名称',
    value: 'certificateName',
    align: 'center',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '规格型号',
    value: 'equipmentModel',
    align: 'center',
  },
  {
    text: '出厂编号',
    value: 'equipmentManufactureNo',
    align: 'center',
  },
  {
    text: '检测单位',
    value: 'subcontractorName',
    align: 'center',
  },
  {
    text: '检定(校准)目期',
    value: 'checkDate',
    align: 'center',
  },
  {
    text: '证书有效期',
    value: 'certificateValid',
    align: 'center',
  },
  {
    text: '计量标识',
    value: 'meterIdentifyName',
    align: 'center',
  },
])
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
// 设备名称
const deviceNameList = ref<any[]>([])
// 规格型号
const modelList = ref<any[]>([])
const allList = ref<any[]>([])
// 监听设备名称下拉框，修改规格型号和辅助字段
watch(() => listQuery.equipmentName, (newVal) => {
  if (newVal) {
    listQuery.equipmentModel = ''
    // 修改规格型号和辅助字段列表
    const data = allList.value.filter(item => item.equipmentName === newVal)
    modelList.value = Array.from(new Set(data.filter(item => item.model).map(item => item.model)))
  }
  else {
    listQuery.equipmentModel = ''
    modelList.value = Array.from(new Set(allList.value.filter(item => item.model).map(item => item.model)))
  }
})
// 获取数据
const fetchData = (isNowPage = true) => {
  listLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  getListPage(listQuery).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    listLoading.value = false
  })
}
fetchData()
// 查询数据
const search = () => {
  fetchData(false)
}
// 重置
const reset = () => {
  datetimerange.value = ''
  datetimerange1.value = ''
  listQuery.certificateName = ''
  listQuery.certificateNo = ''
  listQuery.createTimeEnd = ''
  listQuery.createTimeStart = ''
  listQuery.equipmentName = ''
  listQuery.equipmentNo = ''
  listQuery.subcontractorName = ''
  listQuery.equipmentModel = ''
  listQuery.equipmentManufactureNo = ''
  listQuery.certificateValidStart = ''
  listQuery.certificateValidEnd = ''
  listQuery.checkDateEnd = ''
  listQuery.checkDateStart = ''
  listQuery.offset = 1
  listQuery.limit = 20
  modelList.value = Array.from(new Set(allList.value.filter(item => item.model).map(item => item.model)))
  search()
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  fetchData()
}
// 表格被选中的行
const selectList = ref<any[]>([])
// 表格多选
const multiSelect = (row: any[]) => {
  selectList.value = row
}
const $router = useRouter()
// 新建编辑操作
const handler = (row: any, type: string) => {
  $router.push({
    path: `/pcertificatepage/${type}`,
    query: {
      row: JSON.stringify(row),
      id: row.id,
    },
  })
}
// 删除
const delHandler = (row: any) => {
  console.log(row, 'row')
  ElMessageBox.confirm(
    '确认删除吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteCertificate(row).then((res) => {
      ElMessage.success('操作成功')
      search()
    })
  })
}
// 打印列表
const printList = () => {
  if (list.value.length) {
    // selectList.value.map(item => item.id)
    const properties = columns.value.map((item) => {
      return {
        field: item.value,
        displayName: item.text,
      }
    })
    if (selectList.value.length) {
      printJSON(selectList.value, properties, '分包方证书')
      // selectList.value = []
    }
    else {
      printJSON(list.value, properties, '分包方证书')
    }
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
// 导出列表
const exportList = () => {
  if (list.value.length) {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(255, 255, 255, 0.8)',
    })
    const data = {
      ...listQuery,
      offset: undefined,
      limit: undefined,
      ids: selectList.value.map(item => item.id),
    }
    const fd = new FormData()
    fd.append('certificateName', data.certificateName)
    fd.append('certificateNo', data.certificateNo)
    fd.append('createTimeEnd', data.createTimeEnd)
    fd.append('createTimeStart', data.createTimeStart)
    fd.append('equipmentName', data.equipmentName)
    fd.append('equipmentNo', data.equipmentNo)
    fd.append('ids', data.ids)
    fd.append('subcontractorName', data.subcontractorName)
    exportCertificate(fd).then((res) => {
      exportFile(res.data, '分包方证书')
      loading.close()
    })
      .catch((_) => {
        loading.close()
      })
  }
  else {
    ElMessage.warning('无可导出内容')
  }
}
const fileRef = ref() // 文件上传input，获取input的引用
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    // fd.append('equipmentType', $props.equipmentType)
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    importCertificate(fd).then((res) => {
      if (res.code === 200) {
        ElMessage.success('上传成功')
        fileRef.value.value = ''
        loading.close()
        fetchData(true)
      }
      else {
        fileRef.value.value = ''
        // ElMessage.error(res.message)
        loading.close()
      }
    }).catch(() => {
      // ElMessage.error(err.message)
      loading.close()
    })
  }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// 获取下拉框
const fetchDict = () => {
  // 设备名称
  getDeviceNameList({ equipmentType: '1' }).then((res) => {
    deviceNameList.value = res.data
  })
  // 规格型号
  getModelAllList({ equipmentType: '1' }).then((res) => {
    allList.value = res.data
    modelList.value = Array.from(new Set(res.data.filter((item: any) => item.model).map(item => item.model)))
  })
}
fetchDict()
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model.trim="listQuery.certificateNo" placeholder="证书编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.certificateName" placeholder="证书名称" clearable />
      </search-item>
      <!-- <search-item>
        <el-input v-model.trim="listQuery.equipmentNo" placeholder="受检设备编号" clearable />
      </search-item> -->
      <search-item>
        <!-- <el-input v-model.trim="listQuery.equipmentName" placeholder="设备名称" clearable /> -->
        <el-select v-model.trim="listQuery.equipmentName" filterable placeholder="设备名称" clearable>
          <el-option v-for="(item, index) in deviceNameList" :key="index" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <!-- <el-input v-model.trim="listQuery.equipmentModel" placeholder="规格型号" clearable /> -->
        <el-select v-model.trim="listQuery.equipmentModel" filterable placeholder="规格型号" clearable>
          <el-option v-for="item in modelList" :key="item" :label="item" :value="item" />
        </el-select>
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.equipmentManufactureNo" placeholder="出厂编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.subcontractorName" placeholder="检测单位名称" clearable />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="datetimerange" type="daterange" value-format="YYYY-MM-DD"
          format="YYYY-MM-DD" range-separator="至" start-placeholder="检定开始时间" end-placeholder="检定结束时间"
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="datetimerange1" type="daterange" value-format="YYYY-MM-DD"
          format="YYYY-MM-DD" range-separator="至" start-placeholder="证书有效期开始时间" end-placeholder="证书有效期结束时间"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button icon="icon-add" title="新增" @click="handler({}, 'create')" />
        <icon-button icon="icon-import" title="批量导入" @click="batchImport" />
        <icon-button icon="icon-template" title="模板下载" @click="useTemplateDownload('外送证书管理模块')" />
        <icon-button icon="icon-export" title="导出" @click="exportList" />
        <icon-button icon="icon-print" title="打印" @click="printList" />
        <input ref="fileRef" style="display: none;" type="file" accept=".xls,.xlsx,.zip,.rar" @change="onFileChange">
      </template>
      <!-- 普通表格 -->
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="listLoading"
        :is-showmulti-select="true" :is-multi="true" @change="changePage" @multi-select="multiSelect"
      >
        <template #columns>
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handler(scope.row, 'detail')">
                查看
              </el-button>
              <el-button link type="primary" size="small" @click="handler(scope.row, 'update')">
                编辑
              </el-button>
              <el-button link type="danger" size="small" @click="delHandler(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

