<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.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="[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>

    <PlmModelDrawer ref="plmModelDrawerRef" />

   <!--暂停恢复弹框-->
    <n-modal
      v-model:show="pausemodal"
      title="报检"
      preset="card"
      style="width: 400px"
      :mask-closable="false"
    >

      <n-form
        ref="pauseformRef"
        :model="pauseform"
        :rules="pauserules"
        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="qcNum">
              <n-input v-model:value="pauseform.qcNum" placeholder="请输入报检数量" />
            </n-form-item>
      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="pausemodal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="pauseLoading" 
            @click="pauseSubmit"
            :disabled="pauseisedbtn"
          >保存</n-button>
        </n-space>
      </template>
    </n-modal>
 

  </div>
</template>

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


import { 
  NButton, 
  NIcon, 
  NSpace, 
  NPagination, 
  NGrid, 
  // NGi, 
  NTag,
  useMessage,
  //useDialog,
  //type FormInst, 
} from 'naive-ui'

import { 
  SearchOutline, 
  RefreshOutline
} from '@vicons/ionicons5'

import { useUserStore } from '@/stores/user'
import { dictDataApi } from '@/api/org'
import { 
  mytasks,
  inspectio 
} from '@/api/production'
import PlmModelDrawer from '@/components/PlmModelDrawer.vue'
import type { PlmModelOpenContext } from '@/api/plmModel'

//const dialog = useDialog()

const message = useMessage()

const userStore = useUserStore()

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


//派工状态字典
const qcAssingStatusOptions = ref<{ label: string; value: any;class:any }[]>([])

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



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

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

const plmModelDrawerRef = ref<InstanceType<typeof PlmModelDrawer> | null>(null)

function openPlmModel(row: Record<string, unknown>) {
  console.log(row);
  
  const ctx: PlmModelOpenContext = {
    orderItemId: row.orderItemId as string | number,
    dispatchId: row.id as number | string,
    materialCode: row.materialCode as string | undefined,
    materialName: row.materialName as string | undefined,
    drawingNo: (row.drawingNo as string | undefined) || (row.materialCode as string | undefined),
    title: `三维模型 · ${row.processName || row.materialName || ''}`,
  }
  plmModelDrawerRef.value?.open(ctx)
}

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: '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: '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: '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
  },
  { 
    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: 'actions',
    width: 100,
    fixed: 'right',
    render(row:any) {
      const buttons:any = []
    
          if(hasPermission('biz:assingWork:edit')){
              buttons.push(h(NButton, { 
              size: 'small',
              type:'primary',  
              ghost:true,
              onClick: () => { handlpause(row) } }, 
              { default:  () =>  '报检'}
            ))
          }
          buttons.push(h(NButton, {
            size: 'small',
            type: 'info',
            ghost: true,
            onClick: () => openPlmModel(row),
          }, { default: () => '模型' }))

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





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

//重置
function reset() {
  searchForm.processId =''
  searchForm.processName = ''
}

//获取列表数据
function getlist() {
  mytasks(searchForm).then((rps:any) => {
    datalist.value = rps.records
    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 gxobg = reactive<any>({})

//报检
let pausemodal = ref(false) 
let pauseform = reactive<any>({
  id:'',
  qcNum:''
})  
const pauseformRef = ref() 

const pauserules = {
   qcNum: [
    { required: true, message: '请输报检数量', trigger: 'blur' },
    {
      validator(rule:any,value: any) {
        if(value > pauseform.qcNum){
          return new Error(`报检数量最大为${pauseform.qcNum}`)
        }
        return true
      },
      trigger: ['blur']
    }
  ]
}

watch(()=>pauseform.qcNum,v => {
  pauseform.qcNum = v.replace(/[^\d]/g,'')
})

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

function handlpause(n:any) {
  gxobg.id = n.id
  gxobg.name = n.name

  pausemodal.value = true
  pauseLoading.value = false
  pauseisedbtn.value = false
  pauseformRef.value?.restoreValidation()
  pauseform.id = n.id
  pauseform.qcNum = `${n.quantity}`
 
}

function pauseSubmit() {
  pauseformRef.value?.validate((v:any) => {
    if(!v){
      pauseLoading.value = true
      pauseisedbtn.value = true
      inspectio(Object.assign({},pauseform,{qcNum:pauseform.qcNum*1})).then(() => {
        message.success('操作成功!')
        setTimeout(()=> {
          pausemodal.value = false
          pauseLoading.value = false
          pauseisedbtn.value = false
          getlist()
        },1000)
      }).catch(() => {
        pauseLoading.value = false
        pauseisedbtn.value = 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 {}
}

// function zantqy(row:any) {
//   dialog.warning({
//     title: '温馨提示', 
//     content: `确定要暂停"${row.processName}"吗？`, 
//     positiveText: '确定', 
//     negativeText: '取消',
//     onPositiveClick: () => {
//       pauseresume({}).then(() => {
//         message.success('操作成功!')
//         getlist()
//       })
//     }
//   })
// }
onMounted(() => {
 

 getlist()
 loadDictOptions()

})
</script>

<style scoped>

</style>
