<!-- 原始记录列表 -->
<script lang="ts" setup name="PrimitiveLogList">
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IList, IListQuery, dictType } from './primitiveLogList'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { deletePrimitiveLogList, exportPrimitiveLogList, getPrimitiveLogList } from '@/api/business/lab/primitiveLogList'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'

const { proxy } = getCurrentInstance() as any
const $router = useRouter() // 初始化路由
// 查询条件
const listQuery = ref<IListQuery>({
  measureCategory: '',	// 校验类别
  createUser: '',	// 创建人
  manufacturingNo: '',	// 出厂编号
  originalRecordCode: '',	// 原始记录单编号
  sampleModel: '',	// 样品型号
  sampleName: '',	// 样品名称
  sampleNo: '',	// 样品编号
  offset: 1, // 当前页
  limit: 20, // 每页多少条
})
// 多选选中
const checkoutList = ref<string[]>([])
const list = ref<IList[]>([]) // 数据列表
const total = ref(0) // 总条数
const mesureCategoryList = ref<dictType[]>([]) // 校检类别
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '原始记录编号', value: 'originalRecordCode', width: '160', align: 'center' },
  { text: '原始记录名称', value: 'originalRecordName', align: 'center', width: '110' },
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '160' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '检校类别', value: 'measureCategory', align: 'center' },
  { text: '创建人', value: 'createUser', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
  { text: '备注', value: 'remark', align: 'center' },
])
// 获取字典值
async function getDict() {
  // 校检类别
  const response = await getDictByCode('measureCategory')
  mesureCategoryList.value = response.data
}

// 列表数据查询
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getPrimitiveLogList(listQuery.value).then((res) => {
    list.value = res.data.rows.map((item: IList) => {
      return {
        ...item,
        sampleNo: item.customerSampleInfo.sampleNo, // 样品编号
        sampleName: item.customerSampleInfo.sampleName, // 样品名称
        manufacturingNo: item.customerSampleInfo.manufacturingNo, // 出厂编号
        sampleModel: item.customerSampleInfo.sampleModel, // 型号
        measureCategory: mesureCategoryList.value.find(i => i.value === item.measureCategory) ? mesureCategoryList.value.find(i => i.value === item.measureCategory)!.name : '', // 校检类别
      }
    })
    total.value = res.data.total
    loadingTable.value = false
  })
}

// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    measureCategory: '',	// 校验类别
    createUser: '',	// 创建人
    manufacturingNo: '',	// 出厂编号
    originalRecordCode: '',	// 原始记录单编号
    sampleModel: '',	// 样品型号
    sampleName: '',	// 样品名称
    sampleNo: '',	// 样品编号
    offset: 1, // 当前页
    limit: 20, // 每页多少条
  }
  fetchData(true)
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      measureCategory: '',	// 校验类别
      createUser: '',	// 创建人
      manufacturingNo: '',	// 出厂编号
      originalRecordCode: '',	// 原始记录单编号
      sampleModel: '',	// 样品型号
      sampleName: '',	// 样品名称
      sampleNo: '',	// 样品编号
      offset: 1, // 当前页
      limit: 20, // 每页多少条
      ids: checkoutList.value,
    }
    exportPrimitiveLogList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '原始记录列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 点击编辑/详情
const handleEdit = (row: IList, pageType: 'edit' | 'detail') => {
  $router.push(`/lab/primitiveLogList/${pageType}/${row.id}`)
}

// 点击删除
const handleDelete = (row: IList) => {
  ElMessageBox.confirm(
    `确认删除${row.originalRecordName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deletePrimitiveLogList({ id: row.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('已删除')
          fetchData(true)
        }
      })
    })
}

// 多选选中
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 点击新建
const add = () => {
  $router.push('/lab/primitiveLogList/add')
}

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

// 打印列表
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 => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '原始记录单列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

onMounted(async () => {
  await getDict() // 获取字典
  fetchData(true) // 获取列表数据
})
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="searchList" @clear="clearList">
      <search-item>
        <el-input
          v-model.trim="listQuery.originalRecordCode"
          placeholder="原始记录编号"
          clearable
        />
      </search-item>
      <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.manufacturingNo"
          placeholder="出厂编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleModel"
          placeholder="型号"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.measureCategory"
          placeholder="请选择检校类别"
          style="width: 195px;"
          clearable
        >
          <el-option
            v-for="item in mesureCategoryList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.createUser"
          placeholder="创建人"
          clearable
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button
          v-if="proxy.hasPerm('/measure/train/plan/add')"
          icon="icon-add"
          title="新建"
          type="primary"
          @click="add"
        />
        <icon-button
          v-if="proxy.hasPerm('/measure/train/plan/export')"
          icon="icon-export"
          title="导出"
          type="primary"
          @click="exportAll"
        />
        <icon-button
          v-if="proxy.hasPerm('/measure/train/plan/print')"
          icon="icon-print"
          title="打印"
          type="primary"
          @click="printList"
        />
      </template>
      <normal-table
        :data="list"
        :total="total"
        :columns="columns"
        :query="listQuery"
        :list-loading="loadingTable"
        is-showmulti-select
        @change="changePage"
        @multi-select="handleSelectionChange"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" width="130" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/lab/primitiveLogList/edit')"
                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('/lab/primitiveLogList/delete')"
                size="small"
                link
                type="danger"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>
