<template>
    <div>
        <n-data-table
              v-model:expanded-row-keys="AssingWorkExpandedKeys"
              :columns="AssingWorkColumns"
              :data="AssingWorkTableData"
              :loading="tableLoading"
              :row-key="RowKey"
              :scroll-x="1920"
              :max-height="1000"
              size="small"
              striped
              :single-line="true"
              class="assing-work-table"
              style="margin-bottom:15px"
              @update-expanded-row-keys="handleExpandChange"
          />

        <div class="pagination-container">
          <n-button
              size="small"
              quaternary
              :disabled="tableLoading || !AssingWorkTableData.length"
              @click="AssingWorkToggleExpandAll"
          >
              {{ AssingWorkAllExpanded ? '全部收起' : '全部展开' }}
          </n-button>
          <n-pagination
            v-model:page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount"
            :page-sizes="[2,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-modal
        v-model:show="showQcReport"
        preset="card"
        :title="reportTitle"
        :bordered="false"
        style="width: 920px"
        :segmented="{ content: true, footer: true }"
      >
          <SubmitLogInfoPage
              v-if="baseInfo.logOrQuality === 'log'"
              :assingId="assingId"
              :baseInfo="baseInfo"
          />
          <QualityInfoPage
              v-if="baseInfo.logOrQuality === 'Quality'"
              :assingId="assingId"
              :baseInfo="baseInfo"
          />
        <template #footer>
          <n-space justify="end">
            <n-button @click="showQcReport = false">关闭</n-button>
          </n-space>
        </template>
      </n-modal>
      <!--派工详情弹窗-->
      <n-modal v-model:show="showAssingWorkDetail" title="派工详情" style="width: 1000px" >
          <n-card>
            <n-descriptions :column="2" bordered size="small" label-placement="left" style="margin-bottom: 16px">
              <n-descriptions-item label="物料编码">{{ assingWorkDetail.materialCode || '-' }}</n-descriptions-item>
              <n-descriptions-item label="物料名称">{{ assingWorkDetail.materialName || '-' }}</n-descriptions-item>
              <n-descriptions-item label="工单号">{{ assingWorkDetail.workOrderCode || '-' }}</n-descriptions-item>
              <n-descriptions-item label="工序名称">{{ assingWorkDetail.processName || '-' }}</n-descriptions-item>
              <n-descriptions-item label="车间名称">{{ assingWorkDetail.workshopName || '-' }}</n-descriptions-item>
              <n-descriptions-item label="生产工段">{{ assingWorkDetail.sectionName || '-' }}</n-descriptions-item>
              <n-descriptions-item label="生产设备">{{ assingWorkDetail.deviceName || '-' }}</n-descriptions-item>
              <n-descriptions-item label="派工编号">{{ assingWorkDetail.assingCode || '-' }}</n-descriptions-item>
              <n-descriptions-item label="派工数量">{{ assingWorkDetail.quantity ?? '-' }}</n-descriptions-item>
              <n-descriptions-item label="是否返工">{{ handlerReWork(assingWorkDetail.rework) ?? '-' }}</n-descriptions-item>
              <n-descriptions-item label="返工数量">{{ assingWorkDetail.reworkNum ?? '-' }}</n-descriptions-item>
              <n-descriptions-item label="派工状态">{{ handlerPatchStatus(assingWorkDetail.assingStatus) ?? '-' }}</n-descriptions-item>
              <n-descriptions-item label="暂停时间">{{ formatWorkSeconds(assingWorkDetail.pauseSeconds) }}</n-descriptions-item>
              <n-descriptions-item label="调车时间">{{ formatWorkSeconds(assingWorkDetail.shuntSeconds) }}</n-descriptions-item>
              <n-descriptions-item label="实际工时">{{ formatWorkSeconds(assingWorkDetail.actualWorkSeconds) }}</n-descriptions-item>
              <n-descriptions-item label="单件工时">{{ formatWorkSeconds(assingWorkDetail.unitWorkSeconds) }}</n-descriptions-item>

            </n-descriptions>

            <template #footer>
              <n-space justify="end">
                <n-button @click="showAssingWorkDetail = false">取消</n-button>
              </n-space>
            </template>
          </n-card>

      </n-modal>

    </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  h,
  reactive,
  onMounted,
} from 'vue'

