<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="NC代码编号">
          <n-input v-model:value="searchForm.ncCode" placeholder="请输入NC代码编号" />
        </n-form-item>

        <n-form-item label="NC代码名称">
          <n-input v-model:value="searchForm.ncName" placeholder="请输入NC代码名称" />
        </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:ncCode: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 v-if="hasPermission('biz:ncCode:export')"  type="success" @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 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="cztype[isstype]"
      preset="card"
      style="width: 600px"
      :mask-closable="false"
    >
    
    <n-form
      ref="addformRef"
      :model="formData"
      :rules="addrules"
      label-placement="left"
      label-width="100"
    >
      <n-grid :cols="1" :x-gap="24">
        <n-gi>
          <n-form-item path="ncCode" label="NC代码编号">
            <n-input v-model:value="formData.ncCode" placeholder="自动生成" disabled />
          </n-form-item>
        </n-gi>
        <n-gi>
          <n-form-item path="ncName" label="NC代码名称">
            <n-input v-model:value="formData.ncName" placeholder="请输入NC代码名称" />
          </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>
          <!--type="textarea"-->
          <n-form-item path="ncContent" label="NC代码内容">
            <n-input type="textarea" v-model:value="formData.ncContent" placeholder="请输入NC代码内容" />
          </n-form-item>    
        </n-gi>
        <n-gi>
          <n-form-item label="备注">
            <n-input type="textarea" v-model:value="formData.remark" placeholder="请输入备注" />
          </n-form-item>    
        </n-gi>
        <!-- <n-gi>
          <n-form-item label="工作中心">
            <n-input v-model:value="formData.workCenter" placeholder="请输入工作中心" />
          </n-form-item>    
        </n-gi>
        <n-gi>
          <n-form-item label="设备ID">
            <n-input v-model:value="formData.deviceId" placeholder="请输入设备ID" />
          </n-form-item>    
        </n-gi>
        <n-gi>
          <n-form-item label="设备名称">
            <n-input v-model:value="formData.deviceName" placeholder="请输入设备名称" />
          </n-form-item>  
        </n-gi> -->
        
        <!-- <n-gi>
          <n-form-item label="下发状态">
            <n-radio-group v-model:value="formData.isIssued" 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> -->
        <!-- <template v-if="formData.isIssued == 1">
          <n-gi>
            <n-form-item label="下发时间">
              <n-date-picker 
                v-model:formatted-value="formData.issueTime" 
                type="datetime" 
                style="width: 100%;" 
                clearable
                value-format="yyyy-MM-dd HH:mm:ss" 
              />
            </n-form-item>    
          </n-gi>
          <n-gi>
            <n-form-item label="下发人">
              <n-input v-model:value="formData.issueBy" placeholder="请选择下发人" />
            </n-form-item>    
          </n-gi>
        </template> -->
        
        
      </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"
    >
      <n-transfer
        v-model:value="value"
        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,
} from 'vue'


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

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

import { useUserStore } from '@/stores/user'

import { 
  addnccode,
  nccodelist,
  batchIssue,
  editccode,
  issuecopy,
  generateNccode,
  opertree,
  exportNccode
} from '@/api/nccode'

const dialog = useDialog()

const message = useMessage()

const userStore = useUserStore()

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

//const ncDispatchRecords = ref<ncCode[]>([])

