<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.drawingCode" placeholder="请输入图文编号" />
          </n-form-item>
          <!-- <n-form-item label="图文名称">
            <n-input v-model:value="searchForm.drawingName" placeholder="请输入图文名称" />
          </n-form-item>
          <n-form-item label="图文版本">
            <n-input v-model:value="searchForm.drawingVersion" 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 v-if="hasPermission('biz:drawingFile:add')" 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" v-if="hasPermission('biz:drawingFile:export')" @click="handleExport" 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 v-if="pagination.itemCount > pagination.pageSize" 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" disabled placeholder="自动生成" />
        </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="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 path="processId" label="工序名称">
          <n-select
            v-model:value="selval"
            filterable
            placeholder="请输入工序名称搜索"
            :options="yglist"
            :loading="loadingRef"
            clearable
            remote
            :clear-filter-after-select="false"
            @search="slehand"
            @update:value="updatesle"
          />
        </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.drawingType" :default-value="1" name="radiogroup">
            <n-space>
              <n-radio :value="0">
                图纸
              </n-radio>
              <n-radio :value="1">
                文件
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>    
      </n-gi>
      
      <n-gi>
        <n-form-item path="fileId" label="上传文件">
            <!--:default-file-list="fileList"-->
            <!-- <n-upload
              :action="URL"
              :headers="{
                Authorization:TOKEN
              }"
              list-type="image-card"
            >
              点击上传
            </n-upload> -->
            <!-- @before-upload ="flchang"
                @change="flchang"
                @remove="flchang"-->
            <n-upload
              directory-dnd
              :action="URL"
              :headers="{
                Authorization:TOKEN
              }"
              :max="20"
                v-model:file-list="flist"
               
                @finish="flchang"
            >
              
              <n-upload-dragger>
                <div>
                  <n-icon size="40" :depth="3">
                    <CloudUploadOutline />
                  </n-icon>
                </div>
                <n-text style="font-size: 14px">
                  点击或者拖动文件到该区域来上传
                </n-text>
              </n-upload-dragger>
            </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: 600px"
        :mask-closable="false"
      >
        <div style="display: flex;padding-bottom: 15px;font-size: 16px;">
          <div style="padding: 2px 5px;background: #50a5b7;color: #fff;border-radius: 6px 0 0 6px;">图文编号</div>
          <div style="padding: 2px 5px;border: 1px solid #50a5b7;border-radius: 0 6px 6px 0;">{{ imgCode }}</div>
        </div>
            <n-transfer
                v-model:value="xfsbvalue"
                style="height:500px;"
                :options="options"
                :render-source-list="renderSourceList"
                source-filterable
                @update:value="tranupdate"
            />
          
        
        
        <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,
  watch, 
} from 'vue'


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

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

import { useUserStore } from '@/stores/user'
//import { dictDataApi } from '@/api/org'
import {
  addDrawing, 
  editDrawing, 
  drawinglist, 
  drawingIssue, 
  deleteDrawing,
  generateDFCode,
  exportdraFile,
  opertree,
  filelist
} from '@/api/illustrated'

import { 
  basicProcessPlanApi
} from '@/api/basicProcessPlan'

const URL = `${import.meta.env.VITE_APP_BASE_API}/sys/file/upload`

const dialog = useDialog()

const message = useMessage()

const userStore = useUserStore()

const TOKEN = userStore.token

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


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

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



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

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



const columns = [
  {
      align:"center",
      title:"图文编号",
      key:"drawingCode",
      minWidth:150
    },
    // {
    //   align:"center",
    //   title:"图文名称",
    //   key:"drawingName",
    //   minWidth:150
    // },
    // {
    //   align:"center",
    //   title:"图文版本",
    //   key:"drawingVersion",
    //   minWidth:150
    // },
    // {
    //   align:"center",
    //   title:"关联工序名称",
    //   key:"processName",
    //   minWidth:150
    // },
    // {
    //   align:"center",
    //   title:"关联工序编码",
    //   key:"processCode",
    //   minWidth:150
    // },
    // {
    //   align:"center",
    //   title:"图文缩略图",
    //   key:"materialCode",
    //   minWidth:150,
    //   render(row:any) {
    //     //filePath
    //     return h(NImage, {width:'50',height:'50',src:'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'})
    //   }
    // },
    // {
    //   align:"center",
    //   title:"PLM文档",
    //   key:"plmDocId",
    //   minWidth:150
    // },
    // {
    //   align:"center",
    //   title:"PLM版本号",
    //   key:"plmVersion",
    //   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.isIssued == 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:drawingFile:issue')){
              buttons.push(h(NButton, { 
              size: 'small',
              type:'info',  
              ghost:true,
              onClick: () => { 
                issuehand(row)
               } }, 
              { default:  () =>  '下发'}
            ))
          }
          // if(hasPermission('biz:nccode:add')){
          //     buttons.push(h(NButton, { 
          //     size: 'small',
          //     type:'warning',  
          //     ghost:true,
          //     onClick: () => { 
          //       addhand(3,row)
          //      }}, 
          //     { default:  () =>  '复制'}
          //   ))
          // }

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

//获取列表数据
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 loadingRef = ref(false)
let yglist = ref<any>([])
function slehand(v?:any) {
  loadingRef.value = true

  basicProcessPlanApi.page({
      page: 1,
      pageSize: 200,
      name: v,
    }).then((rps:any) =>{
      if(rps.list && rps.list.length > 0){
        yglist.value = rps.list.map((n:any) => {
          return {
            label:n.name,
            value:n.id  //`${n.id}-${n.code}-${n.name}`
          }
        })
        
      }
      loadingRef.value = false
    }).catch(() => {
      loadingRef.value = false
    })
}

