<template>
  <div class="page">
    <div class="page-head flex items-center">
      <div class="head-opt flex-1 flex justify-between items-center" style="margin-left: 0px">
        <div>
          <!-- <span>场景：</span> -->
        </div>
        <div class="top-bar">
          <div class="back-and-company">
            <div class="back" @click="handelClickBack">
              <img src="@/assets/rollback.png" />
              <span>返回</span>
            </div>
            <div class="company-name">{{ companyName }}</div>
          </div>
          <div class="operation-btns">
            <el-upload
              class="avatar-uploader"
              :action="actionUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="handleBeforeUpload"
              :with-credentials="true"
              name="file"
              :data="{ companyId, deleteFileName: bgImg }"
              :headers="getHeaders()"
            >
              <el-button :icon="Refresh" :disabled="!hasBg"> 替换照片 </el-button>
            </el-upload>

            <el-button :icon="Refresh" :disabled="!hasBg" @click="clearLayout"> 重置布局 </el-button>

            <el-button @click="handleSave" type="primary" :disabled="!companyId"> 保存 </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="paint-tool">
      <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>
        <el-scrollbar style="position: relative; height: calc(100% - 90px)">
          <div
            v-for="item in filterShopList"
            :key="item.code"
            class="camera-item flex justify-start items-center"
            :class="{
              isAdded: isAddedShop(item.id),
              isActive: item.id === Number(activeShopId),
            }"
            @click="handleAddShop(item)"
          >
            <span class="camera-id">{{ item.name }}</span>
          </div>
        </el-scrollbar>
      </div>
      <div ref="drawContainer" id="drawContainer" class="draw-container">
        <div id="shopEditContainer" v-moveable:1 class="shop-edit-container">
          <MapContainer ref="mapContainerRef" :is-mobile-view="isMobileView" :scale="scale" />
        </div>
        <el-upload
          v-if="!hasBg"
          class="upload-icon flex justify-center items-center"
          :action="actionUrl"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :with-credentials="true"
          name="file"
          :data="{ companyId }"
          :headers="getHeaders()"
        >
          <img src="~@/assets/images/img-upload.png" />
          <div class="upload-tips-text"> 请上传1920*1080尺寸的布局背景图，其他尺寸会影响布局准确性！ </div>
        </el-upload>
      </div>
      <div class="shop-tag-edit-area" v-if="hasBg">
        <ShopTagEditArea @transformer-change="transformChange" />
      </div>
    </div>

    <ConfigFinish :visible="visibleResult" :status="configStatus" @on-close="closeResult" class="feedback-position" />
  </div>
</template>

