<template>
  <div class="page-container">
    <!-- 用户列表 -->
    <n-card class="user-list-card" size="small">
      <!-- 搜索表单 -->
      <div class="search-form">
        <n-form 
          inline 
          :model="searchForm" 
          label-placement="left"
        >

          <n-form-item label="图纸编号">
            <n-input v-model:value="searchForm.ncCode" placeholder="请输入图纸编号" />
          </n-form-item>
          <n-form-item label="图纸名称">
            <n-input v-model:value="searchForm.ncName" placeholder="请输入图纸名称" />
          </n-form-item>
          <n-form-item label="工序编码">
            <n-input v-model:value="searchForm.ncName" placeholder="请输入工序编码" />
          </n-form-item>

      
          <n-space> 
            <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>
      </div>

      <n-space style="margin-bottom: 15px;">
          <n-button type="primary" @click="addhand(1)" size="small">
            <template #icon>
              <n-icon>
                <AddOutline />
              </n-icon>
            </template>
            新增
          </n-button>
          <!-- <n-button type="error" @click="delhand" size="small">
            <template #icon>
              <n-icon>
                <ArrowDownCircleOutline />
              </n-icon>
            </template>
            删除
          </n-button> -->
          <n-button type="success" @click="issuehand" size="small">
            <template #icon>
              <n-icon>
                <ArrowDownCircleOutline />
              </n-icon>
            </template>
            导出
          </n-button>
        </n-space>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        size="small"
        striped
        :data="datalist" 
        :bordere="false"
        :single-line="false"
        :loading="loading"
        remote
        :row-key="rowKey"
        @update:checked-row-keys="handleCheck"
      />

      <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="addModel"
      :title="isstype.value == 1?'新增':'修改'"
      preset="card"
      style="width: 500px"
      :mask-closable="false"
    >
    
    <n-form
      ref="addformRef"
      :model="formData"
      :rules="addrules"
      label-placement="left"
      label-width="80"
    >
     <n-grid :cols="1" :x-gap="24">
      <n-gi>

        <n-form-item path="drawingCode" label="图纸编号">
          <n-input v-model:value="formData.drawingCode" placeholder="请输入图纸编号" />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item path="drawingName" label="图纸名称">
          <n-input v-model:value="formData.drawingName" placeholder="请输入图纸名称" />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="图纸版本">
          <n-input v-model:value="formData.drawingVersion" placeholder="请输入图纸版本" />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="工序名称">
          <n-input v-model:value="formData.processName" placeholder="请选择工序" />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="PLM文档">
          <n-input v-model:value="formData.plmDocId" placeholder="请选择PLM文档" />
        </n-form-item>
      </n-gi>
      <n-gi>
        <n-form-item label="状态">
          <n-radio-group v-model:value="formData.status" :default-value="1" name="radiogroup">
            <n-space>
              <n-radio :value="1">
                启用
              </n-radio>
              <n-radio :value="0">
                禁用
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>    
      </n-gi>
      <n-gi>
        <n-form-item path="gxname" label="上传图纸">
            <!--:default-file-list="fileList"-->
            <n-upload
              action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
              list-type="image-card"
            >
              点击上传
            </n-upload>
          </n-form-item>
      </n-gi>
      
      <n-gi>
        <n-form-item path="gxname" label="备注">
          <n-input type="textarea" v-model:value="formData.remark" placeholder="请输入备注" />
        </n-form-item>
      </n-gi>
    </n-grid>
    </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="addModel = false">取消</n-button>
          <n-button 
            type="primary" 
          
            @click="savehand"
          >确认</n-button>
        </n-space>

      </template>
  </n-modal>

    <!--下发-->
    <n-modal
      v-model:show="issueModel"
      title="下发"
      preset="card"
      style="width: 500px"
      :mask-closable="false"
    >
    
    <n-form
      ref="issformRef"
      :model="issformData"
      :rules="issaddrules"
      label-placement="top"
      label-width="100"
    >
      <n-grid :cols="1" :x-gap="24">
        <n-gi>
          <n-form-item path="taskid" label="下发任务">
            <n-select
              :disabled="false"
              :render-label="renderlabe"
              v-model:value="issformData.taskid"
              placeholder="请选择下发任务"
              :options="isstasklist"
            />
          </n-form-item>
          <n-form-item path="equis" label="下发设备">
            <n-select
              :disabled="false"
              :render-label="renderlabe"
              v-model:value="issformData.equis"
              placeholder="请选择下发设备"
              :options="issequiplist"
            />
          </n-form-item>
        </n-gi>
        <!-- <n-gi>
          <n-form-item path="ncName" label="下发代码">
            <n-input v-model:value="formData.ncName" placeholder="请输入NC代码名称" />
          </n-form-item>
        </n-gi>       -->
      </n-grid>
    </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button @click="issueModel = false">取消</n-button>
          <n-button 
            type="primary" 
          
            @click="isssavehand"
          >确认</n-button>
        </n-space>

      </template>
  </n-modal>
