<template>
  <ElButton type="primary" @click="showDialog" size="small" style="margin-top: 10px">
    + 添加算法</ElButton
  >

  <ElDialog v-model="visible" title="添加算法" @close="handleClose" width="500px">
    <ElSelect v-model="selectedIds" multiple style="width: 100%" size="small">
      <ElOption
        v-for="item in allAlgoList"
        :key="item.id"
        :value="item.id"
        :label="item.name"
        :disabled="!!isAlgoBind(item.id)"
      >
        {{ item.name }}
        <span style="margin-left: 5px" v-if="isAlgoBind(item.id)">√</span>
      </ElOption>
    </ElSelect>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit"> 保存 </el-button>
    </template>
  </ElDialog>
</template>
<script lang="ts" setup>
  import { ElDialog, ElSelect, ElOption, ElButton, ElMessage } from 'element-plus';
  import { ref } from 'vue';
  import useCameraAlgoStore from '../../store/useCameraAlgoStore';
  import { storeToRefs } from 'pinia';
  import { createCameraAlgoApi } from '@/api/camera/camera-preview';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  const selectedIds = ref<number[]>([]);
  const cameraAlgoStore = useCameraAlgoStore();

  const { isAlgoBind } = cameraAlgoStore;
  const { allAlgoList, selectedAlgoId } = storeToRefs(cameraAlgoStore);
  const { getCameraAlgoList } = cameraAlgoStore;
  const cameraDetailStore = useCameraDetailStore();

  const visible = ref(false);
  const handleClose = () => {
    visible.value = false;
  };

  const handleSubmit = () => {
    if (selectedIds.value?.length < 1) {
      ElMessage.warning({ message: '请选择算法' });
      return;
    }
    createCameraAlgoApi({
      algoIds: selectedIds.value || [],
      cameraId: cameraDetailStore.cameraId,
    }).then((res) => {
      console.log('createAlgo ok', res);
      selectedAlgoId.value = selectedIds.value?.[0];
      getCameraAlgoList(cameraDetailStore.cameraId);
      visible.value = false;
      ElMessage.success('添加算法成功');
    });
  };

  const showDialog = () => {
    visible.value = true;
    selectedIds.value = undefined;
  };
</script>
<style scoped></style>
