<template>
  <div class="page" @click="handleWholeClick">
    <div class="page-head flex items-center">
      <el-icon size="20"><ArrowLeft /></el-icon>
      <div class="head-opt flex-1 flex justify-between items-center">
        <div>
          <span>场景：</span>
          <el-tree-select
            v-model="selectedShopCode"
            :data="scenesTree"
            accordion
            :render-after-expand="false"
            :default-expand-all="true"
            :teleported="false"
            placeholder="请选择相关场景"
            @change="changeShop"
          />
        </div>
        <div class="flex">
          <el-upload
            class="avatar-uploader flex justify-center items-center"
            action="/skyeye-admin-api/layout/uploadPicture"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :with-credentials="true"
            name="file"
            :data="{ workshopId: selectedShopDetail?.id }"
          >
            <el-button style="font-size: 12px" :icon="Refresh" :disabled="!hasBg">
              替换照片
            </el-button>
          </el-upload>

          <el-button
            @click="handleSave"
            style="margin-left: 40px"
            type="primary"
            :disabled="!selectedShopCode"
            >保存为布局
          </el-button>
        </div>
      </div>
    </div>
    <div class="paint-tool flex">
      <div class="camera-list">
        <div>
          <span class="label-text flex">相机列表：</span>
          <ElInput
            class="search-put"
            style="margin: 10px 0; width: 230px"
            placeholder="请输入搜索内容"
            v-model="searchKey"
            :suffix-icon="Search"
          />
        </div>
        <span v-if="filterShopCameraList.length == 0" class="ml-1" style="color: #3f3f3f">
          提示：请先选择相应场景和图片
        </span>
        <el-scrollbar v-else style="position: relative; height: calc(100% - 90px)">
          <div
            v-for="item in filterShopCameraList"
            :key="item.code"
            class="camera-item flex justify-start items-center"
            :class="{
              isAdded: isAddedCamera(item.code),
              isActive: item.code === caremaActiveId,
            }"
            @click="handleAddCamera(item.code)"
          >
            <span class="camera-id">{{ item.name }}</span>
            <el-popover
              placement="bottom-start"
              trigger="hover"
              :content="item.name"
              :teleported="false"
            >
              <template #reference>
                <span class="space-name">{{ item.workSpaceName }}</span>
              </template>
            </el-popover>
          </div>
        </el-scrollbar>
      </div>
      <div ref="drawContainer" class="draw-container">
        <KonvaMap
          ref="konvaMap"
          @change-default-camera="changeDefault"
          @send-camera-id="sendCameras"
          v-moveable:1
        />
        <div id="editContainer" v-moveable:1></div>
        <el-upload
          v-if="!hasBg"
          class="upload-icon flex justify-center items-center"
          action="/skyeye-admin-api/layout/uploadPicture"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :with-credentials="true"
          name="file"
          :data="{ workshopId: selectedShopDetail?.id }"
        >
          <img src="~@/assets/images/img-upload.png" />
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import useMiniMap from './use-mini-map';
  import { storeToRefs } from 'pinia';
  import { ElMessage, ElInput } from 'element-plus';
  import { onMounted, ref } from 'vue';
  import { updateMinMapViewLayoutApi } from '@/api/scene/scene';
  import { computed } from 'vue';
  import { Search, Refresh, ArrowLeft } from '@element-plus/icons-vue';
  import KonvaMap from './MapBase/KonvaMap.vue';

  const miniMap = useMiniMap();
  const { scenesTree, shopCameraList, selectedShopCode, selectedShopDetail } = storeToRefs(miniMap);
  const { getScenesTree, getShowCameras, getMapLayout } = miniMap;

  const drawContainer = ref<HTMLDivElement>();

  const konvaMap = ref();
  const caremaActiveId = ref<string>('');
  const camerasAdded = ref<string[]>([]);
  const imgUrlBg = ref<string>('');

  const searchKey = ref('');
  // 是否已有背景图
  const hasBg = ref(false);

  const handleBeforeUpload = () => {
    if (!selectedShopCode.value) {
      ElMessage.error({
        message: '请先选择车间',
      });
      return false;
    }
  };
  const sendCameras = (camerasList) => {
    camerasAdded.value = camerasList.map((item) => {
      return item.id;
    });
    // console.log('camerasAdded.value', camerasAdded.value);
  };

  /** 判断相机是否已经添加 */
  const isAddedCamera = (cameraId: string) => {
    const index = camerasAdded.value.findIndex((item) => item === cameraId);
    return index >= 0;
  };

  const changeDefault = (defaultCameraId) => {
    caremaActiveId.value = defaultCameraId;
  };

  const handleAvatarSuccess = (e) => {
    //自己的
    imgUrlBg.value = e.data;
    konvaMap.value.addBg(imgUrlBg.value);
    hasBg.value = true;
  };

  const changeShop = (code: string) => {
    konvaMap.value.resetMap();
    getShopContent(code);
    hasBg.value = false;
  };

  const getShopContent = (code: string) => {
    getShowCameras(code);
    getMapLayout(code).then((res) => {
      if (!res) {
        return;
      }
      hasBg.value = true;
      konvaMap.value.createMap(res);
    });
  };

  const handleWholeClick = (e) => {
    // if (e.button === 0) {
    //   mapEditor.destoryOptBlock();
    // }
  };

  onMounted(() => {
    getScenesTree({ level: 2, valueKey: 'code', labelKey: 'name', disabled: true });
    konvaMap.value.resizeContainer(
      drawContainer.value!.clientWidth,
      drawContainer.value!.clientHeight,
    );
    if (selectedShopCode.value) {
      getShopContent(selectedShopCode.value);
    }
  });

  const filterShopCameraList = computed(() => {
    const k = searchKey.value.trim();
    if (!k) return shopCameraList.value;
    return shopCameraList.value.filter((x) => x.code?.includes(k) || x.workSpaceName?.includes(k));
  });

  const handleAddCamera = (cameraId: string) => {
    if (!hasBg.value) {
      ElMessage.warning({
        message: '请先添加背景图片',
      });
      return;
    }
    konvaMap.value.addCamera(cameraId);
    // mapEditor.addCamera(cameraId);
    // konvaMap.value.addCamera(cameraId);
  };

  const handleSave = () => {
    // const layout = mapEditor.toJson();
    const layout = konvaMap.value.saveLayout();
    updateMinMapViewLayoutApi({ layout, targetId: String(selectedShopDetail.value?.id) }).then(
      (res) => {
        console.log('updateMinMapViewLayoutApi', res);
        ElMessage.success('保存成功');
      },
    );
  };