</div>

  
</template>

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


import { 
  NButton, 
  NIcon, 
  NSpace, 
  NImage,
  NPagination, 
  NGrid,
  useMessage,
  useDialog,
} from 'naive-ui'

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

import { useUserStore } from '@/stores/user'
//import { dictDataApi } from '@/api/org'
import {
  addDrawing, 
  editDrawing, 
  drawinglist,
  deleteDrawing
} from '@/api/illustrated'




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,
  ncCode:'',
  ncName:'',
  status:1
})



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

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


const columns = [
  {
      align:"center",
      title:"图纸编号",
      key:"materialName",
      minWidth:150
    },
    {
      align:"center",
      title:"图纸名称",
      key:"materialCode",
      minWidth:150
    },
    {
      align:"center",
      title:"图纸版本",
      key:"assingCode",
      minWidth:150
    },
    {
      align:"center",
      title:"工序名称",
      key:"materialCode",
      minWidth:150
    },
    {
      align:"center",
      title:"工序编码",
      key:"assingCode",
      minWidth:150
    },
    {
      align:"center",
      title:"图纸缩略图",
      key:"materialCode",
      minWidth:150,
      render(row:any) {
        return h(NImage, {width:'50',height:'50',src:'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'})
      }
    },
    {
      align:"center",
      title:"PLM文档",
      key:"assingCode",
      minWidth:150
    },
  {
    align:"center",
    title:"状态",
    key:"status",
    minWidth:150,
    render(row:any) {
      if(row.status == 1){
        return '启用'
      }
      return '禁用'
    }
  },
  {
    align:"center",
    title:"是否下发",
    key:"isIssued",
    minWidth:150,
    render(row:any) {
      if(row.status == 1){
        return '已下发'
      }
      return '未下发'
    }
  },
  {
    align:"center",
    title:"下发时间",
    key:"issueTime",
    minWidth:150
  },

  {
    align:"center",
    title:"下发人",
    key:"issueBy",
    minWidth:150
  },
  {
    align:"center",
    title:"备注",
    key:"remark",
    minWidth:150
  },

  {
    align:'center',
    title: '操作',
    key: 'actions',
    width: 220,
    fixed: 'right',
    render(row:any) {
      const buttons:any = []
          
          if(hasPermission('biz:ncCode:issue')){
              buttons.push(h(NButton, { 
              size: 'small',
              type:'info',  
              ghost:true,
              onClick: () => { 
                issuehand()
               } }, 
              { default:  () =>  '下发'}
            ))
          }
          // if(hasPermission('biz:nccode:add')){
          //     buttons.push(h(NButton, { 
          //     size: 'small',
          //     type:'warning',  
          //     ghost:true,
          //     onClick: () => { 
          //       addhand(3,row)
          //      }}, 
          //     { default:  () =>  '复制'}
          //   ))
          // }

          if(hasPermission('biz:ncCode:edit')){
              buttons.push(h(NButton, { 
              size: 'small',
              type:'primary',  
              ghost:true,
              onClick: () => { 
                addhand(2,row)
               } }, 
              { default:  () =>  '编辑'}
            ))
          }
          if(hasPermission('biz:ncCode:remove')){
              buttons.push(h(NButton, { 
              size: 'small',
              type:'error',  
              ghost:true,
              onClick: () => {
                dialog.warning({
                  title: '警告',
                  content: `你确定删除NC代码编号为:${row.ncCode}的数据`,
                  positiveText: '确定',
                  negativeText: '取消',
                  //draggable: true,
                  onPositiveClick: () => {
                    deleteDrawing(row.id).then(() => {
                      message.success('操作成功')
                    })
                    
                  },
                  onNegativeClick: () => {
                    
                  }
                })
                
               } }, 
              { 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() {
 
}

//获取列表数据
function getlist() {
  drawinglist(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()
}



// // 加载字典选项
// async function loadDictOptions() {
//   //qcCancelLoading = true
//   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 {}
// }


//新增
let addModel = ref(false)

const addformRef = ref()

let formData = reactive<any>({
  id:'',
  drawingCode:'',	          //图纸编号
  drawingName:'',	          //图纸名称
  drawingVersion:'',	      //图纸版本
  processRouteStepId:'',	  //关联工序ID
  processCode:'',	          //工序编码
  processName:'',	          //工序名称
  filePath:'',	            //文件路径
  fileName:'',	            //文件名
  fileSize:'',              //文件大小
  fileType:'',	            //文件类型
  plmDocId:'',	            //PLM文档ID
  plmVersion:'',	          //PLM版本号
  plmStatus:'',	            //PLM状态
  status:1,	                //状态：1-启用 0-禁用
  remark:''	                //备注
}) 
const addrules = {
   drawingCode: [
    { required: true, message: '请输入图纸编号', trigger: 'blur' },
    // {
    //   validator(rule:any,value: any) {
    //     if(value > pauseform.qcNum){
    //       return new Error(`报检数量最大为${pauseform.qcNum}`)
    //     }
    //     return true
    //   },
    //   trigger: ['blur']
    // }
  ],
  drawingName:[
    { required: true, message: '请输入图纸名称', trigger: 'blur' }
  ],
  ncContent:[
    { required: true, message: '请输入NC代码内容', trigger: 'blur' }
  ]
}

let isstype = ref<any>(1)

const cztype = reactive<any>({
  1:'新增',
  2:'编辑'
})

function addhand(type:any,row?:any) {
  addModel.value = true
  formData.value?.restoreValidation()
  isstype.value = type
  if(row){
    formData.id = row.id
    formData.drawingCode = row.drawingCode
    formData.drawingName = row.drawingName	          
    formData.drawingVersion	= row.drawingVersion      
    formData.processRouteStepId = row.processRouteStepId	  
    formData.processCode = row.processCode	          
    formData.processName = row.processName	          
    formData.filePath = row.filePath	            
    formData.fileName = row.fileName	            
    formData.fileSize = row.fileSize             
    formData.fileType = row.fileType	            
    formData.plmDocId = row.plmDocId	            
    formData.plmVersion = row.plmVersion	          
    formData.plmStatus = row.plmStatus	           
    formData.status = row.status	               
    formData.remark = row.remark	               
  }else{
    formData.id = ''
    formData.drawingCode = ''
    formData.drawingName = ''	          
    formData.drawingVersion	= ''      
    formData.processRouteStepId = ''	  
    formData.processCode = ''	          
    formData.processName = ''	          
    formData.filePath = ''	            
    formData.fileName = ''	            
    formData.fileSize = ''             
    formData.fileType = ''	            
    formData.plmDocId = ''	            
    formData.plmVersion = ''	          
    formData.plmStatus = ''	           
    formData.status = ''	               
    formData.remark = ''
  }
}

function addEdi(){
  if(isstype.value == 1){
    return addDrawing(formData)
  }
  return  editDrawing(formData)
}

function savehand() {
  addformRef.value?.validate((e:any) => {
    if (!e) {
      addEdi().then(() => {
        message.success(isstype.value == 1?'新增':'修改')
        setTimeout(() => {
          getlist()
          addModel.value = false
        },1500)
      })
    }
  })
}

//表格选中

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

let chearr = ref<any>([])
function handleCheck(v:any) {
  chearr.value = v
  console.log(v)
}

//删除
// function delhand() {
//   if(chearr.value.length > 0){
//     drawingIssue(chearr.value).then(() => {
//       message.success('操作成功')
//     })
//   }else{
//     message.error('请勾选设备')
//   }
  
// }

//下发任务列表
let isstasklist = ref<any>([])

//下发设备列表
let issequiplist = ref<any>([])

//下发
let issueModel = ref(false)
let issformData = reactive<any>({
  taskid:'',
  equis:''
}) 
const issaddrules = {
  taskid:[
    { required: true, message: '请选择下发任务', trigger: 'blur' }
  ],
  equis:[
    { required: true, message: '请选择下发设备', trigger: 'blur' }
  ]
  
}  


function renderlabe() {}
function issuehand() {
  issueModel.value = true
  // if(chearr.value.length > 0){
  //   batchIssue(chearr.value).then(() => {
  //     message.success('操作成功')
  //   })
  // }else{
  //   message.error('请勾选设备')
  // }
  
}

const issformRef = ref()

function isssavehand() {
  issformRef.value?.validate((e:any) => {
    if (!e) {
      message.success('操作成功')
      setTimeout(() => {
        getlist()
        issueModel.value = false
      },1500)
    }
  })
}

getlist()

onMounted(() => {
 
 //loadDictOptions()

})
</script>

<style scoped>

</style>
