<template>
    <div>
        <div class="toolbar">
               <n-space>
                    <n-button
                        size="small"
                        :disabled="tableLoading || !AssingWorkTableData.length"
                        @click="AssingWorkToggleExpandAll"
                    >
                        {{ AssingWorkAllExpanded ? '全部收起' : '全部展开' }}
                    </n-button>
                </n-space>  
        </div>
        <n-data-table
            v-model:expanded-row-keys="AssingWorkExpandedKeys"
            :columns="AssingWorkColumns"
            :data="AssingWorkTableData"
            :loading="tableLoading"
            :row-key="RowKey"
            :scroll-x="600"
            :max-height="1000"
            size="small"
            style="margin-bottom:15px"
        />
        <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="[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" :title="reportTitle" style="width: 1000px" >
        <div>
          <SubmitLogInfoPage
              v-if="baseInfo.logOrQuality === 'log'"
              :submitLogList="submitLogList"
              :baseInfo="baseInfo"
          />
          <QualityInfoPage
              v-if="baseInfo.logOrQuality === 'Quality'"
              :qualityTestingList="qualityList"
              :baseInfo="baseInfo"
          />
        </div>



        <template #footer>
          <n-space justify="end">
            <n-button @click="showQcReport = false">取消</n-button>
          </n-space>
        </template>
      </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, DataTableColumns
} from 'naive-ui'
import { dictDataApi } from '@/api/org'
import { assingWorkDetailApi,AssingWorkDetail } from '@/api/AssingWorkDetail'
import { SubmitLog } from '@/api/submitLog'
import SubmitLogInfoPage from "@/views/production/componets/SubmitLogInfoPage.vue";
import {QualityTesting} from "@/api/qualityTesting.ts";
import QualityInfoPage from "@/views/production/componets/QualityInfoPage.vue";


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

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

const qcAssingStatusOptions = 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 AssingWorkColumns :DataTableColumns<AssingWork> = [

  {
    type:"expand",
    expandable:()=>true,
    renderExpand:(row) => renderAssingWorkExpand(row)
  },

  {
    align:"center",
    title:"物料名称",
    key:"materialName",
    minWidth:150,
    render(row:any) {
      var opt = row.materialName
      if(opt) return opt
      return '-'
    }
  },
  {
    align:"center",
    title:"物料编码",
    key:"materialCode",
    minWidth:150,
    render(row:any) {
      var opt = row.materialCode
      if(opt) return opt
      return '-'
    }
  },
  {
    align:"center",
    title:"派工编号",
    key:"assingCode",
    minWidth:150
  },
  {
    align:'center',
    title: '工序名称',
    key: 'processName',
    minWidth: 200
  },
  {
    align:'center',
    title: '工序编号',
    key: 'processCode',
    minWidth: 200
  },
  {
    align:'center',
    title: '派工状态',
    key: 'assingStatus',
    minWidth: 150,
    render(row:any) {
      const val = row.assingStatus
      const opt = qcAssingStatusOptions.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: 'workshopName',
    minWidth: 200
  },
  {
    align:'center',
    title: '工段名称',
    key: 'sectionName',
    minWidth: 200
  },
  {
    align:'center',
    title: '工位名称',
    key: 'deviceName',
    minWidth: 200
  },
  {
    align:'center',
    title: '数量',
    minWidth: 100,
    key: 'quantity'
  },
  {
    align:'center',
    title: '是否返工',
    key: 'rework',
    minWidth: 100,
    render(row:any) {
      const quit = row.rework === 1
      return h(NTag, {type: quit ? 'error' : 'success', size: 'small'}, {default: () => (quit ? '是' : '否')})
    }
  },
  {
    align:'center',
    title: '返工次数',
    key: 'reworkNum',
    minWidth: 150
  },
  {
    align:'center',
    title: '完成数量',
    key: 'completedQuantity',
    minWidth: 150
  },
  {
    align:'center',
    title: '完成时间',
    key: 'completedTime',
    minWidth: 180
  },
  {
    align:'center',
    title: '是否质检打回',
    key: 'qualityReturn',
    minWidth: 120,
    render(row:any) {
      const quit = row.qualityReturn === 1
      return h(NTag, {type: quit ? 'error' : 'success', size: 'small'}, {default: () => (quit ? '是' : '否')})
    }
  },
  {
    align:'center',
    title: '质检打回数量',
    key: 'qualityReturnNum',
    minWidth: 150
  },
  {
    align:'center',
    title: '工序状态',
    key: 'status',
    minWidth: 100,
    render(row:any) {
      if(row.status == 0){
        return h(NTag, {
            type:'success',
            size: 'small'
          },
          {
            default: () => '启用'
          }
        )
      }
      if(row.status == 1){
        return h(NTag, {
            type:'warning',
            size: 'small'
          },
          {
            default: () => '已暂停'
          }
        )
      }
      if(row.status == 2){
        return h(NTag, {
            type:'warning',
            size: 'small'
          },
          {
            default: () => '已改派'
          }
        )
      }
      return '-'
    }
  },
  {
    align:'center',
    title: '暂停/改派时间',
    key: 'pauseTime',
    minWidth: 150
  },
  {
    align:'center',
    title: '暂停/改派原因',
    key: 'reason',
    minWidth: 150
  },
  {
    align:'center',
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
    render(row:any) {
      const buttons:any = []
      buttons.push(
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            ghost:true,
            onClick: () => {
              handleReportRecords(row)
            }
          },
          { default: () => '汇报信息' }
        )
      )
      buttons.push(
          h(
              NButton,
              {
                size: 'small',
                type: 'primary',
                ghost:true,
                onClick: () => {
                  handleQualityRecords(row)
                }
              },
              { default: () => '质检信息' }
          )
      )
      return buttons.length > 0 ? h(NSpace, {justify:'center'}, { default: () => buttons }) : '-'
    }
  }

]