<script setup lang="ts">
  import ConfigFinish from './component/ConfigFinish.vue';
  import { storeToRefs } from 'pinia';
  import { ElMessage, ElInput, ElMessageBox } from 'element-plus';
  import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
  import { getWorkshopListApi } from '@/api/scene/scene';
  import { computed } from 'vue';
  import { Search, Refresh, ArrowLeftBold } from '@element-plus/icons-vue';
  import usePageConfig from './usePageConfig';
  import MapContainer from './component/mapContainer/MapContainer.vue';
  import useMapEditor, { LabelPositionEnum } from './stores/useMapEditor';
  import {
    uploadCompanyLayout,
    updateCompanyLayout,
    getCompanyLayoutApi,
    getMobileCompanyLayoutApi,
  } from '@/api/scene/scene';
  import safeParse from '@/utils/safeParse';
  import { useRouter } from 'vue-router';
  import urlJoin from 'url-join';
  import { useGlobSetting } from '@/hooks/setting';
  import { getHeaders } from '@/utils/http/axios';
  import { ShopType } from '@/types/page-config/type';
  import ShopTagEditArea from './component/ShopTagEditArea.vue';
  import { ViewType } from '@/types/page-config/type';

  const mapEditor = useMapEditor();
  const { bgImg, addedShops, activeShopId, showShops, mapHeight, mapWidth } = storeToRefs(mapEditor);
  const { addShop, addBg, calcLayout, resetMap, createMap, deleteShop } = mapEditor;

  const router = useRouter();

  const pageConfig = usePageConfig();
  const { label, layoutId } = pageConfig;
  const { urlPrefix, minifyImgUrl } = useGlobSetting();
  const drawContainer = ref<HTMLDivElement>();
  const mapContainerRef = ref();

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

  // 是否开启移动端视图
  const isMobileView = ref(false);

  const companyId = ref<number>();
  const companyName = ref<string>();
  const viewType = ref<ViewType>();

  const shopList = ref<ShopType[]>([]); // 车间列表

  // mapContainer宽高
  const mapContainerStageSize = reactive({ height: 0, width: 0 });
  // // mapContainer缩放比例
  const scale = computed(() =>
    Math.min(mapContainerStageSize.width / mapWidth.value, mapContainerStageSize.height / mapHeight.value),
  );

  const defaultLayoutString = ref(''); // 默认布局的string，用于点击返回时判断是否未保存布局就离开

  const handleBeforeUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpg' && rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('请上传jpg、jpeg、png格式的图片!');
      return Promise.reject();
    }
    const mSize = 1024 * 1024;
    if (rawFile.size > 2 * mSize) {
      const realSize = (rawFile.size / mSize).toFixed(2);
      ElMessageBox.alert(`<div>当前图片${realSize}M，建议压缩到2M以内。 <div>`, '提示', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: minifyImgUrl ? '点我去压缩' : '确定',
        type: 'warning',
      }).then(() => {
        if (minifyImgUrl) {
          window.open(minifyImgUrl);
        }
      });

      return Promise.reject();
    }
  };

  /** 判断相机是否已经添加 */
  const isAddedShop = (shopId: number) => {
    const index = addedShops.value.findIndex((item) => item.id === shopId);
    return index >= 0;
  };

  const transformChange = () => {
    mapContainerRef.value.updateLayoutTransformer();
  };

  const actionUrl = computed(() => {
    return urlJoin(urlPrefix, '/admin/homepageConfig/uploadCompanyPicture');
  });

  watch(
    () => showShops,
    () => {
      transformChange();
    },
    { deep: true },
  );

  //总体的保存，将整个数据传过去
  const visibleResult = ref(false);
  const configStatus = ref(true);
  const closeResult = () => {
    visibleResult.value = false;
  };
  /** ------------- */

  const handleAvatarSuccess = (e) => {
    if (e.code !== 200) {
      ElMessage.error(e.data);
      return;
    }
    bgImg.value = e.data;
    hasBg.value = true;
    addBg();
  };

  const getShopContent = () => {
    const companyLayoutApiMap = {
      [ViewType.companyHomepage_PC]: getCompanyLayoutApi,
      [ViewType.companyHomepage_phone]: getMobileCompanyLayoutApi,
    };
    getWorkshopListApi({ companyId: companyId.value! }).then((res) => {
      shopList.value = res;
    });

    companyLayoutApiMap[viewType.value!]({
      companyId: companyId.value!,
    }).then((res) => {
      if (!res) {
        layoutId.value = undefined;
        return;
      }
      layoutId.value = res.id;
      const layoutJSON = res.layout ? safeParse(res.layout) : null;

      if (!layoutJSON) {
        return;
      }
      hasBg.value = true;
      createMap(layoutJSON);
      defaultLayoutString.value = res.layout;
    });
  };

  const clearLayout = () => {
    ElMessageBox.confirm('是否重置当前设置？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      resetMap();
      hasBg.value = false;
    });
  };

  const handleKeyDown = (e) => {
    // 删除键
    if (e.keyCode === 46 || e.code === 'Delete') {
      deleteShop();
    }
  };

  const filterShopList = computed(() => {
    const k = searchKey.value.trim();
    if (!k) return shopList.value;
    return shopList.value?.filter((x) => x.name?.includes(k));
  });

  const setNodePosition = (positionX = 50, positionY = 50) => {
    if (addedShops.value.find((item) => item.x === positionX && item.y === positionY)) {
      return setNodePosition(positionX, positionY + 50);
    } else return { positionX, positionY };
  };

  const handleAddShop = (shop: ShopType) => {
    //如果已经存在车间，则禁止加入
    const existingCamera = addedShops.value.find((item) => item.id === shop.id);
    if (existingCamera) return;
    if (!hasBg.value) {
      ElMessage.warning({
        message: '请先添加背景图片',
      });
      return;
    }

    const nodePosition = setNodePosition();

    const shopNode = {
      ...shop,
      x: nodePosition.positionX,
      y: nodePosition.positionY,
      scaleX: 1,
      scaleY: 1,
      bgColor: 'rgba(58, 170, 209, 1)',
      fontSize: 14,
      fontColor: '#ffffff',
      posType: LabelPositionEnum.LEFT,
    };
    addShop(shopNode);
  };

  const handleSave = () => {
    if (hasBg.value === false) {
      ElMessage.error('请添加背景图片');
      return;
    }

    if (addedShops.value.length === 0) {
      ElMessage.error('请至少添加1个车间标签后发布');
      return;
    }

    const { json } = mapContainerRef.value?.getLayout();
    const layout = calcLayout(json);
    const param = {
      layout,
      targetId: companyId.value || 2,
      labelId: label.value || 1,
      viewType: viewType.value!,
    };
    if (!layoutId.value) {
      uploadCompanyLayout(param).then((res) => {
        layoutId.value = res;
        ElMessage.success('保存成功');
      });
    } else {
      updateCompanyLayout({ ...param, id: layoutId.value }).then((_res) => {
        ElMessage.success('更新成功');
      });
    }
    defaultLayoutString.value = layout;
  };

  function handelClickBack() {
    const json = calcLayout(mapContainerRef.value?.getLayout().json);

    if (json !== defaultLayoutString.value) {
      ElMessageBox.confirm('未保存当前设置，是否离开？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        router.back();
      });
    } else router.back();
  }

  watch(
    () => mapHeight.value,
    () => {
      mapContainerStageSize.height = document.getElementById('drawContainer')?.clientHeight!;
      mapContainerStageSize.width = document.getElementById('drawContainer')?.clientWidth!;
    },
  );

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeyDown);
    window.onresize = null;
    resetMap();
  });

  onMounted(() => {
    const routerParams = router.currentRoute.value.query;

    if (routerParams.companyId) {
      companyId.value = Number(routerParams.companyId);
      companyName.value = String(routerParams.companyName);
      viewType.value = Number(routerParams.viewType);
    }

    window.addEventListener('keydown', handleKeyDown);
    window.onresize = () => {
      mapContainerStageSize.height = document.getElementById('drawContainer')?.clientHeight!;
      mapContainerStageSize.width = document.getElementById('drawContainer')?.clientWidth!;
    };

    if (companyId.value) {
      getShopContent();
    }
  });