import { mytasks,type AssingWork } from '@/api/production';
import {
  NButton, NSpace, NTag, NDataTable, NIcon, DataTableColumns, NDescriptions, NDescriptionsItem, NPagination
} from 'naive-ui'
import { DocumentTextOutline, ShieldCheckmarkOutline } from '@vicons/ionicons5'
import { dictDataApi } from '@/api/org'
import { assingWorkDetailApi,AssingWorkDetail } from '@/api/AssingWorkDetail'
import SubmitLogInfoPage from "@/views/production/componets/SubmitLogInfoPage.vue";
import QualityInfoPage from "@/views/production/componets/QualityInfoPage.vue";
import { formatWorkSeconds, getaDtetime } from '@/utils/tool'

function dash(value: unknown) {
  if (value === 0) return '0'
  if (value == null || value === '') return '-'
  return String(value)
}

function renderInline(primary?: unknown, secondary?: unknown) {
  const main = dash(primary)
  const sub = dash(secondary)
  const title = sub === '-' ? main : `${main} ${sub}`
  return h('div', { class: 'cell-inline', title }, [
    h('span', { class: 'cell-main' }, main),
    sub !== '-' ? h('span', { class: 'cell-sub' }, sub) : null
  ])
}

function renderFlag(label: string, value: unknown) {
  const yes = value == 1
  const no = value == 0
  return h('span', {
    class: ['flag-chip', yes ? 'is-yes' : no ? 'is-no' : 'is-empty']
  }, `${label}${yes ? '是' : no ? '否' : '-'}`)
}

function compactHours(seconds?: number | string | null) {
  return formatWorkSeconds(seconds).replace('小时', 'h').replace('分', 'm').replace('秒', 's')
}

function completedQtyOf(row: any) {
  return Number(row.completedQuantity ?? row.completeQuantity) || 0
}

function planQtyOf(row: any) {
  return Number(row.quantity) || 0
}

function formatCompletedTime(value: unknown) {
  if (!value) return '-'
  if (typeof value === 'number' || value instanceof Date) return getaDtetime(value)
  return String(value)
}


const defaultBaseInfo = ref({
  materialName:undefined,
  materialCode:undefined,
  processName:undefined,
  processCode:undefined,
  assingCode:undefined,
  logOrQuality:undefined,
  workOrderCode:undefined
})

const baseInfo = ref({...defaultBaseInfo})

const qcAssingStatusOptions = ref<{ label: string; value: any;class:any }[]>([])
const qcAssingWorkDetailStatusOptions = ref<{ label: string; value: any;class:any }[]>([])

//汇报信息
const tableLoading = ref<Boolean>(false)
const AssingWorkTableData = ref<AssingWork[]>([])
const AssingWorkExpandedKeys = ref<Array<string |number>>([])

const processName = ref<string>()
const assingCode = ref<string>()
const materialCode = ref<string>()
const materialName = ref<string>()
const workOrderCode = ref<string>()

//派工详情弹窗
const showAssingWorkDetail = ref<boolean>(false)
const assingWorkDetail = ref<AssingWork>({})