const showQcReport = ref<boolean>(false)
const reportTitle = ref<string>()
const submitLogList = ref<SubmitLog[]>([])

const qualityList = ref<QualityTesting[]>([])

//懒加载子级
const loadingRowIds = ref<Set<number>>(new Set())

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:150
  },
  {
    align:"center",
    title:"来源",
    key:"source",
    width:150,
    render(row:any) {
      var opt = row.deviceName
      if(opt == 1) return '设备'
      if(opt == 2) return '终端'
      if(opt == 3) return '后台'
      return '-'
    }
  },
  {
    align:"center",
    title:"操作人",
    key:"userName",
    width:150
  },
  {
    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()
}

// //获取列表数据
function getlist() {
  try{
         mytasks({
            page:pagination.page,
            pageSize:pagination.pageSize,
            processName:processName.value
         }).then((rps:any) => {
                AssingWorkTableData.value = rps.records
                pagination.itemCount = rps.total
            })
  }catch(error) {
        console.log(error);

  }
}

const loadTableData = async(params:Record<string,any>) => {
   processName.value = params.processName
   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() {
    if(AssingWorkAllExpanded.value) {
        AssingWorkExpandedKeys.value = []
    }else{
        AssingWorkExpandedKeys.value = AssingWorkTableData.value.map(RowKey)
    }
}

// 缓存：key=派工id，value=明细数组
const expandDataMap = new Map<number, any[]>()



function renderAssingWorkExpand(row: AssingWork) {
  // 1. 首次展开，发起请求
  if (!expandDataMap.has(row.id)) {
    expandDataMap.set(row.id, [])
    loadingRowIds.value.add(row.id)

    // 异步请求，不阻塞当前渲染
    getAssingWorkDetail(row.id).then((detailList) => {
      expandDataMap.set(row.id, detailList)
      loadingRowIds.value.delete(row.id)
    })
  }

  // 2. 根据缓存状态渲染
  if (loadingRowIds.value.has(row.id)) {
    return h('div', { style: 'padding:12px' }, '加载中...')
  }

  const tableData = expandDataMap.get(row.id)!
  return h('div', { style: 'padding: 0 16px 12px' }, [
    h(NDataTable, {
      columns: AssingWorkDetailColums,
      data: tableData,
      rowKey: DetailRowKey,
      size: 'small',
      bordered: true,
      striped: true,
      scrollX: 1360
    })
  ])
}


async function getAssingWorkDetail(assingWorkId:number) {
    const res = await  assingWorkDetailApi.selectAssingWorkDetailListByAssingWorkId(assingWorkId)
    console.log(res);

    return res
  }


// 加载字典选项
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 {}

}

//汇报信息弹窗
function handleReportRecords(row:any) {
  showQcReport.value = true
  reportTitle.value = "汇报信息"
  submitLogList.value = row.submitLogList
  baseInfo.value = {...row}
  baseInfo.value.logOrQuality = "log"
}



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




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


defineExpose({
  loadTableData
})

</script>


<style scoped>
    .toolbar {
        margin-bottom: 12px;
    }
    .pgClass {
      font-weight: bold;
    }
</style>