<template>
  <div class="page-container">
    <n-card>
      <!-- 搜索表单 -->
      <div class="search-form">
        <n-form inline :model="searchForm" label-placement="left">
          <n-form-item label="判定类型">
            <n-select
                v-model:value="searchForm.resultType"
                :options="qcResultTypeOptions"
                placeholder="请选择判定类型"
                clearable
                style="width: 200px"
            />
          </n-form-item>
          <n-form-item label="追溯码">
            <n-input v-model:value="searchForm.traceCode" placeholder="请输入批次号/SN码" clearable />
          </n-form-item>
          <n-form-item label="缺陷码">
            <n-input v-model:value="searchForm.defectCode" placeholder="请输入批次号/SN码" clearable />
          </n-form-item>
          <n-form-item>
            <n-space>
              <n-button type="primary" @click="handleSearch">
                <template #icon><n-icon><SearchOutline /></n-icon></template>
                搜索
              </n-button>
              <n-button @click="handleReset">
                <template #icon><n-icon><RefreshOutline /></n-icon></template>
                重置
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </div>

      <!-- 表格 -->
      <n-data-table
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :pagination="pagination"
          :row-key="(row:any) => row.id"
          :scroll-x="1200"
          @update:page="handlePageChange"
          @update:page-size="handlePageSizeChange"
          @update:checked-row-keys="handleCheck"
      />
    </n-card>



  </div>
</template>

<script setup lang="ts">
import { ref, reactive,h, onMounted } from 'vue'
import { NButton, NSpace,NTag, NIcon, type DataTableColumns} from 'naive-ui'
import { SearchOutline, RefreshOutline } from '@vicons/ionicons5'
import { qcResultDetailApi, type QcResultDetail } from '@/api/qcResultDetail'
import { dictDataApi } from '@/api/org'

import {useRoute} from "vue-router";
const qcId = ref<number>(0)


// 表格数据
const tableData = ref<QcResultDetail[]>([])
const loading = ref(false)
const selectedIds = ref<number[]>([])


const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})
// 搜索表单
const searchForm = reactive({
  page: pagination.page,
  pageSize: pagination.pageSize,
  qcId:qcId,
  resultType: undefined, //判定类型
  traceCode: undefined,//追溯码
  defectCode: undefined,//缺陷吗
})

// 字典选项（下拉框/单选框/复选框关联字典时使用）
const actionStatusOptions = ref<{ label: string; value: any }[]>([])
//判定类型
const qcResultTypeOptions = ref<{ label: string; value: any }[]>([])
//执行状态
const qcActionStatusOptions = ref<{ label: string; value: any;class:any }[]>([])


// 表格列
const columns: DataTableColumns<QcResultDetail> = [
  { type: 'selection' },
  { title: '判定类型', key: 'resultType',
    render(row) {
      const val = row.resultType
      const opt = qcResultTypeOptions.value.find(o => o.value === val || String(o.value) === String(val))
      return opt ? opt.label : (val ?? '-')
    }
  },
  { title: '判定数量', key: 'qty' },
  { title: '批次号/SN码', key: 'traceCode' },
  { title: '缺陷码', key: 'defectCode' },
  { title: '后续动作', key: 'handleAction' },
  { title: '执行状态', key: 'actionStatus',
    render(row) {
      const val = row.actionStatus
      const opt = qcActionStatusOptions.value.find(o => o.value === val || String(o.value) === String(val))
         if (!opt) return val ?? '-'
      return h(NTag, { type: opt.class, size: 'small' }, { default: () => opt.label })
    }
  },
  { title: '备注/原因描述', key: 'remark' },
  { title: '创建时间', key: 'createTime', width: 180 },
  { title: '更新时间', key: 'updateTime', width: 180 },
  // {
  //   title: '操作',
  //   key: 'actions',
  //   width: 140,
  //   fixed: 'right',
  //   render(row) {
  //     return h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'nowrap' } }, [
  //       h(NButton, { size: 'small', quaternary: true, onClick: () => handleEdit(row) }, {
  //         default: () => [h(NIcon, null, { default: () => h(CreateOutline) }), ' 编辑']
  //       }),
  //       h(NButton, { size: 'small', quaternary: true, type: 'error', onClick: () => handleDelete(row) }, {
  //         default: () => [h(NIcon, null, { default: () => h(TrashOutline) }), ' 删除']
  //       })
  //     ])
  //   }
  // }
]

// 加载数据
async function loadData() {
  loading.value = true
  try {
    const res = await qcResultDetailApi.page(searchForm)
    tableData.value = res.list
    pagination.itemCount = res.total
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  pagination.page = 1
  loadData()
}

// 重置
function handleReset() {
  searchForm.traceCode =  undefined
  searchForm.defectCode =  undefined
  searchForm.resultType =  undefined

  handleSearch()
}

// 分页
function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize
  pagination.page = 1
  loadData()
}

// 选择
function handleCheck(keys: Array<string | number>) {
  selectedIds.value = keys as number[]
}



// 加载字典选项
async function loadDictOptions() {
  try {
    const data = await dictDataApi.listByType('sys_status')
    actionStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue) }))
  } catch {}
  try {
    const data = await dictDataApi.listByType('qc_result_type')
    qcResultTypeOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue) }))
  }catch {}
  try {
    const data = await dictDataApi.listByType('qc_action_status')
    qcActionStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class: d.listClass }))
  }catch {}
}

onMounted(() => {
  const route = useRoute()
  qcId.value =Number(route.params.id)
  loadData()
  loadDictOptions()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}
</style>