<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.submitStatus"
                :options="submitStatusOptions"
                placeholder="请选择派工状态"
                clearable
                style="width: 200px"
            />
          </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>

      <!-- 工具栏 -->
      <div class="table-toolbar">
        <n-space>
          <n-button type="primary" @click="handleStatistics" disabled>
            <template #icon></template>
              汇报统计
          </n-button>
          <n-button @click="handleExport">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            导出{{ selectedIds.length > 0 ? `(${selectedIds.length})` : '' }}
          </n-button>
          <!-- <n-button @click="importModalVisible = true">
            <template #icon><n-icon><CloudUploadOutline /></n-icon></template>
            导入
          </n-button>

          <n-button type="error" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <template #icon><n-icon><TrashOutline /></n-icon></template>
            删除
          </n-button> -->
        </n-space>
      </div>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        size="small"
        remote
        :border="false"
        :single-line="false"
        striped
      />
        <div class="pagination-container" style="display: flex; justify-content: flex-end; margin-top: 12px">
          <n-pagination
            v-model:page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount"
            :page-sizes="[10, 20, 50, 100]"
            show-size-picker
            show-quick-jumper
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          >
            <template #prefix>
              共 {{ pagination.itemCount }} 条
            </template>
          </n-pagination>
         </div>
    </n-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal v-model:show="modalVisible" preset="card" :title="modalTitle" style="width: 600px">
      <n-form ref="formRef" :model="formData" :rules="formRules" label-placement="left" label-width="100px">
        <n-form-item label="派工id;派工id" path="assingWorkId">
          <n-input v-model:value="formData.assingWorkId" placeholder="请输入派工id;派工id" />
        </n-form-item>
        <n-form-item label="工序id;工序id" path="processId">
          <n-input v-model:value="formData.processId" placeholder="请输入工序id;工序id" />
        </n-form-item>
        <n-form-item label="提交数量;提交数量" path="quantity">
          <n-input v-model:value="formData.quantity" placeholder="请输入提交数量;提交数量" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="modalVisible = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 导入弹窗 -->
    <n-modal v-model:show="importModalVisible" preset="card" title="导入派工工单汇报记录" style="width: 500px">
      <n-space vertical>
        <n-alert type="info">
          <template #header>导入说明</template>
          <ul style="margin: 0; padding-left: 16px; line-height: 1.8">
            <li>请先下载导入模板，按模板格式填写数据</li>
            <li>支持 .xlsx 或 .xls 格式</li>
          </ul>
        </n-alert>
        <n-space>
          <n-button type="primary" @click="handleDownloadTemplate">
            <template #icon><n-icon><DownloadOutline /></n-icon></template>
            下载模板
          </n-button>
        </n-space>
        <n-upload :max="1" accept=".xlsx,.xls" :show-file-list="true" :custom-request="handleImportUpload">
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <n-icon size="48" :depth="3"><CloudUploadOutline /></n-icon>
            </div>
            <n-text style="font-size: 16px">点击或拖拽文件到此处上传</n-text>
            <n-p depth="3" style="margin: 8px 0 0 0">支持 .xlsx 或 .xls 格式</n-p>
          </n-upload-dragger>
        </n-upload>
      </n-space>
      <template #footer>
        <n-button @click="importModalVisible = false">关闭</n-button>
      </template>
    </n-modal>

    <!--汇报详情面板 -->
    <n-modal v-model:show="reportDetailVisible" preset="card" title="汇报详情" style="width: 1000px">
         <n-card title="质检信息" hoverable style="margin-bottom: 12px" >
            <div v-if="qualityTestings.length === 0" style="height:520px;display:flex;align-items:center;justify-content:center;color:#999">
              暂无质检单据数据
            </div>
          <n-tabs 
              type="line" 
              animated
              placement="left" 
              style="height: 520px"
              v-else
            >
              <n-tab-pane 
                v-for="item in qualityTestings"
                :name="item.qcNo"
                :tab="item.qcNo">
                   <n-card title="质检基础信息" style="margin-bottom:12px">
                    <n-descriptions :column="3">
                      <n-descriptions-item label="资源类型">{{formatDisplayValue("resourceType",item.resourceType)  }}</n-descriptions-item>
                      <n-descriptions-item label="质检状态">{{formatDisplayValue("status",item.qcStatus)  }}</n-descriptions-item>
                      <n-descriptions-item label="总数量">{{ item.totalQty }}</n-descriptions-item>
                    </n-descriptions>
                  </n-card>

                    <!--汇报表格-->
                    <n-card title="汇报列表">
                      <n-data-table
                        :columns="submitColumns"
                        :data="item.submitLogs"
                        :scroll-x="700"
                        max-height="320"
                        :pagination="{ pageSize:3 }"
                      >
                       <!--空数据提示插槽-->
                      <template #empty>
                        <div style="padding:40px;text-align:center;color:#999">
                          当前没有数据
                        </div>
                      </template>
                    
                    </n-data-table>
                     
                    </n-card>
              </n-tab-pane>
            </n-tabs>
         </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted } from 'vue'
