<template>
    <!-- 权限信息弹出框 -->
<el-dialog title="设备绑定" v-model='dialogVisible' @close="close" v-bind="dialogBig" width="600" draggable>
    <div>
        <el-transfer v-model="value" 
        filterable
      :filter-method="filterMethod"
      filter-placeholder="请输入内容搜索"
      :data="allData" 
      :titles="['未绑定设备', '已绑定设备']">
      <template #default="{ option }">
        <el-tooltip :content="option.tips" placement="top" :show-after=1000>
          <span>{{ option.label }}</span>
        </el-tooltip>
      </template>
      </el-transfer>
      
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="save()">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import { computed, ref } from 'vue'
  import type { Device } from '@/api/device/interface'
  import deviceDataList from '@/api/device/deviceData'
  import { dialogBig } from '@/utils/elementBind'
  import { getUnboundPqDevList,getBoundPqDevList } from '@/api/plan/plan.ts'
  import { type Plan } from '@/api/plan/interface'
  import { ElMessage } from 'element-plus'
  const unboundPqDevList=ref<Device.ReqPqDevParams[]>([])//指定模式下所有未绑定的设备
  const boundPqDevList=ref<Device.ReqPqDevParams[]>([])//根据检测计划id查询出所有已绑定的设备 
  const dialogVisible = ref(false)
  const planData = ref<Plan.ReqPlan | null>(null) // 新增状态管理
   
  const value = ref<string[]>([])
  const generateData = () => {
  const unboundData = unboundPqDevList.value.map((i: Device.ReqPqDevParams) => ({
    key: i.id,
    label: i.name,
    tips: i.description
  }))
  const boundData = boundPqDevList.value.map((i: Device.ReqPqDevParams) => ({
    key: i.id,
    label: i.name,
    tips: i.description
  }))

  return [...unboundData, ...boundData]
  
}

const allData = computed(() => generateData())


const filterMethod = (query: string, item: { label?: string }) => {
  return item.label?.toLowerCase().includes(query.toLowerCase()) ?? false
}

  // 打开弹窗，可能是新增，也可能是编辑
  const open = async (data: Plan.ReqPlan) => {
  dialogVisible.value = true
  planData.value = data

  const pqDevList_Result1 = await getUnboundPqDevList(data);
  unboundPqDevList.value = pqDevList_Result1.data as Device.ReqPqDevParams[];

  const pqDevList_Result2 = await getBoundPqDevList({'planId': data.id});
  boundPqDevList.value = pqDevList_Result2.data as Device.ReqPqDevParams[];

  value.value = boundPqDevList.value.map((i: { id: { toString: () => any } }) => i.id.toString());
}
  const close = () => {
    dialogVisible.value = false
  }

  const save = async () => {
    if (planData.value) {
    //await BindPqDevList({ 'planId': planData.value.id,'pqDevIds': value.value  })
    ElMessage.success({ message: `设备绑定保存成功成功！` })
  }
  dialogVisible.value = false
  }

  // 对外映射
defineExpose({ open })
const props = defineProps<{
  refreshTable: (() => Promise<void>) | undefined;
}>()
  </script>