<template>
  <MainPanel>
    <template v-slot:header>
      <Header
        :count="selects.length"
        :title="`全部照片（${photos.length}）`"
        type="return"
        :on-back="() => router.back()"
      >
        <ui-button
          type="primary"
          @click="selectMode = !selectMode"
          width="96px"
          v-if="sortPhotos.length"
        >
          {{ selectMode ? "取消" : "选择" }}
        </ui-button>
      </Header>
    </template>

    <Photos
      undata-msg="无照片，请打开场景拍照获取。"
      :getURL="(data) => data.urlRaw || data.url"
      v-model:active="active"
      v-model:selects="selects"
      :select-mode="selectMode"
      :data="sortPhotos"
    />
    <!--    @click="router.push(writeRouteName.scene)"-->
    <ButtonPane class="back fun-ctrl" v-if="!selectMode">
      <ui-icon type="photo" class="icon" />
      <ui-input
        type="select"
        :options="photoOptions"
        dire="top"
        class="select"
        v-model="photoType"
      />
    </ButtonPane>

    <ActionMenus
      class="select-menus"
      :menus="selectMenus"
      dire="row"
      v-if="selects.length"
    />
  </MainPanel>

  <FillSlide
    :data="sortPhotos"
    v-model:active="active"
    @quit="active = null"
    v-if="active"
    :getURL="(data) => data.urlRaw || data.url"
  >
    <template v-slot:foot>
      <ActionMenus class="menus" :menus="menus" dire="row" />
    </template>
    <template v-slot:topRight>
      <ui-icon type="share" @click="sharePhoto" />
      <ui-icon type="del" @click="delPhoto(active)" />
    </template>
  </FillSlide>
</template>

<script setup lang="ts">
import MainPanel from "@/components/main-panel/index.vue";
import FillSlide from "@/components/fill-slide/index.vue";
import Header from "@/components/photos/header.vue";
import { PhotoRaw, photos } from "@/store/photos";
import UiIcon from "@/components/base/components/icon/index.vue";
import { router, writeRouteName } from "@/router";
import ButtonPane from "@/components/button-pane/index.vue";
import { computed, onActivated, ref, watchEffect } from "vue";
import { Mode } from "@/views/graphic/menus";
import UiButton from "@/components/base/components/button/index.vue";
import Photos from "@/components/photos/index.vue";
import ActionMenus from "@/components/group-button/index.vue";
import { useConfirm } from "@/hook";
import UiInput from "@/components/base/components/input/index.vue";
import { api, downloadImage, uploadImage } from "@/store/sync";
import { formatDate, getId, imageToBlob } from "@/utils";
import { genUseLoading } from "@/hook";

const sortPhotos = computed(() => [...photos.value].reverse());
const active = ref<PhotoRaw>();
const selectMode = ref(false);
const selects = ref<PhotoRaw[]>([]);
const menus = [
  {
    key: "road",
    text: "现场绘图",
    icon: "draw_s",
    onClick: () => gotoDraw(Mode.Road),
  },
  {
    key: "accident",
    icon: "label",
    text: "事故照片",
    onClick: () => gotoDraw(Mode.Photo),
  },
];

const sharePhoto = async () => {
  // 如果没下载过相册则下载，通过文件名判断
  if (!active.value.url.includes("img_")) {
    const filename = `img_${formatDate(new Date(), "yyyyMMddhhmmss")}_${
      active.value.meterPerPixel || 1
    }_${new Date().getTime().toString().substring(8)}.jpg`;

    const img = await api.getFile(active.value.url);
    const blob = await imageToBlob(img);
    const url = await uploadImage(blob, filename);
    await downloadImage(blob, filename);
    active.value.url = url;
  }

  api.shareImage(active.value.url);
};

const selectMenus = [
  {
    key: "del",
    icon: "del",
    text: "删除",
    onClick: () => delSelects(),
  },
];

const photoType = ref<string>();
const photoOptions = [
  { value: "photograph", label: "相机拍照" },
  { value: "selectPhotoAlbum", label: "相册选择" },
  { value: "scene", label: "场景截图" },
];

watchEffect(() => {
  if (photoType.value) {
    if (photoType.value === "scene") {
      router.push(writeRouteName.scene);
    } else {
      api[photoType.value]().then((url) => {
        if (url) {
          photos.value.push({
            id: getId(),
            url,
            urlRaw: url,
            time: new Date().getTime(),
            meterPerPixel: null,
            measures: [],
            baseLines: [],
            fixPoints: [],
            basePoints: [],
          });
        }
      });
    }
    photoType.value = null;
  }
});

watchEffect(() => {
  if (!selectMode.value) {
    selects.value = [];
  }
});

const delPhotoRaw = (photo = active.value) => {
  const index = photos.value.indexOf(photo);
  const reset = active.value ? photos.value.indexOf(active.value) : -1;
  if (~index) {
    photos.value.splice(index, 1);
  }
  if (~reset) {
    if (reset >= photos.value.length) {
      if (photos.value.length) {
        active.value = photos.value[photos.value.length - 1];
      } else {
        active.value = null;
      }
    } else {
      active.value = photos.value[reset];
    }
  }
};
const delPhoto = async (photo = active.value) => {
  if (await useConfirm(`确定要删除此数据？`)) {
    delPhotoRaw(photo);
  }
};
const delSelects = async () => {
  if (await useConfirm(`确定要删除这${selects.value.length}项数据？`)) {
    while (selects.value.length) {
      delPhotoRaw(selects.value[0]);
      selects.value.shift();
    }
    if (!sortPhotos.value.length) {
      selectMode.value = false;
    }
  }
};

const gotoDraw = (mode: Mode) => {
  router.push({
    name: writeRouteName.graphic,
    params: { mode, id: active.value.id, action: "add" },
  });
};

onActivated(() => {
  active.value = null;
  selectMode.value = false;
});
</script>

<style scoped lang="scss">
.fun-ctrl {
  color: #fff;
  font-size: 20px;
  transition: color 0.3s ease;

  .icon {
    position: absolute;
    transform: translateX(-50%);
  }
}
.select-menus {
  left: 50%;
  transform: translateX(-50%);
  bottom: var(--boundMargin);
}

.back {
  right: var(--boundMargin);
  bottom: var(--boundMargin);
  overflow: hidden;

  background-color: #fff;
  i {
    color: var(--editor-menu-back);
  }

  .select {
    position: absolute;
    width: 100px;
    right: 0;
    opacity: 0;
    height: 100%;
    top: -5px;
  }
}

.menus {
  left: 50%;
  transform: translateX(-50%);
  bottom: var(--boundMargin);
}
</style>
