<template>
  <div class="presetSetting">
    <div style="margin-right: 10px">预置位</div>
    <div>
      <ElSelect
        :model-value="currentPresetToken"
        size="small"
        filterable
        @update:model-value="handleChangeValue"
      >
        <ElOption
          v-for="item in presetOptions"
          :key="item.token"
          :label="item.name"
          :value="item.token"
        >
          <span style="float: left">{{ item.name }}</span>
          <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
            <!-- 点击删除的时候，阻止选中菜单 -->
            <el-icon @click.stop="handleDeletePreset(item.token)"><CircleCloseFilled /></el-icon>
          </span>
        </ElOption>
      </ElSelect>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ElSelect, ElOption, ElMessage, ElMessageBox } from 'element-plus';
  import { CircleCloseFilled } from '@element-plus/icons-vue';
  import usePresetListStore from '../../store/usePresetListStore';
  import { storeToRefs } from 'pinia';
  import { deletePresetApi } from '@/api/camera/camera-preview';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  import { ref } from 'vue';
  // const presetOptions = ref([
  //   { label: '预置位1', value: 'p1' },
  //   { label: '预置位2', value: 'p2' },
  // ]);

  const presetListStore = usePresetListStore();

  const cameraDetailStore = useCameraDetailStore();

  const { data: presetOptions, currentPresetToken } = storeToRefs(presetListStore);

  const handleDeletePreset = (token: string) => {
    ElMessageBox({
      message:
        '该预置位可能存在关联的电子围栏。删除该预置位将会删除对应的电子围栏信息，请确认是否删除',
      title: '删除确认',
      showCancelButton: true,
      confirmButtonText: '确认删除',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          deletePresetApi({ presetToken: token, cameraId: cameraDetailStore.cameraId })
            .then((res) => {
              ElMessage.success('删除成功！');
              presetListStore.getPresetList(cameraDetailStore.cameraId);
              currentPresetToken.value = presetOptions.value?.[0].token || '';
              done();
            })
            .finally(() => {
              instance.confirmButtonLoading = true;
            });
        } else {
          done();
        }
      },
    });
  };

  const handleChangeValue = (val) => {
    console.log('changeValue', val);
    currentPresetToken.value = val;
  };
</script>
<style scoped>
  .presetSetting {
    display: flex;
    align-items: center;
  }
</style>
