<template>
  <MainPanel>
    <template v-slot:header>
      <Header
        :count="selects.length"
        :title="`现场图管理（${sortPhotos.length}）`"
        type="return"
        :on-back="() => onBack()"
      >
        <ui-button
          :type="selectMode ? 'primary' : 'normal'"
          @click="selectMode = !selectMode"
          width="96px"
          style="margin-right: 16px"
          v-if="sortPhotos.length"
        >
          {{ selectMode ? "取消" : "选择" }}
        </ui-button>
        <ui-button
          v-if="!selectMode"
          type="primary"
          @click="router.push({ name: writeRouteName.photos })"
          width="96px"
        >
          新增
        </ui-button>
        <template v-slot:center="{ count }">
          <template v-if="count"> 已选择 {{ count }} 张 </template>
          <!-- <div v-else class="filter-type">
            <span
              :class="{ active: currentType === TypeEnum.Draw }"
              @click="() => (currentType = TypeEnum.Draw)"
              >绘图</span
            >
            <span
              :class="{ active: currentType === TypeEnum.Table }"
              @click="() => (currentType = TypeEnum.Table)"
              >制表</span
            >
          </div> -->
        </template>
      </Header>
    </template>

    <!-- :getURL="(data) => data?.table?.url || data.url" -->
    <Photos
      undata-msg="无现场图。请点击右上角按钮绘制现场图。"
      v-model:active="active"
      v-model:selects="selects"
      :select-mode="selectMode"
      :data="sortPhotos"
      :getURL="(data) => data.url"
    >
      <template v-slot="{ data }">
        <p v-if="currentType === TypeEnum.Table">
          <!-- {{ (data as any).title || "默认标题" }} -->
        </p>
      </template>
    </Photos>

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

  <!-- :getURL="(data) => data?.table?.url || data.url" -->
  <FillSlide
    :getURL="(data) => data.url"
    :data="sortPhotos"
    v-model:active="active"
    @quit="active = null"
    v-if="active"
  >
    <template v-slot:foot>
      <ActionMenus class="menus" :menus="menus" dire="row" />
    </template>
    <template v-slot:topRight>
      <ui-icon type="copy" @click="copyPhoto" />
      <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 { roadPhotos, RoadPhoto } from "@/store/roadPhotos";
import ActionMenus from "@/components/group-button/index.vue";
import { readyRouteName, router, writeRouteName } from "@/router";
import { computed, onDeactivated, reactive, ref, watchEffect } from "vue";
import { Mode } from "@/views/graphic/menus";
import UiButton from "@/components/base/components/button/index.vue";
import Header from "@/components/photos/header.vue";
import Photos from "@/components/photos/index.vue";
import ButtonPane from "@/components/button-pane/index.vue";
import UiIcon from "@/components/base/components/icon/index.vue";
import { useConfirm } from "@/hook";
import { api } from "@/store/sync";
import { photos } from "@/store/photos";
import { getId } from "@/utils";

const enum TypeEnum {
  Draw = "draw",
  Table = "table",
}
const currentType = ref(TypeEnum.Draw);
const sortPhotos = computed(
  () =>
    roadPhotos.value.sort((a, b) => (b.updateTime || b.time) - (a.updateTime || a.time))
  // .filter((item) => (currentType.value === TypeEnum.Draw ? !item.table : !!item.table))
);
const onBack = () => {
  router.replace(readyRouteName.scene);
  // let back = router.currentRoute.value.query.back;
  // if (back) {
  //   router.back();
  // } else {
  //   api.closePage();
  // }
};

const active = ref<RoadPhoto>();
const selectMode = ref(false);
const selects = ref<RoadPhoto[]>([]);
const menus = computed(() => [
  // {
  //   key: "copy",
  //   icon: "copy",
  //   text: "复制",
  //   onClick: () => {
  //     const copy = JSON.parse(JSON.stringify(active.value)) as RoadPhoto;
  //     copy.id = getId();
  //     copy.time = new Date().getTime();
  //     roadPhotos.value.push(copy);
  //     active.value = null;
  //     // gotoDraw(copy);
  //   },
  // },
  {
    key: "tabulation",
    icon: "tabulation",
    // hide: currentType.value === TypeEnum.Table,
    text: "制表",
    onClick: () => gotoDraw(active.value, true),
  },
  {
    key: "road",
    icon: "edit",
    text: "修改",
    onClick: () => gotoDraw(),
  },
]);

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

const copyPhoto = () => {
  const copy = JSON.parse(JSON.stringify(active.value)) as RoadPhoto;
  copy.id = getId();
  copy.time = new Date().getTime();
  roadPhotos.value.push(copy);
  active.value = null;
  // gotoDraw(copy);
};

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

watchEffect(() => {
  const route = router.currentRoute.value;
  if (route.name === readyRouteName.roads) {
    console.log(route.params);
    if (route.params.type) {
      currentType.value = route.params.type as TypeEnum;
    }
  }
});

const delPhotoRaw = (roadPhoto = active.value) => {
  const index = roadPhotos.value.indexOf(roadPhoto);
  const reset = active.value ? roadPhotos.value.indexOf(active.value) : -1;
  if (~index) {
    roadPhotos.value.splice(index, 1);
  }
  if (~reset) {
    if (reset >= roadPhotos.value.length) {
      if (roadPhotos.value.length) {
        active.value = roadPhotos.value[roadPhotos.value.length - 1];
      } else {
        active.value = null;
      }
    } else {
      active.value = roadPhotos.value[reset];
    }
  }
};

const delPhoto = async (photo = active.value) => {
  if (await useConfirm(`确定要删除此数据？`)) {
    console.log(photo);
    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 = (road = active.value, forece = false) => {
  if (forece) {
    router.push({
      name: writeRouteName.tabulation,
      params: { id: road.id },
    });
  } else {
    router.push({
      name: writeRouteName.graphic,
      params: { mode: Mode.Road, id: road.id, action: "update" },
    });
  }
  // if (forece || road.table) {
  //   router.push({
  //     name: writeRouteName.tabulation,
  //     params: { id: road.id },
  //   });
  // } else {
  //   router.push({
  //     name: writeRouteName.graphic,
  //     params: { mode: Mode.Road, id: road.id, action: "update" },
  //   });
  // }
};

onDeactivated(() => {
  active.value = null;
});
</script>

<style scoped lang="scss">
.photo p {
  color: #fff;
  font-size: 14px;
  margin-top: 8px;
  height: 20px;
  word-break: keep-all; /* 不换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.menus {
  left: 50%;
  transform: translateX(-50%);
  bottom: var(--boundMargin);
}
.fun-ctrl {
  color: #fff;
  font-size: 20px;
  transition: color 0.3s ease;

  .icon {
    position: absolute;
    transform: translateX(-50%);
  }
}

.del {
  left: 50%;
  transform: translateX(-50%);
  bottom: var(--boundMargin);
}

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

.filter-type {
  span {
    display: inline-block;
    color: #ffffff;
    font-size: 16px;
    margin: 0 20px;
    &.active {
      position: relative;

      &::after {
        position: absolute;
        content: "";
        bottom: 0;
        margin-bottom: -14px;
        left: 0;
        right: 0;
        height: 4px;
        background: #1779ed;
        border-radius: 2px;
      }
    }
  }
}
</style>