const AssingWorkColumns :DataTableColumns<AssingWork> = [

  {
    type:"expand",
    expandable:()=>true,
    renderExpand:(row) => renderAssingWorkExpand(row)
  },
  {
    align:"center",
    title:"派工编号",
    key:"assingCode",
    width: 170,
    render(row:any) {
      return h(
          'a',
          {
            class: 'route-code-link',
            href: 'javascript:;',
            onClick: () => {
              viewAssingWorkDetail(row)
            },
          },
          row.assingCode
      )
    }
  },
  {
    title: '工单 / 工序',
    key: 'workOrderCode',
    width: 240,
    render(row: any) {
      return renderInline(row.workOrderCode, row.processName)
    }
  },
  {
    title: '物料编码',
    key: 'materialCode',
    width: 120,
    ellipsis: false,
    className: 'material-full-cell',
    render(row: any) {
      return h('span', { class: 'cell-full' }, dash(row.materialCode))
    }
  },
  {
    title: '物料名称',
    key: 'materialName',
    width: 120,
    ellipsis: false,
    className: 'material-full-cell',
    render(row: any) {
      return h('span', { class: 'cell-full' }, dash(row.materialName))
    }
  },
  {
    title: '工位 / 设备',
    key: 'deviceName',
    width: 120,
    ellipsis: { tooltip: true },
    render(row: any) {
      return dash(row.deviceName)
    }
  },
  {
    align: 'center',
    title: '质检 / 入库',
    key: 'qualityInspection',
    width: 126,
    render(row: any) {
      return h('div', { class: 'flag-group' }, [
        renderFlag('质检', row.qualityInspection),
        renderFlag('入库', row.storageEntry)
      ])
    }
  },
  {
    align: 'center',
    align:'center',
    title: '是否入库',
    key: 'storageEntry',
    width: 90,
    render(row) {
      var opt = row.storageEntry
      if (opt == 0) {
        return h(NTag, { type: 'error', size: 'small' }, { default: () => "否" })
      }
      if (opt == 1) {
        return h(NTag, { type: 'success', size: 'small' }, { default: () => "是" })
      }
    }
  },
  {
    align:'center',
    title: '返工任务',
    key: 'rework',
    width: 90,
    render(row) {
      var opt = row.rework
      if (opt == 0) {
        return h(NTag, { type: 'error', size: 'small' }, { default: () => "否" })
      }
      if (opt == 1) {
        return h(NTag, { type: 'success', size: 'small' }, { default: () => "是" })
      }
    }
  },
  {
    align:'center',
    title: '派工状态',
    key: 'assingStatus',
    width: 96,
    render(row: any) {
      const val = row.assingStatus
      const opt = qcAssingStatusOptions.value.find(o => o.value === val || String(o.value) === String(val))
      if (!opt) return dash(val)
      return h(NTag, { type: opt.class, size: 'small', bordered: false }, { default: () => opt.label })
    }
  },
  {
    title: '完成进度',
    key: 'quantity',
    width: 88,
    render(row: any) {
      return h('span', { class: 'qty-text' }, `${completedQtyOf(row)}/${planQtyOf(row)}`)
    }
  },
  {
    title: '完成时间',
    key: 'completedTime',
    width: 156,
    render(row: any) {
      return h('span', { class: 'time-text' }, formatCompletedTime(row.completedTime))
    }
  },
  {
    title: '工时',
    key: 'actualWorkSeconds',
    width: 200,
    ellipsis: { tooltip: true },
    render(row: any) {
      const title = `暂停 ${formatWorkSeconds(row.pauseSeconds)}　调车 ${formatWorkSeconds(row.shuntSeconds)}　实际 ${formatWorkSeconds(row.actualWorkSeconds)}　单件 ${formatWorkSeconds(row.unitWorkSeconds)}`
      return h('div', { class: 'hours-cell', title }, [
        h('span', { class: 'hours-item' }, ['停 ', h('b', compactHours(row.pauseSeconds))]),
        h('span', { class: 'hours-item' }, ['调 ', h('b', compactHours(row.shuntSeconds))]),
        h('span', { class: 'hours-item is-actual' }, ['实 ', h('b', compactHours(row.actualWorkSeconds))]),
        h('span', { class: 'hours-item is-unit' }, ['单 ', h('b', compactHours(row.unitWorkSeconds))])
      ])
    }
  },
  {
    align: 'center',
    title: '状态',
    key: 'status',
    width: 84,
    render(row: any) {
      if (row.status == 0) {
        return h(NTag, { type: 'success', size: 'small', bordered: false }, { default: () => '启用' })
      }
      if (row.status == 1) {
        return h(NTag, { type: 'warning', size: 'small', bordered: false }, { default: () => '已暂停' })
      }
      if (row.status == 2) {
        return h(NTag, { type: 'info', size: 'small', bordered: false }, { default: () => '已改派' })
      }
      return '-'
    }
  },
  {
    align: 'center',
    title: '操作',
    key: 'action',
    width: 196,
    fixed: 'right',
    render(row: any) {
      return h('div', { class: 'action-cell' }, [
        h(NButton, {
          size: 'small',
          quaternary: true,
          onClick: () => handleReportRecords(row)
        }, {
          default: () => [
            h(NIcon, { size: 16 }, { default: () => h(DocumentTextOutline) }),
            ' 汇报信息'
          ]
        }),
        h(NButton, {
          size: 'small',
          quaternary: true,
          onClick: () => handleQualityRecords(row)
        }, {
          default: () => [
            h(NIcon, { size: 16 }, { default: () => h(ShieldCheckmarkOutline) }),
            ' 质检信息'
          ]
        })
      ])
    }
  }

]