function updatesle(v:any) {
  if(v){
    //let varr = v.split('-')
    formData.processId = v+''
    // formData.processRouteStepId = varr[0]
    // formData.processCode = varr[1]
    // formData.processName = varr[2]
  }else{
    formData.processId = ''
    // formData.processRouteStepId = ''
    // formData.processCode = ''
    // formData.processName = ''
  }
  //formData.processRouteStepId = v
}

//新增
let addModel = ref(false)

const addformRef = ref()

let formData = reactive<any>({
  id:'',
  drawingCode:'',	              //图文编号
  processId:'',	                //关联工序ID
  drawingType:0,                //0 图纸 1 文件
  fileId:'',                    //文件id
  status:1,	                      //状态：1-启用 0-禁用
  // drawingName:'',	              //图文名称
  // drawingVersion:'',	          //图文版本
  // processCode:'',	              //工序编码
  // processName:'',	              //工序名称
  // filePath:'',	                //文件路径
  // fileName:'',	                //文件名
  // fileSize:'',	                //文件大小
  // fileType:'',	                //文件类型
  // plmDocId:'',	                //PLM文档ID
  // plmVersion:'',	              //PLM版本号
  // plmStatus:'',	                //PLM状态
  
  // isIssued:1,	                  //是否已下发：1-已下发 0-未下发
  // issueTime:'',	                //下发时间
  // issueBy:'',	                  //下发人
  // 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']
    // }
  ],
  processId:[
    { required: true, message: '请选择工序', trigger: 'blur' }
  ],
  fileId:[
    { required: true, message: '请上传文件', trigger: 'blur' }
  ]
  
}

//文件上传回调
let flist = ref<any>([])
function flchang(n:any) {
   let v = JSON.parse(n.event.target.responseText)
   if(v.data && v.data.id){
      formData.fileId = v.data.id+''
   }
  
  console.log(flist.value,'flist')
}


let isstype = ref<any>(1)
let selval = ref<any>('')
function addhand(type:any,row?:any) {
  addModel.value = true
  formData.value?.restoreValidation()
  isstype.value = type
  if(row){
    //slehand('')
    formData.id = row.id
    formData.drawingCode = row.drawingCode
    formData.processId = row.processId	                
    formData.drawingType = row.drawingType              
    formData.fileId = row.fileId   

    
    selval.value = row.processId
    flist.value.splice(0)
    filelist(row.fileId).then(rps => {
      if(rps){
         flist.value.push({
          id: rps.id,
          name: rps.originalName,
          status: 'finished',             // 关键：状态设为 'finished' 表示上传完成
          url: rps.url,                   // 用于预览
        })
      }
     
    })
    // 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.processId = ''	                
    formData.drawingType = 0
    formData.status = 1	              
    formData.fileId = ''  
    flist.value.splice(0)
    // 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 = 1	               
    // formData.remark = ''
    generateDFCode().then(rps => {
      formData.drawingCode = rps
    })
  }
   
}

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('请勾选设备')
//   // }
  
// }

let treeData:any = []
let xfsbvalue = ref<Array<string | number>>([])
let renderSourceList:any = ''

let options = ref<any>([])    //flattenTree(createData())

function flattenTree(list: undefined | any[]) {
  const result: any[] = []
  function flatten(_list: any[] = []) {
    _list.forEach((item) => {
      //result.push(item)
      if(item.childList){
        flatten(item.childList)
      }else{
        result.push(item)
      }
    })
  }
  flatten(list)
  return result
}

let issarr:any[] = []
let imgCode = ref<any>('')
function tranupdate(v:any) {
  issarr = []
  if(v.length > 0){
    v.forEach((n:any) => {
      if(n.split('-').length == 3){
        issarr.push(n)    
      }
    })
  }
}

let imgid = ''
function issuehand(row:any) {
  issueModel.value = true
  issarr = []
  imgid = row.id
  imgCode.value = row.drawingCode
}


function isssavehand() {
  if(issarr.length > 0){
    drawingIssue({
      id:imgid,
      twCode:issarr
    }).then(() => {
    message.success('操作成功')
    setTimeout(() => {
      getlist()
      issueModel.value = false
    },1500)
  })
  }else{
    message.warning('请选择设备')
  }
  
}


const issformRef = ref()

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

function handleExport() {


  exportdraFile({}).then(rps => {
     const url = window.URL.createObjectURL(rps)
    const link = document.createElement('a')
    link.href = url
    link.download = '图文数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  })
}

getlist()

onMounted(() => {
 //加载任务树
  opertree().then(rps => {
      treeData = rps
      options.value = flattenTree(treeData)
      renderSourceList = function (obj:any) {
          return h(NTree, {
              style: 'margin: 0 4px;',
              keyField: 'value',
              checkable: true,
              selectable: false,
              blockLine: true,
              checkOnClick: true,
              childrenField:'childList',
              data: treeData,
              cascade:true,
              defaultExpandAll:true,
              pattern:obj.pattern,
              checkedKeys: xfsbvalue.value,
              onUpdateCheckedKeys: (checkedKeys:any) => {
                  obj.onCheck(checkedKeys)
              }
          })
      }
  })
 //loadDictOptions()

})
</script>

<style scoped>

</style>