import { NButton, NSpace, NIcon,NTag, NUpload, useMessage, useDialog, type DataTableColumns, type UploadCustomRequestOptions } from 'naive-ui'
import { SearchOutline, RefreshOutline, AddOutline, TrashOutline, CreateOutline, CloudUploadOutline, DownloadOutline, Options } from '@vicons/ionicons5'
import { submitLogApi, type SubmitLog } from '@/api/submitLog'
import { dictDataApi } from '@/api/org'
import router from '@/router'


const message = useMessage()
const dialog = useDialog()



// 表格数据
const tableData = ref<SubmitLog[]>([])
const loading = ref(false)
const selectedIds = ref<number[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50,100]
})

// 搜索表单
const searchForm = reactive({
  page:pagination.page as number,
  submitStatus:undefined 
})

// 弹窗
const modalVisible = ref(false)
const modalTitle = ref('')
const importModalVisible = ref(false)
const formRef = ref()
const defaultFormData: SubmitLog = {
  assingWorkId: undefined,
  processId: undefined,
  quantity: undefined,
}
const formData = reactive<SubmitLog>({ ...defaultFormData })
//汇报详情弹窗
const reportDetailVisible = ref(false)

// 字典选项（下拉框/单选框/复选框关联字典时使用）
//判定状态字典
const qcResultTypeOptions =  ref<{ label: string; value: any;class:any }[]>([])
//业务来源字典
const qcSourceTypeOptions = ref<{ label: string; value: any;class:any }[]>([])
//质检状态字典
const qcStatusOptions = ref<{ label: string; value: any;class:any }[]>([])
//汇报状态字典
const submitStatusOptions = ref<{ label: string; value: any ;class:any}[]>([])
// 表单校验规则
const formRules = {
}

// 表格列
const columns: DataTableColumns<SubmitLog> = [
  { title: '物料名称', key: 'materialName',align: 'center',
    render(rowData, rowIndex) {
      return rowData.materialName? rowData.materialName: '-'
    },
   },
  { title: '物料编码', key: 'materialCode',align: 'center',
     render(rowData, rowIndex) {
      return rowData.materialCode? rowData.materialCode: '-'
    },
   },
  { title: '物料数量', key: 'materialQty',align: 'center',
     render(rowData, rowIndex) {
      return rowData.materialQty? rowData.materialQty: '-'
    },
  },
  { title: '工序名称', key: 'processName',align: 'center' },
  { title: '工序编号', key: 'processCode',align: 'center' },
  { title: '汇报数量', key: 'quantity',align: 'center'},
  { title: '派工编号', key: 'assingCode',align: 'center' },
  { title: '汇报人', key: 'userName',align: 'center' },
  { title: '派工状态', key: 'submitStatus',align: 'center',
     render: (row) => {
      const val = row.submitStatus
      const opt = submitStatusOptions.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',align: 'center' },
]

//汇报详情属性
const  qualityTestings = ref()
const submitColumns = ref([
  { title: "提交人", key: "sumbitUser" },
  { title: "提交时间", key: "submitCreateTime" },
  { title: "提交数量", key: "quantity" },
  { title: "单据状态", key: "submitStatus",
      render: (row:any) => {
      const val = row.submitStatus
      const opt = qcResultTypeOptions.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 })
    }
   }
])
// 加载数据
async function loadData() {
  loading.value = true
  try {
    const res = await submitLogApi.page({
      page: pagination.page,
      pageSize: pagination.pageSize,
      submitStatus: searchForm.submitStatus
    })
    tableData.value = res.list
    pagination.itemCount = res.total
    console.log(pagination.itemCount);
    
  } finally {
    loading.value = false
  }
}

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