const showQcReport = ref<boolean>(false)
const reportTitle = ref<string>()



const AssingWorkDetailColums:DataTableColumns<AssingWorkDetail> = [
   {
    align:"center",
    title:"工位/设备",
    key:"deviceName",
    width:100,
    render(row:any) {
      var opt = row.deviceName
      if(opt) return opt
      return '-'
    }
  },
  {
    align:"center",
    title:"数量",
    key:"num",
    width:80
  },
  {
    align:"center",
    title:"暂停时间",
    key:"pauseSeconds",
    width:120,
    render(row: any) {
      return formatWorkSeconds(row.pauseSeconds)
    }
  },
  {
    align:"center",
    title:"调车时间",
    key:"shuntSeconds",
    width:120,
    render(row: any) {
      return formatWorkSeconds(row.shuntSeconds)
    }
  },
  {
    align:"center",
    title:"实际工时",
    key:"actualWorkSeconds",
    width:120,
    render(row: any) {
      return formatWorkSeconds(row.actualWorkSeconds)
    }
  },
  {
    align:"center",
    title:"来源",
    key:"source",
    width:100,
    render(row:any) {
      var opt = row.source
      if(opt == 1) return '设备'
      if(opt == 2) return '终端'
      if(opt == 3) return '后台'
      return '-'
    }
  },
  {
    align:'center',
    title: '状态',
    key: 'status',
    width: 100,
    render(row:any) {
      const val = row.status
      const opt = qcAssingWorkDetailStatusOptions.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 })

    }
    //派工状态0待执行 1执行中 2质检中+3已汇报一4已关闭
  },
  {
    align:"center",
    title:"操作人",
    key:"userName",
    width:100
  },
  {
    align:"center",
    title:"创建时间",
    key:"createTime",
    width:150
  },
]

//分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0
})


function handlePageChange(page: number) {
  pagination.page = page
  getlist()
}

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

// //获取列表数据
async function getlist() {
  tableLoading.value = true
  try {
    const rps: any = await mytasks({
      page: pagination.page,
      pageSize: pagination.pageSize,
      processName: processName.value || undefined,
      assingCode: assingCode.value || undefined,
      materialCode: materialCode.value || undefined,
      materialName: materialName.value || undefined,
    })
    AssingWorkTableData.value = rps?.records ?? []
    pagination.itemCount = rps?.total ?? 0
  } catch (error) {
    console.error(error)
  } finally {
    tableLoading.value = false
  }
}

const loadTableData = async (params: Record<string, any> = {}) => {
  processName.value = params.processName || undefined
  assingCode.value = params.assingCode || undefined
  materialCode.value = params.materialCode || undefined
  materialName.value = params.materialName || undefined
  pagination.page = 1
  AssingWorkExpandedKeys.value = []
  await getlist()
}


