<template>
  <div class="page-container">
    <!-- 用户列表 -->
    <n-card class="user-list-card" size="small">
      <!-- 搜索表单 -->
      <div class="search-form">
        <n-form  
          :model="searchForm" 
          label-placement="left"
        >
        <n-grid :cols="24" :x-gap="24">
          <!-- <n-form-item-gi :span="6" label="工序编码">
            <n-input v-model:value="searchForm.processId" placeholder="请输入工序编号" clearable />
          </n-form-item-gi> -->
          <n-form-item-gi :span="6" label="工序名称">
            <n-input v-model:value="searchForm.processName" placeholder="请输入工序名称" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="工人名称">
            <n-input v-model:value="searchForm.userName" placeholder="请输入工人名称" clearable />
          </n-form-item-gi>
          <!-- <n-form-item-gi :span="6" label="数里">
            <n-input v-model:value="searchForm.processId" placeholder="请输入数里" clearable />
          </n-form-item-gi> -->
          <!-- <n-form-item-gi :span="6" label="是否返工">
            <n-input v-model:value="searchForm.processId" placeholder="请选择" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="返工次数">
            <n-input v-model:value="searchForm.processId" placeholder="请输入返工次数" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="完成数里">
            <n-input v-model:value="searchForm.processId" placeholder="请输入完成数里" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="完成时间">
            <n-input v-model:value="searchForm.processId" placeholder="请选择完成时间" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="创建时间">
            <n-input v-model:value="searchForm.processId" placeholder="请选择创建时间" clearable />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="创建人">
            <n-input v-model:value="searchForm.processId" placeholder="请输入创建人" clearable />
          </n-form-item-gi> -->
          <n-form-item-gi :span="6">
            <n-space> 
              <n-button type="primary" @click="search">
                <template #icon><n-icon><SearchOutline /></n-icon></template>
                搜索
              </n-button>
              <!-- <n-button type="primary" @click="search">
                <template #icon><n-icon><SearchOutline /></n-icon></template>
                我的派工
              </n-button> -->
              <n-button @click="reset"> 
                <template #icon><n-icon><RefreshOutline /></n-icon></template>
                重置
              </n-button>
            </n-space>
          </n-form-item-gi>
        </n-grid>
          
          
          <!-- <n-form-item label="用户类型">
            <n-select
              v-model:value="searchForm.userType"
              placeholder="请选择用户类型"
              :options="userTypeOptions"
              clearable
              style="width: 140px"
            />
          </n-form-item> -->
          <!-- <n-form-item label="状态">
            <n-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              :options="statusOptions"
              clearable
              style="width: 120px"
            />
          </n-form-item> -->
          
        </n-form>
      </div>

      

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        size="small"
        striped
        :data="datalist" 
        :bordere="false"
        :single-line="false"
        :loading="loading"
        remote
      />

      <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-card>

    <!-- 新增/编辑弹窗 -->
    <n-modal
      v-model:show="editmodal"
      title="编辑派工单"
      preset="card"
      style="width: 800px"
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        label-width="80"
        class="modal-form"
      >
        <n-grid :cols="2">
          <!-- <n-gi>
            <n-form-item label="工序编号" path="processName">
              <n-input v-model:value="formData.processName" placeholder="请输入用户名" :disabled="!!formData.id" />
            </n-form-item>
          </n-gi> -->
          <n-gi>
            <n-form-item label="工序名称" path="processName">
              <n-input v-model:value="formData.processName" placeholder="请输入工序名称"  />
            </n-form-item>
          </n-gi>
          <n-gi>
            <n-form-item label="改派工人" path="">
              <n-select
                 v-model:value="reassform.userId"
                placeholder="请指定改派的员工"
                clearable
                style="width: 200px"
                :options="reassignEmployees"
           />
           </n-form-item>
          </n-gi>
          <n-gi>
            <n-form-item label="数量" path="quantity">
              <n-input v-model:value="formData.quantity" placeholder="请输入数量" />
            </n-form-item>
          </n-gi>
          <n-gi>
            <n-form-item label="是否返工" path="rework">
              <n-input v-model:value="formData.rework" placeholder="请输入" />
            </n-form-item>
          </n-gi>
          <!-- <n-gi>
            <n-form-item label="返工次数" path="username">
              <n-input v-model:value="formData.username" placeholder="请输入用户名" :disabled="!!formData.id" />
            </n-form-item>
          </n-gi> -->
          <n-gi>
            <n-form-item label="完成数量" path="completedQuantity">
              <n-input v-model:value="formData.completedQuantity" placeholder="请输入用户名" :disabled="!!formData.id" />
            </n-form-item>
          </n-gi>
          
        </n-grid>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="editmodal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="submitLoading" 
            @click="handleSubmit"
            :disabled="disedbtn"
          >保存</n-button>
        </n-space>
      </template>
    </n-modal>
  
    <!--改派弹框-->
    <n-modal
      v-model:show="reassignmodal"
      title="改派"
      preset="card"
      style="width: 400px"
      :mask-closable="false"
    >
      <n-form
        ref="reassformRef"
        :model="reassform"
        :rules="reassrules"
        label-placement="top"
        label-width="80"
      >
          <n-form-item label="工序编号">
            <n-input v-model:value="gxobg.id" disabled  />
          </n-form-item>
          <n-form-item label="工序名称">
            <n-input v-model:value="gxobg.name" disabled  />
          </n-form-item>

          <n-form-item label="改派工人" path="">
              <n-select
                 v-model:value="reassform.userId"
                placeholder="请指定改派的员工"
                clearable
                style="width: 200px"
                :options="reassignEmployees"
           />
          
            </n-form-item>
          <n-form-item label="改派原因" path="reason">
              <n-input type="textarea" v-model:value="reassform.reason" placeholder="请输入改派原因" />
            </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="reassignmodal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="reassLoading"
            @click="reassSubmit"
            :disabled="reassdisedbtn"
          >确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <!--暂停恢复弹框-->
    <n-modal
      v-model:show="pausemodal"
      title="暂停/恢复"
      preset="card"
      style="width: 400px"
      :mask-closable="false"
    >
      <n-form
        ref="pauseformRef"
        :model="pauseform"
        label-placement="top"
        label-width="80"
      >
          <n-form-item label="工序编号">
            <n-input v-model:value="gxobg.id" disabled  />
          </n-form-item>
          <n-form-item label="工序名称">
            <n-input v-model:value="gxobg.name" disabled  />
          </n-form-item>
          <n-form-item label="暂停原因" path="reason">
              <n-input type="textarea" v-model:value="pauseform.reason" placeholder="请输入暂停原因" />
            </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="pausemodal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="submitLoading" 
            @click="pauseSubmit"
            :disabled="disedbtn"
          >确定</n-button>
        </n-space>
      </template>
    </n-modal>


    <!--查询汇报详情-->

    <n-modal v-model:show="reportDetailVisible" preset="card" :title="reportDetailTitle" style="width: 1000px">
        <n-card hoverable style="margin-bottom: 12px" >
          <template #header>
          <div style="display:flex;justify-content:space-between;align-items:center;width:100%">
            <span>主表信息</span>
            <n-button text @click="infoIsCollapse = !infoIsCollapse">
              <n-icon :component="infoIsCollapse ? ArrowDownOutline : ArrowUpOutline" />
            </n-button>
          </div>
        </template>
        <n-descriptions :column="3" bordered v-show="!infoIsCollapse">
         <n-descriptions-item
              v-for="item in mappedInfoList"
              :key="item.key"
              :label="item.label"
          >
            {{ formatDisplayValue(item.key, item.value) }}
          </n-descriptions-item>
        </n-descriptions>
        </n-card>
        <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,
  render, 
} from 'vue'