//派工状态字典
//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 = [
    // { 
    //   type: 'selection',
    //   minWidth:60
    // },
    {
    align:"center",
    title:"NC代码编号",
    key:"ncCode",
    minWidth:150
  },
  {
    align:"center",
    title:"NC代码名称",
    key:"ncName",
    minWidth:150
  },


  {
    align:"center",
    title:"NC代码内容",
    key:"ncContent",
    minWidth:150
  },

  // {
  //   align:"center",
  //   title:"工作中心",
  //   key:"workCenter",
  //   minWidth:150
  // },
  
  // {
  //   align:"center",
  //   title:"设备ID",
  //   key:"deviceId",
  //   minWidth:150
  // },

  // {
  //   align:"center",
  //   title:"设备名称",
  //   key:"deviceName",
  //   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: 260,
    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: () => {
                    deleteIssue(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() {
 
}

//获取列表数据
function getlist() {
  nccodelist(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:'',
  ncCode:'',	          //NC代码编号
  ncName:'',	          //NC代码名称
  ncContent:'',	        //NC代码内容
  workCenter:'',	      //工作中心
  deviceId:'',	        //设备ID
  deviceName:'',	      //设备名称
  status:1,	            //状态：1-启用 0-禁用
  // isIssued:1,          //是否已下发：1-已下发 0-未下发
  // issueTime:null,       //下发时间
  // issueBy:'',	          //下发人
  remark:''	            //备注
}) 
const addrules = {
   ncCode: [
    { required: true, message: '请输入NC代码编号', trigger: 'blur' },
    // {
    //   validator(rule:any,value: any) {
    //     if(value > pauseform.qcNum){
    //       return new Error(`报检数量最大为${pauseform.qcNum}`)
    //     }
    //     return true
    //   },
    //   trigger: ['blur']
    // }
  ],
  ncName:[
    { required: true, message: '请输入NC代码名称', trigger: 'blur' }
  ],
  ncContent:[
    { required: true, message: '请输入NC代码内容', trigger: 'blur' }
  ]
}

let isstype = ref<any>(1)

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

function addhand(type:any,row?:any) {
  addModel.value = true
  formData.value?.restoreValidation()
  isstype.value = type
  if(type == 1 || type == 3){
    generateNccode().then(rps => {
      formData.ncCode = rps  
    })
  }
  
  if(row){
    formData.id = row.id	          
    formData.ncName = row.ncName	          
    formData.ncContent = 	row.ncContent        
    formData.workCenter = row.workCenter	      
    formData.deviceId = 	row.deviceId        
    formData.deviceName = row.deviceName	      
    formData.status = row.status	          
    // formData.isIssued = row.isIssued          
    // formData.issueTime = row.issueTime       
    // formData.issueBy = row.issueBy	        
    formData.remark = row.remark
    if(type == 2){
      formData.ncCode = row.ncCode
    }else{
      formData.ncCode = ''
    }	        
  }else{
    formData.id = ''
    formData.ncCode = ''	          
    formData.ncName = ''	          
    formData.ncContent = 	''        
    formData.workCenter = ''	      
    formData.deviceId = 	''        
    formData.deviceName = ''	      
    formData.status = 1	          
    // formData.isIssued = ''          
    // formData.issueTime = ''       
    // formData.issueBy = ''	        
    formData.remark = ''
  }
}

function addEdi(){
  if(isstype.value == 1){
    return addnccode(formData)
  }
  if(isstype.value == 2){
    return  editccode(formData)
  }
  formData.id = ''
  return issuecopy(formData)
  
}

function savehand() {
  addformRef.value?.validate((e:any) => {
    if (!e) {

      addEdi().then(() => {
        message.success(`${cztype[isstype.value]}成功`)
        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){
    batchIssue(chearr.value).then(() => {
      message.success('操作成功')
    })
  }else{
    message.error('请勾选设备')
  }
  
}

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

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

let treeData:any = []
let value = 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
}


function tranupdate(v:any) {
    console.log(v)
}

//下发
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

  
}

const issformRef = ref()

function isssavehand() {
  issformRef.value?.validate((e:any) => {
    if (!e) {
      batchIssue('').then(() => {
        message.success('操作成功')
        setTimeout(() => {
          getlist()
          issueModel.value = false
        },1500)
      })
      
    }
  })
}
//导出
//let selectedIds = ref<any>([])
function handleExport() {


  exportNccode({}).then(rps => {
     const url = window.URL.createObjectURL(rps)
    const link = document.createElement('a')
    link.href = url
    link.download = 'NC代码数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  })
}


getlist()

//查看下发记录
async function handleDispatchRecord(row:ncCode){
    const ncId = row.id
    // ncDispatchRecords.value = await
}


onMounted(() => {
 
  //加载任务树
  opertree().then(rps => {
      treeData = rps
      options.value = flattenTree(treeData)
      console.log(rps,'112')
      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: value.value,
              onUpdateCheckedKeys: (checkedKeys: Array<string | number>) => {
                  obj.onCheck(checkedKeys)
                  console.log(value.value,'tree')
              }
          })
      }
  })

 //loadDictOptions()

})
</script>

<style scoped>

</style>
