<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> -->
          <el-select
            v-model="selectedCompany"
            class="m-2"
            placeholder="请选择相关公司"
            style="width: 216px"
            @change="changeCompany"
          >
            <el-option
              v-for="item in scenesInfos"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div v-if="selectedCompany" style="display: flex">
          <div class="label-workshop">选择标签:</div>
          <div>
            <el-radio-group
              v-model="label"
              :border="true"
              style="display: flex"
              @change="changeShop"
            >
              <el-radio-button
                v-for="item in labelList"
                :key="item.id"
                :label="item.id!"
                class="label-select"
                >{{ item.name }}</el-radio-button
              >
            </el-radio-group></div
          >
        </div>
        <div class="flex">
          <!-- <el-button @click="toJson">tojson</el-button> -->
          <el-upload
            class="avatar-uploader flex justify-center items-center"
            action="/skyeye-admin-api/homepageConfig/updateCompanyPicture"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="handleBeforeUpload"
            :with-credentials="true"
            name="file"
            :data="{ companyId: selectedCompany, labelId: label, deleteFileName: bgImg }"
            :headers="getHeaders()"
          >
            <el-button :icon="Refresh" :disabled="!hasBg"> 替换照片 </el-button>
          </el-upload>

          <el-button
            @click="handleSave"
            style="margin-left: 40px"
            type="primary"
            :disabled="!selectedCompany && !label"
            >保存为布局
          </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="filterShopList.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 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>
          <MapContainer ref="mapContainerRef" @on-open="openConfig" />
        </div>
        <el-upload
          v-if="!hasBg"
          class="upload-icon flex justify-center items-center"
          action="/skyeye-admin-api/homepageConfig/uploadCompanyPicture"
          :show-file-list="false"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :with-credentials="true"
          name="file"
          :data="{ companyId: selectedCompany, labelId: label }"
          :headers="getHeaders()"
        >
          <img src="~@/assets/images/img-upload.png" />
        </el-upload>
      </div>
    </div>
    <el-tooltip
      class="box-item position-tooltip"
      effect="dark"
      content="显示侧边栏"
      :offset="12"
      placement="left"
    >
      <div
        v-if="leftShow"
        class="circle-rectangle"
        :class="{ 'shape-shadow': shadow }"
        @mouseover="shadowAdd"
        @mouseout="shadowRemove"
        @click="dialogReopen"
      >
        <el-icon class="left-icon" size="16px"><ArrowLeftBold /></el-icon>
        <el-icon style="margin-top: 7px" size="16px"><ArrowLeftBold /></el-icon>
      </div>
    </el-tooltip>

    <ConfigDialog
      ref="configDrawer"
      @on-close="onClose"
      @transformer-change="transformChange"
      class="drawer-position"
    />

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

<script setup lang="ts">
  import ConfigDialog from './component/ConfigDrawer.vue';
  import ConfigFinish from './component/ConfigFinish.vue';
  import { storeToRefs } from 'pinia';
  import { ElMessage, ElInput } from 'element-plus';
  import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
  import { WorkShopInfoItem } 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 } from '@/api/scene/scene';
  import safeParse from '@/utils/safeParse';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  const getHeaders = () => {
    return { Satoken: userStore.getToken, Tenantid: userStore.getTenantId };
  };

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

  const router = useRouter();

  const pageConfig = usePageConfig();
  const { selectedCompany, scenesInfos, label, labelList, shopList, layoutId } = pageConfig;

  const drawContainer = ref<HTMLDivElement>();
  const mapContainerRef = ref();

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

  const handleBeforeUpload = (rawFile) => {
    if (!selectedCompany.value || !label.value) {
      ElMessage.error({
        message: '请先选择公司和标签',
      });
      return false;
    }
    if (
      rawFile.type !== 'image/jpg' &&
      rawFile.type !== 'image/jpeg' &&
      rawFile.type !== 'image/png'
    ) {
      ElMessage.error('请上传jpg、jpeg、png格式的图片!');
      return false;
    }
  };

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

  //左边的浮动按钮
  const leftShow = ref(true);
  const onClose = (val) => {
    leftShow.value = val;
  };

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

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

  const shadow = ref(false);
  const shadowAdd = () => {
    shadow.value = true;
  };
  const shadowRemove = () => {
    shadow.value = false;
  };

  const configDrawer = ref();
  const dialogReopen = () => {
    configDrawer.value.openDialog();
  };

  const openConfig = () => {
    configDrawer.value.openDialog();
  };

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

  const handleAvatarSuccess = (e) => {
    bgImg.value = e.data;
    hasBg.value = true;
    addBg();
  };

  const changeShop = () => {
    hasBg.value = false;
    resetMap();
    getShopContent();
  };

  const getShopContent = () => {
    getCompanyLayoutApi({ companyId: selectedCompany.value || 2, labelId: label.value || 1 }).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);
      },
    );
  };

  const changeCompany = () => {
    label.value = undefined;
    resetMap();
    hasBg.value = false;
  };

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

  onMounted(() => {
    const routerParams = router.currentRoute.value.query;
    if (routerParams.companyId) {
      selectedCompany.value = Number(routerParams.companyId);
    }
    if (routerParams.labelId) {
      label.value = Number(routerParams.labelId);
    }

    window.addEventListener('keydown', handleKeyDown);

    if (selectedCompany.value && label.value) {
      getShopContent();
    }
  });

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

  const handleAddShop = (shop: WorkShopInfoItem) => {
    //如果已经存在车间，则禁止加入
    const existingCamera = addedShops.value.find((item) => item.id === shop.id);
    if (existingCamera) return;
    // activeShopId.value = shop.id;
    if (!hasBg.value) {
      ElMessage.warning({
        message: '请先添加背景图片',
      });
      return;
    }
    const shopNode = {
      ...shop,
      x: 50,
      y: 50,
      scaleX: 1,
      scaleY: 1,
      bgColor: 'rgba(58, 170, 209, 1)',
      fontSize: 14,
      fontColor: '#ffffff',
      posType: LabelPositionEnum.LEFT,
    };
    addShop(shopNode);
    dialogReopen();
  };

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

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeyDown);
    resetMap();
  });
</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 {
    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;
  }

  .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;
  }

  .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;
  }

  :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