import { 
  NButton, 
  NDropdown,
  NIcon, 
  NSpace, 
  NPagination, 
  NGrid, 
  NGi, 
  NTag,
  useMessage,
  //useDialog,
  type FormInst, 
} from 'naive-ui'
import {
  SearchOutline, RefreshOutline, AddOutline, TrashOutline, CreateOutline, CloudUploadOutline, DownloadOutline,
  EllipsisHorizontalOutline, ArrowDownOutline, ArrowUpOutline
} from '@vicons/ionicons5'
import { useUserStore } from '@/stores/user'
import { dictDataApi } from '@/api/org'
import { 
  disworlist,
  editdiswor, 
  transfer, 
  pauseresume,
  //workload 
} from '@/api/production'

import { submitLogApi } from '@/api/submitLog'

import { SysUser, userApi } from '@/api/system'

//const dialog = useDialog()

const message = useMessage()

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission: string) => userStore.hasPermission(permission)

//判定状态字典
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 qcAssingStatusOptions = ref<{ label: string; value: any;class:any  }[]>([])

//汇报详情
const infoIsCollapse = ref(false)

const reportDetailVisible = ref(false)
const reportDetailTitle = ref<string>('')

const mappedInfoList = ref<Array<{ label: string; key: string; value: any }>>([])
const qualityTestings = ref<any[]>([])

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 })
    }
   }
])