// 重置
function handleReset() {
  searchForm.submitStatus =  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[]
}

// 新增
function handleAdd() {
  modalTitle.value = '新增派工工单汇报记录'
  Object.assign(formData, defaultFormData)
  modalVisible.value = true
}

// 编辑
function handleEdit(row: SubmitLog) {
  modalTitle.value = '编辑派工工单汇报记录'
  Object.assign(formData, row)
  if (formData.createTime && typeof formData.createTime === 'string') {
    formData.createTime = new Date(formData.createTime.replace(' ', 'T')).getTime()
  }
  modalVisible.value = true
}

// 提交
async function handleSubmit() {
  await formRef.value?.validate()
  try {
    const submitData = { ...formData } as SubmitLog
    if (typeof submitData.createTime === 'number') {
      submitData.createTime = new Date(submitData.createTime).toISOString().slice(0, 19).replace('T', ' ')
    }
    if (submitData.id) {
      await submitLogApi.update(submitData)
      message.success('修改成功')
    } else {
      await submitLogApi.create(submitData)
      message.success('新增成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 删除
function handleDelete(row: SubmitLog) {
  dialog.warning({
    title: '提示',
    content: '确定要删除该记录吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await submitLogApi.delete([row.id!])
        message.success('删除成功')
        loadData()
      } catch (error) {
        // 错误已在拦截器处理
      }
    }
  })
}

// 批量删除
function handleBatchDelete() {
  dialog.warning({
    title: '提示',
    content: `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await submitLogApi.delete(selectedIds.value)
        message.success('删除成功')
        selectedIds.value = []
        loadData()
      } catch (error) {
        // 错误已在拦截器处理
      }
    }
  })
}

// 导出
async function handleExport() {
  try {
    const params: Record<string, any> = {}
    if (selectedIds.value.length > 0) params.ids = selectedIds.value
    if (searchForm.submitStatus != null) params.id = searchForm.submitStatus
    const blob = await submitLogApi.export(params)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '派工工单汇报记录数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 下载导入模板
async function handleDownloadTemplate() {
  try {
    const blob = await submitLogApi.downloadTemplate()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '派工工单汇报记录导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 导入上传
async function handleImportUpload({ file }: UploadCustomRequestOptions) {
  if (!file.file) return
  try {
    const result = await submitLogApi.importData(file.file)
    if (result.fail > 0) {
      dialog.warning({
        title: '导入结果',
        content: `成功: ${result.success} 条，失败: ${result.fail} 条\n错误信息: ${(result.errors || []).join('\n') || '无'}`,
        positiveText: '确定'
      })
    } else {
      message.success(`导入成功，共 ${result.success} 条数据`)
      importModalVisible.value = false
    }
    loadData()
  } catch (error) {
    // 错误已在拦截器处理
  }
}

// 加载字典选项
async function loadDictOptions() {
    try {
    const data = await dictDataApi.listByType('qc_result_type')
    qcResultTypeOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}
  try {
    const data = await dictDataApi.listByType('source_type')
    qcSourceTypeOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}
  try {
    const data = await dictDataApi.listByType('qc_status')
    qcStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}
  try {
    const data = await dictDataApi.listByType('submit_status')
    submitStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}
}

//查看汇报信息

function handleViewReport(row) {
  reportDetailVisible.value = true
  
  qualityTestings.value = row.qualityTestings
      
}


function formatDisplayValue(key:string,value: any){
  if (value === null || value === undefined) return '-'

  //根据字段类型格式化
  switch(key) {
     case 'resourceType': {
      const sourceOpt = qcSourceTypeOptions.value.find(o => o.value === value || String(o.value) === String(value))
      return sourceOpt ? sourceOpt.label : String(value)
    }
    case 'status': {
      const statusOpt = qcStatusOptions.value.find(o => o.value === value || String(o.value) === String(value))
      return statusOpt ? statusOpt.label : String(value)
    }

    case 'qcNo':
      return value ? new Date(value).toLocaleString('zh-CN') : '-'
    default:
      return String(value)
  }
}

//汇报统计
function handleStatistics() {
  let path = 'statistic'
  router.push(path)
}

onMounted(() => {
  loadData()
  loadDictOptions()
})
</script>

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

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