</script>

<style scoped lang="scss">
  .page {
  }
  .page-head {
    height: 54px;
    padding-left: 15px;
    background-color: #ffffff;
  }
  .head-opt {
    margin-left: 20px;
    padding-right: 15px;
    font-size: 14px;
    color: #3f3f3f;
  }

  .avatar-uploader {
    /* width: 120px; */
    /* height: 30px; */
    /* border: 1px solid #eee; */
    border-radius: 4px;
    margin-left: 30px;
  }
  .upload-icon {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    margin: auto;
  }

  .paint-tool {
    position: relative;
    height: calc(100vh - 138px);
    margin-top: 2px;
  }

  .camera-list {
    width: 250px;
    padding: 0 10px;
    background-color: #ffffff;
  }
  .label-text {
    font-size: 14px;
    font-weight: 600;
    margin: 10px 0 5px 10px;
  }
  .camera-item {
    height: 32px;
    font-size: 14px;
    padding-left: 8px;
    font-weight: 400;
    color: #404040;
    line-height: 14px;
    cursor: pointer;

    &:hover {
      background-color: #e6f7ff;
      color: #1890ff;
    }
  }
  .isAdded {
    color: #1890ff;
    cursor: not-allowed;
  }
  .isActive {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  .camera-item-disabled {
    color: #c6c6c6;
  }
  .camera-id {
    width: 110px;
  }
  .space-name {
    width: 120px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .draw-container {
    position: relative;
    width: calc(100% - 300px);
    margin: 20px;
    overflow: hidden;
  }

  :deep(.search-put .el-input__wrapper) {
    background-color: #f0f2f5;
  }
  :deep(.el-popper__arrow) {
    display: none;
  }
  :deep(.el-tree-node__content:hover) {
    background: #e6f4ff;
  }
  :deep(.el-button--primary) {
    --el-button-disabled-bg-color: #bfbfbf;
  }
  :deep(.el-popover) {
    width: unset !important;
    min-width: 110px;
    text-align: center;
    font-weight: 400;
  }
</style>