//改派员工列
const reassignEmployees = ref<Array<{value: number, username: string}>>([])



// ==================== 搜索表单 ====================
const searchForm = reactive({
  page: 1,
  pageSize: 20,
  processId:null ,
  processName:null,
  userName:null
})



// ==================== 表格 ====================
const datalist = ref<any>([])
const loading = ref(false)

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


const columns = [
  // { 
  //   type: 'selection',
  //   minWidth:60
  // },

  {
    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:"traceType",
    render(row:any) {
      const val = row.traceType
      if(val == 1) return '-'
      if(val == 2) return '追溯码'
      if(val == 3) return '批次码' 
    },
    minWidth:80
  },
  // {
  //   align:'center',
  //   title:"追溯码/批次号",
  //   key:"traceCode",
  //   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 })

    }
    
  },
  { 
    align:'center',
    title: '车间名称',
    key: 'workshopName', 
    minWidth: 200 
  },
  { 
    align:'center',
    title: '工段名称',
    key: 'sectionName', 
    minWidth: 200 
  },
  { 
    align:'center',
    title: '工位名称',
    key: 'deviceName', 
    minWidth: 200 
  },
  { 
    align:'center',
    title: '工人名称',
    key: 'userName', 
    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:"isQual",
    minWidth:100,
    render(row:any) {
      const qual = row.isQual === 1
      return h(NTag, {type: qual ? 'error' : 'success', size: 'small'}, {default: () => (qual ? '是' : '否')})
    }
  },
  {
    align:'center',
    title:"是否直接入库",
    key:"isStorage",
    minWidth:120,
    render(row:any) {
      const storage = row.isQual === 1
      return h(NTag, {type: storage ? 'error' : 'success', size: 'small'}, {default: () => (storage ? '是' : '否')})
    }
  },
  { 
    align:'center',
    title: '完成数量', 
    key: 'completedQuantity', 
    minWidth: 150
  },
  { 
    align:'center',
    title: '完成时间', 
    key: 'completedTime', 
    minWidth: 180
  },
  { 
    align:'center',
    title: '创建人', 
    key: 'createBy', 
    minWidth: 150
  },
  { 
    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,
    render(row:any) {
      var count = row.qualityReturnNum
      if(count>0) return count
      return 0
    }
  },
  { 
    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:'error', 
            size: 'small'
          }, 
          {
            default: () => '已改派'
          }
        )
      }
      return '-'
    }
  },
  { 
    align:'center',
    title: '暂停/改派时间', 
    key: 'pauseTime', 
    minWidth: 180
  },
  { 
    align:'center',
    title: '暂停/改派原因', 
    key: 'reason', 
    minWidth: 150
  },
  {
    align:'center',
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
    render(row:any) {
      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(NDropdown, {
            trigger:'click',
            options:[
              {label:"改派",key:'transfer'},
              {type: 'divider' }, // 分割线
              {label: '启用/暂停',key:'pauseResume'},
              {type: 'divider' }, // 分割线
              {label:'查看汇报',key:'view'},
            ],
            onSelect:(key:string)=>{
              switch(key) {
                case "transfer":
                  handlreass(row)
                  break
                case "pauseResume":
                  handlpause(row)
                  break 
                case "view":
                  handleViewReport(row.id)
                  break   
              
              }
            }
         },{
          // 下拉触发按钮：三点图标 / 更多文字
          default: () => h(NButton, { size: 'small', quaternary: true }, {
            default: () => [h(NIcon, null, { default: () => h(EllipsisHorizontalOutline) })]
          })
        })
      ])


      // const buttons:any = [
      // ]
    
      //     if(hasPermission('biz:assingWork:edit')){
      //         buttons.push(h(NButton, { 
      //         size: 'small',
      //         type:'primary',  
      //         ghost:true,
      //         onClick: () => { handleEdit(row) } }, 
      //         //{ default:  () => [h(NIcon, null, { default: () => h(CreateOutline) }), ' 编辑' ]}
      //         { default:  () =>  '编辑'}
      //       ))
      //     }
      //     if(hasPermission('biz:assingWork:transfer')){
      //       buttons.push(h(NButton, { 
      //         size: 'small',
      //         type:'success',
      //         ghost:true,
      //         onClick: () => { handlreass(row) } }, 
      //         { default:  () =>  '改派'}
      //       ))
      //     }
      //     if(hasPermission('biz:assingWork:pauseResume')){
      //       buttons.push(h(NButton, { 
      //         size: 'small',
      //         type:'warning',
      //         ghost:true,
      //         onClick:()=>{ handlpause(row) }
      //       }, 
      //         { default:  () =>  '暂停'}
      //       )) 
      //     }
      // buttons.push(
          
      //   )

      // return buttons.length > 0 ? h(NSpace, {justify:'center'}, { default: () => buttons }) : '-'
    }
  }
]