function RowKey(row:AssingWork) {
    return row.id
}

function DetailRowKey(row:any) {
    return row.id
}

const AssingWorkAllExpanded = computed(()=>{
    const total = AssingWorkTableData.value.length
    if(!total) return false
    return AssingWorkExpandedKeys.value.length >= total
})

function AssingWorkToggleExpandAll() {
  console.log(AssingWorkTableData.value)
  if(AssingWorkAllExpanded.value) {
    console.log(AssingWorkTableData.value)
        AssingWorkExpandedKeys.value = []
    }else{
        AssingWorkExpandedKeys.value = AssingWorkTableData.value.map(RowKey)
    console.log(AssingWorkTableData.value)
    }
}

// 缓存：key=派工id，value=明细数组
interface DetailPageState {
  list: AssingWorkDetail[]
  page: number
  pageSize: number
  total: number
  loading: boolean
}

// key：父行id
const expandDetailMap = new Map<number, DetailPageState>()


function renderAssingWorkExpand(row: AssingWork) {
  const rowId = row.id

  if (!expandDetailMap.has(rowId)) {
    expandDetailMap.set(rowId, reactive({
      list: [],
      page: 1,
      pageSize: 10,
      total: 0,
      loading: true
    }))
    loadDetail(rowId)
  }

  const state = expandDetailMap.get(rowId)!
  console.log(state)
  console.log(state.list)

  // 加载中提示
  // if (state.loading) {
  //   return h('div', {style: 'padding:12px'}, '加载中...')
  // }


  return h('div', { style: 'padding: 0 16px 12px' }, [
    h(NDataTable, {
      columns: AssingWorkDetailColums,
      data: state.list,
      rowKey: DetailRowKey,
      size: 'small',
      bordered: true,
      striped: true,
      scrollX: 1360
    }),
    // ✅ 复刻你原来的分页容器 + n‑pagination + prefix插槽
    h('div', {
      class: 'pagination-container',
      style: 'display: flex; justify-content: flex-end; margin-top: 12px'
    }, [
      h(NPagination, {
        page: state.page,
        pageSize: state.pageSize,
        itemCount: state.total,
        onUpdatePage: (p: number) => handleDetailPageChange(rowId, p),
        onUpdatePageSize: (sz: number) => handleDetailPageSizeChange(rowId, sz)
      }, {
        // ✅ #prefix 插槽
        prefix: () => h('span', `共 ${state.total} 条`)
      })
    ])
  ])
}
// 分页切换事件，点击页码/每页大小
async function handleDetailPageChange(rowId: number,page:number) {
  const state = expandDetailMap.get(rowId)
  if (!state) return
  state.page = page
  loadDetail(rowId)
}

async function handleDetailPageSizeChange(rowId: number,pageSize: number) {
  const state = expandDetailMap.get(rowId)
  if (!state) return
  state.pageSize = pageSize
  state.page = 1
  loadDetail(rowId)
}

function  handleExpandChange(openKeys: number[]){
  for (const [rowId] of expandDetailMap) {
    if (!openKeys.includes(rowId)) {
      expandDetailMap.delete(rowId)
    }
  }
}



const loadDetail = async (rowId: number)=>{
  const state = expandDetailMap.get(rowId)
  if (!state) return
  state.loading = true
  try {
    const res = await assingWorkDetailApi.selectAssingWorkDetailListByAssingWorkId({
      assingWorkId: rowId,
      page: state.page,
      pageSize: state.pageSize
    })
    state.list = res.list
    state.total = res.total
  }finally {
    state.loading = false
  }
}

// 加载字典选项
async function loadDictOptions() {
  try {
    const data = await dictDataApi.listByType('assing_status')
    qcAssingStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}
  try {
    const data = await dictDataApi.listByType('assing_work_detail_status')
    qcAssingWorkDetailStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}

}

