<template>
  <div class="system-ys7Devices-add">
    <!-- 摄像头绑定项目对话框 -->
    <el-dialog v-model="state.isShowDialog" width="769px" :close-on-click-modal="false" :destroy-on-close="true">
      <template #header>
        <div v-drag="['.system-ys7Devices-add .el-dialog', '.system-ys7Devices-add .el-dialog__header']">设备分配</div>
      </template>
      <el-form ref="formRef" :model="state.formData" label-width="90px">
        <el-radio-group v-model="state.formData.projectId" class="device_box">
          <div v-for="item in projectList" class="device_row" :key="item.id">
            <el-radio :label="item.id">{{ item.name }}</el-radio>
          </div>
        </el-radio-group>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmit">确 定</el-button>
          <el-button @click="onCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { devicesLinkPro } from '@/api/other/ys7Device';
// props
defineProps<{
  projectList: Array<any>;
}>();

// emit
const emit = defineEmits<{
  (e: 'ys7DevicesList'): void;
}>();

const { proxy } = getCurrentInstance() as any;

const formRef = ref<HTMLElement | null>(null);
const menuRef = ref();

const state = reactive({
  loading: false,
  isShowDialog: false,
  formData: { projectId: null, id: null }
});

const openDialog = (row: any) => {
  resetForm();

  if (row.row && row.row.id) {
    state.formData.id = row.row.id;
  }
  state.isShowDialog = true;
};

const closeDialog = () => {
  state.isShowDialog = false;
};

const onCancel = () => {
  closeDialog();
};

const onSubmit = () => {
  if (state.formData.projectId) {
    state.loading = true;
    devicesLinkPro(state.formData)
      .then(() => {
        ElMessage.success('分配成功');
        closeDialog();
        emit('ys7DevicesList');
      })
      .finally(() => {
        state.loading = false;
      });
  } else {
    ElMessage.warning('未选择所属项目');
  }
};

const resetForm = () => {
  state.formData = {
    id: null,
    projectId: null
  };
};

// 暴露用于父组件调用的 openDialog 方法（如果需要）
defineExpose({
  openDialog,
  closeDialog
});
</script>

<style scoped lang="scss">
.device_box {
  width: 100%;

  > div {
    padding-right: 30px;
    height: 45px;
    line-height: 45px;
  }
}
</style>