// 编辑
const editmodal = ref(false)
const formRef = ref<FormInst | null>(null)
const submitLoading = ref(false)

const formData = reactive<any>({
  id:'',
  processName:'',             //工序名称
  userId:'',                  //工人id
  stringUserName:'',          //工人名称
  quantity:'',                //数里
  rework:'',                  //是否返工
  reworkNum:'',               //返工次数
  completedQuantity:'',       //完成数里
})

const rules = {
  processName: [{ required: true, message: '请输工序名称', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
}

//搜索数据
function search() {
  pagination.page = 1
  searchForm.page = 1
  searchForm.pageSize = 20
  getlist()
}

//重置
function reset() {
  searchForm.processId =null
  searchForm.processName = null
  searchForm.userName = null

  
}

//获取列表数据
function getlist() {
  disworlist(searchForm).then((rps:any) => {
    datalist.value = rps.list
    pagination.itemCount = rps.total
  })
}



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

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


//编辑工单
let disedbtn = ref(false)
function handleEdit(n:any) {
  editmodal.value = true
  submitLoading.value = false
  disedbtn.value = false
  formRef.value?.restoreValidation()
  formData.id = n.id
  formData.processName = n.processName             
  // formData.userId = ''                  //工人id
  // formData.stringUserName = ''          //工人名称
  // formData.quantity = ''                //数里
  // formData.rework = ''                  //是否返工
  // formData.reworkNum = ''               //返工次数
  // formData.completedQuantity = ''       //完成数里
}

function handleSubmit() {
  formRef.value?.validate(v => {
    if(!v){
      submitLoading.value = true
      disedbtn.value = true
      editdiswor(formData).then(() => {
        message.success('保存成功!')
        setTimeout(()=> {
          editmodal.value = false
          submitLoading.value = false
          disedbtn.value = false
          getlist()
        },1000)
      }).catch(() => {
        disedbtn.value = false
        submitLoading.value = false
      })
    }
  })
}

let gxobg = reactive<any>({})

//改派
let reassignmodal = ref(false)

const reassformRef = ref()

let reassform = reactive<any>({
  // userId:'',                  //工人id
  // stringUserName:'',          //工人名称

  id:null,     //派工id
  reason:null, //改派原因 
  userId:null  //改派人Id
})
 const reassrules = {
  userid: [{ required: true, message: '请选择员工', trigger: 'blur' }]
 }
let reassLoading = ref(false)
let reassdisedbtn = ref(false)

function handlreass(n:any) {

  gxobg.name = n.processName
  gxobg.id = n.processId

  reassignmodal.value = true
  reassLoading.value = false
  reassdisedbtn.value = false
  reassformRef.value?.restoreValidation()
  reassform.id = n.id
  reassform.reason = ''
  reassform.userid = 456
 
}

 function reassSubmit() {
  reassformRef.value?.validate((v:any) => {
    if(!v){
      reassLoading.value = true
      reassdisedbtn.value = true
      transfer(reassform).then(() => {
        message.success('操作成功!')
        setTimeout(()=> {
          reassignmodal.value = false
          reassLoading.value = false
          reassdisedbtn.value = false
          getlist()
        },1000)
      }).catch(() => {
        reassdisedbtn.value = false
        reassLoading.value = false
      })
    }
  })
}


//暂停/启用

let pausemodal = ref(false) 
let pauseform = reactive<any>({
  id:'',
  status:'',  //0启用1暂停2改派
  reason:''   //原因
})  
const pauseformRef = ref() 

 let pauseLoading = ref(false)
 let pauseisedbtn = ref(false)

function handlpause(n:any) {

  gxobg.name = n.processName
  gxobg.id = n.processId

  pausemodal.value = true
  pauseLoading.value = false
  pauseisedbtn.value = false
  pauseformRef.value?.restoreValidation()
  pauseform.id = n.id
  pauseform.reason = ''
  pauseform.status = n.status === '0'?'1':'0'  
}

function pauseSubmit() {
  pauseformRef.value?.validate((v:any) => {
    if(!v){
      pauseLoading.value = true
      pauseisedbtn.value = true
      pauseresume(pauseform).then(() => {
        message.success('操作成功!')
        pausemodal.value = false
        pauseLoading.value = false
        pauseisedbtn.value = false
        getlist()
      }).catch(() => {
        pauseLoading.value = false
        pauseisedbtn.value = false
      })
    }
  })
}

async function handleViewReport(id:number) {
  reportDetailTitle.value='汇报详情'
  reportDetailVisible.value = true

  const res = await submitLogApi.getByDispatch(id);
  
  mappedInfoList.value = [
    {key:"materialCode",label:"物料编码",value:res.materialCode},
    {key:"materialName",label:"物料名称",value:res.materialName},
    {key:"materialQty",label:"物料数量",value:res.materialQty},
    {key:"processCode",label:"工序编号",value:res.processCode},
    {key:"processName",label:"工序名称",value:res.processName},
    {key:"processQty",label:"生产总数",value:res.processQty},
    {key:"assingCode",label:"派工编号",value:res.assingCode},
    {key:"workerName",label:"派工人",value:res.workerName},
    {key:"assingQty",label:"派工数量",value:res.assingQty}
  ]
  qualityTestings.value = res.qualityTestings
  
  
}


function formatDisplayValue(key: string, value: any): string {
  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') : '-'
    case 'inspectTime':
    case 'createTime':
    case 'updateTime':
      return value ? new Date(value).toLocaleString('zh-CN') : '-'
    default:
      return String(value)
  }
}



// 加载字典选项
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('assing_status')
    qcAssingStatusOptions.value = data.map(d => ({ label: d.dictLabel, value: (Number(d.dictValue) || d.dictValue),class:d.listClass }))
  }catch {}
}


//获取员工列
async function getUserList() {
  const res =  await userApi.getPathList();

  reassignEmployees.value = res.map((user:SysUser)=>(
      {
      label: user.username,
      value: user.id
    }
  ))
}

onMounted(() => {
 
 getlist()
 getUserList()
 loadDictOptions()
 //workload() 

})
</script>

<style scoped>

</style>