</script>

<style scoped lang="scss">
  .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 {
    border-radius: 4px;
    margin-left: 30px;
  }

  .label-workshop {
    font-size: 14px;
    font-weight: 400;
    margin-left: 36px;
    margin-top: 6px;
    margin-right: 16px;
  }

  .upload-icon {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    margin: auto;
  }

  .upload-tips-text {
    margin-top: 15px;
  }

  .paint-tool {
    position: relative;
    height: calc(100vh - 138px);
    margin-top: 2px;
    display: flex;
    justify-content: space-between;
  }

  .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 {
    height: calc(100vh - 160px);
    position: relative;
    margin: 10px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .shop-edit-container {
    scale: v-bind(scale);
  }

  .drawer-position {
    position: absolute;
    right: 0px;
    // left: 1150px;
    top: 74px;
    z-index: 99;
    opacity: 1;
    background: #ffffff;
  }

  .dialog-btn {
    position: absolute;
    right: 0px;
    top: 66px;
  }

  .position-tooltip {
    margin-right: -10px;
  }

  .circle-rectangle {
    width: 40px;
    height: 30px;
    border-radius: 50% 0% 0% 50%;
    position: absolute;
    right: 0px;
    top: 66px;
    background-color: white;
    display: flex;
  }

  .shape-shadow {
    filter: drop-shadow(5px 5px 10px rgb(102, 100, 100));
  }
  .left-icon {
    margin-top: 7px;
    margin-left: 8px;
    margin-right: -7px;
  }

  .feedback-position {
    position: absolute;
    left: 760px;
    top: 250px;
    z-index: 9999;
  }

  .top-bar {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .back-and-company {
      display: flex;
      align-items: center;
      gap: 10px;
      .back {
        display: flex;
        align-items: center;
        gap: 10px;
        cursor: pointer;
        img {
          width: 14px;
          height: 14px;
        }
        span {
          line-height: 14px;
        }
      }
      .company-name {
        font-weight: 600;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
      }
    }
    .operation-btns {
      width: 380px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .el-button {
        // margin-left: 20px;
      }
    }
  }

  .shop-tag-edit-area {
    width: 300px;
    background-color: #ffffff;
  }

  :deep(.el-button) {
    margin: 0px;
  }

  :deep(.el-upload) {
    flex-direction: column;
  }

  :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;
  }
  ::v-deep.el-radio-button {
    margin-right: 8px;
    box-shadow: none;
    border-radius: 4px !important;
    border: 1px solid #d9d9d9 !important;
  }
</style>
./MapBase/useCameraMap ./MapBase/CameraMapBak ./usePageConfig1
