<template>
  <el-dialog class="api-edit" v-model="showDialog" title="绑定设备" width="800px" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-table :data="tableData" v-if="showDialog" style="width: 100%" row-key="key" @selection-change="handleSelectionChange" v-loading="loading">
      <el-table-column type="selection" reserve-selection :selectable="(row: any) => !hasBindKeys.includes(row.key)" width="55" align="center" />
      <el-table-column prop="name" label="设备名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="key" label="设备编码" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="productName" label="所属产品" align="center"></el-table-column>
    </el-table>
    <div class="flex-row">
      <pagination v-if="params.total" :total="params.total" v-model:page="params.pageNum" v-model:limit="params.pageSize" @pagination="getList()" />
    </div>
    <div style="float: right">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="onSubmit">绑定设备</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import api from '/@/api/projects';
import deviceApi from '/@/api/device';
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useSearch } from '/@/hooks/useCommon';

const emit = defineEmits(['getList']);

defineProps({
  hasBindKeys: {
    type: Array,
    default: () => []
  },
});

const showDialog = ref(false);
const code = ref('');
const keys = ref<any[]>([]);

const { params, tableData, getList, loading } = useSearch<any[]>(deviceApi.instance.getList, 'device', { keyWord: '', status: undefined, pageSize: 10 });

// 多选框选中数据
const handleSelectionChange = (selections: any[]) => {
  keys.value = selections.map((item) => item.key);
};

const onSubmit = async () => {

  await api.template.bindDevices({ code: code.value, deviceKeys: keys.value });

  ElMessage.success('操作成功');
  // resetForm();
  showDialog.value = false;
  emit('getList');
};

const open = async (templateseCode: string) => {
  tableData.value = []
  code.value = templateseCode;
  showDialog.value = true;
  getList();
};

function cancel() {
  showDialog.value = false;
}

defineExpose({ open });
</script>
