<template>
  <el-form ref="form" label-width="100px" class="camera-from">
    <el-form-item label="SN码：" class="mandatory">
      <el-input
        :modelValue="bindCamera.snCode"
        placeholder="请输入相机底部SN码，如214D5RE2G8"
        @update:modelValue="(val: string) => (bindCamera.snCode = val.trim())"
      ></el-input>
    </el-form-item>
    <el-form-item label="所属架构：" class="mandatory">
      <com-company v-model="bindCamera.deptId" hide-all />
    </el-form-item>
    <el-form-item label="管理员：" class="mandatory">
      <el-select v-model="bindCamera.userId" placeholder="请选择" style="width: 100%">
        <el-option
          v-for="item in users"
          :key="item.id"
          :label="item.nickName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import comCompany from "@/components/company-select/index.vue";
import { Camera, addCamera } from "@/store/camera";
import { UserInfo, getUsers } from "@/store/user";
import { ref, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import { QuiskExpose } from "@/helper/mount";

const props = defineProps<{ camera?: Camera }>();
const bindCamera = ref<Camera>(
  (props.camera ? { ...props.camera } : { cameraSn: "", snCode: "" }) as Camera
);
const users = ref<UserInfo[]>([]);
watchEffect(async () => {
  if (bindCamera.value.deptId) {
    users.value = await getUsers(bindCamera.value.deptId);
  }
});

defineExpose<QuiskExpose>({
  async submit() {
    if (!bindCamera.value.snCode || !bindCamera.value.snCode.trim()) {
      ElMessage.error("SN码不能为空");
      throw "SN码不能为空";
    } else if (!bindCamera.value.userId) {
      ElMessage.error("请选择管理员");
      throw "请选择管理员";
    } else {
      await addCamera(bindCamera.value);
      return bindCamera.value;
    }
  },
});
</script>