//汇报信息弹窗
const assingId = ref<number>(null)
function handleReportRecords(row:any) {
  showQcReport.value = true
  reportTitle.value = "汇报信息"
  assingId.value = row.id
  baseInfo.value = {...row}
  baseInfo.value.logOrQuality = "log"
}



//质检信息弹窗
function handleQualityRecords(row:any) {
  showQcReport.value = true
  reportTitle.value = "质检信息"
  assingId.value = row.id
  baseInfo.value = {...row}
  baseInfo.value.logOrQuality = "Quality"
}

const viewAssingWorkDetail= ((row:any)=>{
  showAssingWorkDetail.value = true
  assingWorkDetail.value = row
  console.log(assingWorkDetail.value)
})


const handlerReWork = ((row:any)=>{
  if (row == 0) return '否'
  if (row == 1) return '是'
})

const handlerPatchStatus = ((row:any)=>{
  const val = row
  console.log(qcAssingStatusOptions.value)
  const opt = qcAssingStatusOptions.value.find(
      o => o.value === val || String(o.value) === String(val)
  )
  if (!opt) return val ?? '-'
  console.log( opt)
  return opt.label
})

onMounted(()=>{
    getlist()
    loadDictOptions()
})


defineExpose({
  loadTableData
})

</script>


<style scoped>
    .pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 12px;
    }
    .pgClass {
      font-weight: bold;
    }
    :deep(.assing-work-table .n-data-table-th) {
      padding-top: 6px;
      padding-bottom: 6px;
    }
    :deep(.assing-work-table .n-data-table-td) {
      padding-top: 4px;
      padding-bottom: 4px;
    }
    :deep(.route-code-link) {
      color: #1f6feb;
      font-weight: 600;
      font-variant-numeric: tabular-nums;
      text-decoration: none;
    }
    :deep(.route-code-link:hover) {
      text-decoration: underline;
    }
    :deep(.cell-inline) {
      display: flex;
      align-items: baseline;
      gap: 6px;
      min-width: 0;
      overflow: hidden;
      white-space: nowrap;
    }
    :deep(.cell-main) {
      color: #1f2328;
      font-weight: 600;
      flex-shrink: 0;
    }
    :deep(.cell-sub) {
      color: #656d76;
      font-size: 12px;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    :deep(.cell-full) {
      display: inline-block;
      white-space: nowrap;
      overflow: visible;
      word-break: keep-all;
    }
    :deep(.n-data-table-td.material-full-cell) {
      overflow: visible;
      white-space: nowrap;
    }
    :deep(.action-cell) {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      flex-wrap: nowrap;
    }
    :deep(.flag-group) {
      display: flex;
      justify-content: center;
      gap: 4px;
    }
    :deep(.flag-chip) {
      display: inline-flex;
      align-items: center;
      padding: 0 6px;
      border-radius: 999px;
      font-size: 12px;
      line-height: 18px;
      white-space: nowrap;
    }
    :deep(.flag-chip.is-yes) {
      color: #1a7f37;
      background: #dafbe1;
    }
    :deep(.flag-chip.is-no) {
      color: #656d76;
      background: #f6f8fa;
    }
    :deep(.flag-chip.is-empty) {
      color: #8c959f;
      background: #f6f8fa;
    }
    :deep(.qty-text) {
      font-variant-numeric: tabular-nums;
      font-weight: 600;
      color: #1f2328;
    }
    :deep(.time-text) {
      font-variant-numeric: tabular-nums;
      color: #424a53;
    }
    :deep(.hours-cell) {
      display: flex;
      align-items: center;
      gap: 8px;
      overflow: hidden;
      white-space: nowrap;
      font-size: 12px;
      color: #656d76;
    }
    :deep(.hours-item b) {
      font-weight: 600;
      color: #424a53;
      font-variant-numeric: tabular-nums;
    }
    :deep(.hours-item.is-actual),
    :deep(.hours-item.is-actual b) {
      color: #1f6feb;
    }
    :deep(.hours-item.is-unit),
    :deep(.hours-item.is-unit b) {
      color: #0d9488;
    }
</style>