<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 style="display: flex">
            <div class="label-workshop" style="margin-left: 0px">选择标签:</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> -->
        <div class="top-bar">
          <div class="back-btn" @click="router.back">
            <img src="@/assets/rollback.png" />
            <span>返回</span>
            <div class="company-name">{{ companyName }}</div>
          </div>
          <!-- <el-button @click="toJson">tojson</el-button> -->
          <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"> 替换照片 </el-button>
            </el-upload>

            <el-button :icon="Refresh" @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>
        <!-- <span v-if="filterShopList.length == 0" class="ml-1" style="color: #3f3f3f">
          提示：请先选择相应公司和图片
        </span> -->
        <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"
            :module-code="labelMouduleCode"
            @on-open="openConfig"
          />
        </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" />
        </el-upload>
      </div>
      <div class="shop-tag-edit-area" v-if="hasBg">
        <ShopTagEditArea @transformer-change="transformChange" />
      </div>
    </div>
    <!-- <el-tooltip
      class="box-item position-tooltip"
      effect="dark"
      content="显示侧边栏" 
      :offset="12"
      placement="left"
    >
      <div
        v-if="leftShow && activeShopId && !isMobileView && activeShopId != -1"
        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
      v-if="!isMobileView"
      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, ElSwitch, 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 } 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 { CompanyLayoutType, LayoutType, ShopType } from '@/types/page-config/type';
  import ShopTagEditArea from './component/ShopTagEditArea.vue';

  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 { scenesInfos, label, labelList, layoutId } = pageConfig;
  const { urlPrefix } = 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<number>();

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

  // // mapContainer宽高
  // const mapContainerStageSize = reactive({ height: 0, width: 777 });

  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();
  };

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

  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 labelMouduleCode = computed(() => {
    return (
      scenesInfos.value
        .find((item) => item.id === companyId.value)
        ?.labelModuleList.find((item) => item.sceneLabel.id === label.value)?.sceneModule.code ||
      'default'
    );
  });

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

  const getShopContent = () => {
    // getCompanyLayoutApi({ companyId: selectedCompany.value || 2 }).then((res) => {
    getWorkshopListApi({ companyId: companyId.value! }).then((res) => {
      shopList.value = res;
    });

    getCompanyLayoutApi({
      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);
    });
  };

  // const changeCompany = () => {
  const clearLayout = () => {
    // label.value = undefined;

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

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

  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;
    // activeShopId.value = shop.id;
    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);
    // dialogReopen();
  };

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

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeyDown);
    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);
    }
    // if (routerParams.labelId) {
    //   label.value = Number(routerParams.labelId);
    // }

    window.addEventListener('keydown', handleKeyDown);

    if (companyId.value) {
      getShopContent();
    }

    // console.log('clientHeight', document.getElementById('shopEditContainer')?.clientHeight);
    // console.log('clientWidth', document.getElementById('shopEditContainer')?.clientWidth);
    // mapContainerStageSize.height = document.getElementById('shopEditContainer')?.clientHeight!;
    // mapContainerStageSize.width = document.getElementById('shopEditContainer')?.clientWidth!;
  });
</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;
    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;
    width: calc(100% - 600px);
    margin: 10px;
    overflow: hidden;
    border: 1px solid #1890ff;
  }

  .shop-edit-container {
    height: 100%;
    border: 1px solid #ff7118;
  }

  .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-btn {
      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: 350px;
      display: flex;
      align-items: center;
      .el-button {
        margin-left: 20px;
      }
    }
  }

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

  :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
