<script lang="ts" setup name="SampleList">
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { ISampleList, ISampleListQuery } from './sample_list_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { deleteSample, exportSapmleList, getSampleList } from '@/api/customer/sampleList'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
// 查询条件
const listQuery: Ref<ISampleListQuery> = ref({
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  sampleModel: '', // 型号
  customerId: '', // 委托方代码
  customerName: '', // 委托方名称
  startTime: '1', // 检定开始时间
  endTime: '1', // 检定结束时间
  offset: 1,
  limit: 20,
})
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 表头
const columns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'evaluationName', align: 'center' },
  { text: '委托方代码', value: 'customerId', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '检定周期', value: 'mesurePeriod', align: 'center' },
  { text: '上次检定时间', value: 'effectiveDate', align: 'center', width: '180px' },
  { text: '备注', value: 'remark', align: 'center', width: '180px' },
])
// 表格数据
const list = ref<ISampleList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])
// 文件上传input
const fileRef = ref()
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  listQuery.value.startTime = timeRange.value[0] as string || ''
  listQuery.value.endTime = timeRange.value[1] as string || ''
  getSampleList(listQuery.value).then((response) => {
    // 模拟数据

    // response.data.rows = [
    //   {
    //     id: '1597579843411234817',
    //     sampleNo: '1', // 样品编号
    //     sampleName: '1', // 样品名称
    //     sampleModel: '1', // 型号
    //     evaluationName: '1', // 出厂编号
    //     customerId: '1', // 委托方代码
    //     customerName: '1', // 委托方名称
    //     mesurePeriod: '1', // 检定周期
    //     effectiveDate: '1', // 上次检定时间
    //     remark: '备注', // 备注
    //   }]
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 点击编辑/详情
const handleEdit = (row: ISampleList, pageType: 'edit' | 'detail') => {
  $router.push(`/sample/${pageType}/${row.id}`)
}
// 点击删除
const handleDelete = (index: string, row: ISampleList) => {
  ElMessageBox.confirm(
    `确认删除${row.customerName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteSample({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    sampleModel: '', // 型号
    customerId: '', // 委托方代码
    customerName: '', // 委托方名称
    startTime: '', // 投诉开始时间
    endTime: '', // 投诉结束时间
    offset: 1,
    limit: 20,
  }
}

// 上传文件/批量导入
const onFileChange = (event: any) => {
  // todo: 校验文件类型，调用上传接口
  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格式')
  }
}
// 模板下载
const templateDownload = () => {

}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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(true)
}

// 点击批量导入
const uploadAll = () => {
  fileRef.value.click()
}
// 新建样品
const add = () => {
  $router.push('/sample/add')
}
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      sampleNo: listQuery.value.sampleNo, // 样品编号
      sampleName: listQuery.value.sampleName, // 样品名称
      sampleModel: listQuery.value.sampleModel, // 型号
      customerId: listQuery.value.customerId, // 委托方代码
      customerName: listQuery.value.customerName, // 委托方名称
      startTime: listQuery.value.startTime, // 投诉开始时间
      endTime: listQuery.value.endTime, // 投诉结束时间
      ids: checkoutList.value,
    }
    exportSapmleList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '样品列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '样品列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: any) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '样品列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

fetchData(true)
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleNo"
          placeholder="样品编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleName"
          placeholder="样品名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleModel"
          placeholder="型号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerId"
          placeholder="委托方代码"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerName"
          placeholder="委托方名称"
          clearable
        />
      </search-item>
      <search-item>
        <search-item>
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="到"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
            start-placeholder="上次检定开始时间"
            end-placeholder="上次检定结束时间"
          />
        </search-item>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/sample/list/import')" icon="icon-import" title="批量导入" type="primary" @click="uploadAll" />
        <icon-button v-if="proxy.hasPerm('/sample/list/import')" icon="icon-template" title="模板下载" type="primary" @click="templateDownload" />
        <icon-button v-if="proxy.hasPerm('/sample/list/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/sample/list/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/sample/list/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <input v-show="false" ref="fileRef" type="file" accept="*" @change="onFileChange">
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multi-select="handleSelectionChange"
      >
        <template #columns>
          <el-table-column label="操作" align="center" width="120">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/sample/list/update')"
                size="small"
                type="primary"
                link
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/sample/list/delete')"
                size="small"
                link
                type="danger"
                @click="handleDelete(row.$index, row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
