<template>
  <div id="algoSetting">
    <div>
      <div class="algoTagWrapper">
        <!-- <AddAlgoDialog v-if="algoDialogVisible" @close="closeDialog" /> -->
        <AlgoSwitchCard
          v-for="item in cameraAlgoList"
          :key="item.code"
          :label="item.algoInfo?.name"
          :is-selected="item.algoId === selectedAlgoId"
          :is-algo-open="item.status === ALGO_ENABLED_STATUS.enabled"
          @click.capture="handleSelectAlgo(item.algoId, $event)"
          @remove="confirmRemove(item.algoId, item)"
          @toggle-algo="confirmToggleAlgoOpen(item, $event)"
          :is-fence-open="item.electronicFence === FENCE_ENBALED_STATUS.enabled"
          @toggle-fence-tool="toggleFenceTool(item, $event)"
          @toggle-setting="handleToggleSetting(item.algoId)"
        />
      </div>
      <div>
        <AlgoParamsSetting
          @on-submit="handleSubmit"
          @on-cancel="handleCancel"
          @change="handleSettingChange"
          :is-changed="isParamsChanged"
          :algo-detail="selectedAlgoDetail"
          v-if="selectedAlgoId && algoSettingIsOpen"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import useCameraAlgoStore from '../../store/useCameraAlgoStore';
  import AlgoParamsSetting from '@/modules/algo/algo-params-edit/index.vue';
  import { storeToRefs } from 'pinia';
  import {
    deleteCameraAlgoApi,
    updateCameraAlgoApi,
    FENCE_ENBALED_STATUS,
    CameraAlgoItem,
    updateCameraAlgoRelStatus,
  } from '@/api/camera/camera-preview';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import AlgoSwitchCard from '../AlgoSwitchCard/AlgoSwitchCard.vue';
  import useFenceStore from '../../store/useFenceStore';
  import useCameraDetailStore from '../../store/useCameraDetailStore';
  import usePresetListStore from '../../store/usePresetListStore';
  // import AddAlgoDialog from './AddAlgoDialog.vue';
  import { createAlgoSubmitParams, algoDetailToJSON, cameraAlgoToJSON } from '@/modules/algo/algo-params-edit/utils';

  import { ALGO_ENABLED_STATUS } from '@/api/camera/camera-preview';
  import { ref, watchEffect } from 'vue';

  const cameraAlgoStore = useCameraAlgoStore();
  const fenceStore = useFenceStore();
  const presetStore = usePresetListStore();

  const { getCameraAlgoList, getAlgoDetail } = cameraAlgoStore;
  const { cameraAlgoList, selectedAlgoId, selectedAlgoDetail } = storeToRefs(cameraAlgoStore);
  const cameraDetailStore = useCameraDetailStore();

  // const hasAddPermission = () => userStore.checkPermission(PERM_ALGO.CONFIG_ADD);
  const algoSettingIsOpen = ref(false);

  // 是否修改过参数配置
  const isParamsChanged = ref(false);

  const handleSettingChange = () => {
    isParamsChanged.value = true;
  };

  const handleToggleSetting = (algoId: number) => {
    // 如果是在当前选中的卡片上切换设置开关，那么反选即可
    if (selectedAlgoId.value === algoId) {
      checkExitParams().then(() => {
        algoSettingIsOpen.value = !algoSettingIsOpen.value;
        isParamsChanged.value = false;
      });
    }
  };

  /** 检测是否要离开参数设置 */
  const checkExitParams = (): Promise<unknown> => {
    if (isParamsChanged.value) {
      return confirmSwitchAlgo();
    } else {
      return Promise.resolve();
    }
  };

  const handleSelectAlgo = (algoId: number, e) => {
    // 如果点击的是它自己，那么取消选中当前的算法
    if (selectedAlgoId.value === algoId) {
      return;
    }
    // 如果点击的是其他卡片，那么先切换到这个卡片，不执行按钮的默认操作
    e.stopPropagation();
    const switchToNewAlgo = (_algoId: number) => {
      selectedAlgoId.value = _algoId;
      algoSettingIsOpen.value = false;
      isParamsChanged.value = false;
      fenceStore.showFenceTool = false;
    };
    /** 确认电子围栏是否要离开，如果确认离开，再确认算法参数配置要不要离开 */
    fenceStore
      .confirmExitFence()
      .then(checkExitParams)
      .then(() => {
        switchToNewAlgo(algoId);
        // 切换成功后要把原来的电子围栏数据给清空
        fenceStore.clear();
      });
  };

  watchEffect(() => {
    const algoId = selectedAlgoId.value;
    if (!algoId) return;
    const detail = getAlgoDetail(algoId);
    if (!detail) return;
    selectedAlgoDetail.value = cameraAlgoToJSON(detail);
    fenceStore.getFence({
      algoId: algoId,
      cameraId: cameraDetailStore.cameraId,
      presetToken: presetStore.currentPresetToken,
    });
  });

  const toggleFenceTool = () => {
    const nextShowFenceTool = !fenceStore.showFenceTool;
    fenceStore.showFenceTool = nextShowFenceTool;
  };

  const confirmToggleAlgoOpen = (detail: CameraAlgoItem, algoStatus: boolean) => {
    if (algoSettingIsOpen.value) {
      confirmSwitchAlgo().then(() => {
        handleToggleAlgoOpen(detail, algoStatus);
      });
    } else {
      handleToggleAlgoOpen(detail, algoStatus);
    }
  };

  const handleToggleAlgoOpen = (detail: CameraAlgoItem, algoStatus: boolean) => {
    // 如果是在已选中的卡片上切换或者其他卡片设置是关闭的情况下，直接切不提示。
    // 只有切到其他卡片并且当前的设置是打开的情况下，才需要提示。
    const cameraId = cameraDetailStore.cameraId;
    const algoId = detail.algoId;
    // console.log({ detail, status });
    const status = algoStatus ? ALGO_ENABLED_STATUS.enabled : ALGO_ENABLED_STATUS.disabled;
    const params = {
      cameraId: cameraId,
      id: detail.id as number,
      algoId,
      status,
    };
    const initialStatus = detail.status;
    detail.status = status;
    selectedAlgoId.value = algoId;
    isParamsChanged.value = false;
    algoSettingIsOpen.value = false;
    updateCameraAlgoRelStatus(params)
      .then(() => {
        ElMessage.success(algoStatus ? '算法已开启' : '算法已关闭');
      })
      .catch(() => {
        detail.status = initialStatus;
      });
  };

  const handleSubmit = (param) => {
    const cameraId = cameraDetailStore.cameraId;

    const newParam = { cameraId: cameraId, ...createAlgoSubmitParams(param, selectedAlgoDetail.value) };
    if (param.id) {
      updateCameraAlgoApi({ ...newParam, id: param.id }).then(() => {
        ElMessage.success('更新成功');
        getCameraAlgoList(cameraId);
        isParamsChanged.value = false;
      });
    }
  };

  const confirmRemove = (algoId: number, item) => {
    ElMessageBox.confirm(`请确定是否删除【${item.algoInfo.name}】算法?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      handleRemove(algoId);
    });
  };

  const confirmSwitchAlgo = (): Promise<boolean> => {
    return ElMessageBox.confirm('算法参数设置未保存，离开后无法保存设置内容。', '', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }).then(() => {
      return true;
    });
  };

  const handleRemove = (algoId: number) => {
    deleteCameraAlgoApi({ algoId, cameraId: cameraDetailStore.cameraId }).then(() => {
      ElMessage.success('删除成功');
      getCameraAlgoList(cameraDetailStore.cameraId);
      selectedAlgoId.value = undefined;
      isParamsChanged.value = false;
    });
  };

  const handleCancel = () => {
    isParamsChanged.value = false;
    selectedAlgoId.value = undefined;
  };
</script>
<style scoped>
  .algoTagWrapper {
    min-width: 150px;
    margin-right: 15px;
    display: flex;
    flex-wrap: wrap;
  }

  :deep(.el-message-box__status.el-icon) {
    top: 0 !important;
    transform: none !important;
  }
</style>
