<template>
  <div class="meta2d">
    <div class="tools">
      <t-tooltip content="新建" placement="bottom">
        <a><t-icon name="add" @click="newFile" /></a>
      </t-tooltip>
      <t-tooltip content="保存为大屏" placement="bottom">
        <a>
          <t-badge
            :style="{
              color: canSave ? '' : '#4f5b75',
              cursor: canSave ? '' : 'not-allowed',
            }"
            dot
            :showZero="false"
            :count="dot ? 1 : 0"
          >
            <t-icon
              name="save"
              @click="canSave && save(SaveType.Save, false, true)" /></t-badge
        ></a>
      </t-tooltip>
      <t-tooltip content="保存为我的组件" placement="bottom">
        <a
          :style="{
            color: canSaveComponent ? '' : '#4f5b75',
            cursor: canSaveComponent ? '' : 'not-allowed',
          }"
          ><t-icon
            name="layers"
            @click="canSaveComponent && save(SaveType.Save, true, true)"
        /></a>
      </t-tooltip>
      <t-tooltip content="格式化（双击可连续使用）" placement="bottom">
        <a
          @click="oneFormat"
          @dblclick="alwaysFormat"
          :style="{
            color: one || always ? ' #1677ff' : '',
          }"
        >
          <svg
            width="1em"
            height="1em"
            viewBox="0 0 256 256"
            xmlns="http://www.w3.org/2000/svg"
            xmlns:xlink="http://www.w3.org/1999/xlink"
          >
            <defs>
              <path id="77456364" d="M0 0h256v256H0z"></path>
            </defs>
            <g fill="none" fill-rule="evenodd">
              <mask id="3804093554b" fill="#fff">
                <use xlink:href="#77456364"></use>
              </mask>
              <path
                d="M213 77c0 14.36-11.64 26-26 26H69c-14.36 0-26-11.64-26-26V51c0-14.36 11.64-26 26-26h118c14.36 0 26 11.64 26 26v2h9.125c9.83 0 17.82 7.88 17.997 17.67l.003.33v50c0 9.83-7.88 17.82-17.67 17.997l-.33.003h-84.626v18H139c9.83 0 17.82 7.88 17.997 17.67l.003.33v35c0 16.016-12.984 29-29 29-15.856 0-28.74-12.725-28.996-28.52L99 210v-35c0-9.83 7.88-17.82 17.67-17.997L117 157h.499l.001-20c0-9.83 7.88-17.82 17.67-17.997l.33-.003h84.625V73H213Zm-76 100h-18v33a9 9 0 0 0 8.471 8.985l.264.011.265.004a9 9 0 0 0 8.996-8.735L137 210v-33Zm50-132H69a6 6 0 0 0-6 6v26a6 6 0 0 0 6 6h118a6 6 0 0 0 6-6V51a6 6 0 0 0-6-6Z"
                fill="currentColor"
                fill-rule="nonzero"
                mask="url(#3804093554b)"
              ></path>
            </g>
          </svg>
        </a>
      </t-tooltip>
      <t-tooltip content="清除格式" placement="bottom">
        <a @click="clearFormat">
          <svg
            width="1em"
            height="1em"
            viewBox="0 0 1024 1024"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M889.186 384.07 677.671 172.56c-53.063-53.063-139.094-53.063-192.157 0L134.617 523.457c-53.063 53.063-53.063 139.099 0 192.158l170.196 170.2a41.354 41.354 0 0 0 29.243 12.11h215.001a41.354 41.354 0 0 0 29.184-12.05L889.155 576.26c53.094-53.09 53.094-139.126.031-192.19zM830.7 442.558c20.48 20.472 20.764 53.492.855 74.319l-.961.984-298.618 297.358H351.185l-158.09-158.086c-20.76-20.763-20.76-54.43 0-75.193l350.901-350.897c20.764-20.764 54.43-20.764 75.193 0l211.515 211.511z"
              fill="currentColor"
            ></path>
            <path
              d="m685.505 678.754-58.19 58.77-317.587-314.43 58.191-58.774zm197.55 136.508c23.46 0 42.483 18.514 42.483 41.353 0 22.45-18.38 40.724-41.294 41.338l-1.19.016h-454.6c-23.462 0-42.485-18.514-42.485-41.354 0-22.449 18.381-40.723 41.295-41.338l1.19-.015h454.6z"
              fill="currentColor"
            ></path>
          </svg>
        </a>
      </t-tooltip>
      <div class="flex-grow"></div>

      <t-tooltip content="直线" placement="bottom">
        <a
          :draggable="true"
          @dragstart="onAddShape($event, 'line')"
          @click.stop="onAddShape($event, 'line')"
          ><t-icon name="slash"
        /></a>
      </t-tooltip>
      <t-tooltip content="文字" placement="bottom">
        <a
          :draggable="true"
          @dragstart="onAddShape($event, 'text')"
          @click.stop="onAddShape($event, 'text')"
          >T</a
        >
      </t-tooltip>
      <t-tooltip content="连线（双击可连续使用）" placement="bottom">
        <a
          @click="oneDraw"
          @dblclick="alwaysDraw"
          :style="{
            color: oneD || alwaysD ? ' #1677ff' : '',
          }"
        >
          <svg
            width="1em"
            height="1em"
            viewBox="0 0 1024 1024"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M192 64a128 128 0 0 1 123.968 96H384a160 160 0 0 1 159.68 149.504L544 320v384a96 96 0 0 0 86.784 95.552L640 800h68.032a128 128 0 1 1 0 64.064L640 864a160 160 0 0 1-159.68-149.504L480 704V320a96 96 0 0 0-86.784-95.552L384 224l-68.032 0.064A128 128 0 1 1 192 64z m640 704a64 64 0 1 0 0 128 64 64 0 0 0 0-128zM192 128a64 64 0 1 0 0 128 64 64 0 0 0 0-128z"
              fill="currentColor"
            ></path>
          </svg>
        </a>
      </t-tooltip>
      <t-dropdown
        :minColumnWidth="200"
        :maxHeight="560"
        :delay2="[10, 150]"
        overlayClassName="header-dropdown"
      >
        <a>
          <svg class="l-icon" aria-hidden="true">
            <use
              :xlink:href="
                lineTypes.find((item) => item.value === currentLineType)?.icon
              "
            ></use>
          </svg>
        </a>
        <t-dropdown-menu>
          <t-dropdown-item v-for="item in lineTypes">
            <div class="flex middle" @click="changeLineType(item.value)">
              {{ item.name }} <span class="flex-grow"></span>
              <svg class="l-icon" aria-hidden="true">
                <use :xlink:href="item.icon"></use>
              </svg>
            </div>
          </t-dropdown-item>
        </t-dropdown-menu>
      </t-dropdown>
      <t-dropdown
        :minColumnWidth="200"
        :maxHeight="560"
        :delay2="[10, 150]"
        overlayClassName="header-dropdown"
      >
        <a>
          <svg class="l-icon" aria-hidden="true">
            <use
              :xlink:href="
                fromArrows.find((item) => item.value === fromArrow)?.icon
              "
            ></use>
          </svg>
        </a>
        <t-dropdown-menu>
          <t-dropdown-item v-for="item in fromArrows">
            <div
              class="flex middle"
              style="height: 30px"
              @click="changeFromArrow(item.value)"
            >
              <svg class="l-icon" aria-hidden="true">
                <use :xlink:href="item.icon"></use>
              </svg>
            </div>
          </t-dropdown-item>
        </t-dropdown-menu>
      </t-dropdown>
      <t-dropdown
        :minColumnWidth="200"
        :maxHeight="560"
        :delay2="[10, 150]"
        overlayClassName="header-dropdown"
      >
        <a>
          <svg class="l-icon" aria-hidden="true">
            <use
              :xlink:href="
                toArrows.find((item) => item.value === toArrow)?.icon
              "
            ></use>
          </svg>
        </a>
        <t-dropdown-menu>
          <t-dropdown-item v-for="item in toArrows">
            <div
              class="flex middle"
              style="height: 30px"
              @click="changeToArrow(item.value)"
            >
              <svg class="l-icon" aria-hidden="true">
                <use :xlink:href="item.icon"></use>
              </svg>
            </div>
          </t-dropdown-item>
        </t-dropdown-menu>
      </t-dropdown>
      <!-- </t-tooltip> -->
      <t-tooltip content="视图大小" placement="bottom">
        <div style="line-height: 40px; margin-left: 8px">{{ scale }}%</div>
      </t-tooltip>

      <t-tooltip content="100%视图" placement="bottom">
        <a @click="onScaleView"><t-icon name="refresh" /></a>
      </t-tooltip>
      <t-tooltip content="窗口大小" placement="bottom">
        <a @click="onScaleWindow"><t-icon name="fullscreen-exit" /></a>
      </t-tooltip>
      <t-tooltip content="数据源" placement="bottom">
        <a @click="onShowDataDialog"><t-icon name="server" /></a>
      </t-tooltip>

      <div class="flex-grow"></div>
      <t-tooltip :content="isLock ? '浏览模式' : '编辑模式'" placement="bottom">
        <a>
          <svg
            v-if="isLock"
            class="l-icon"
            aria-hidden="true"
            @click="onLock(0)"
          >
            <use xlink:href="#l-lock"></use>
          </svg>
          <svg v-else class="l-icon" aria-hidden="true" @click="onLock(1)">
            <use xlink:href="#l-unlock"></use>
          </svg>
        </a>
      </t-tooltip>
      <t-tooltip content="运行（查看）" placement="bottom">
        <a @click="preview"><t-icon name="caret-right" /></a>
      </t-tooltip>
      <t-tooltip content="分享" placement="bottom">
        <a @click="share">
          <t-icon name="share" :class="{ primary: shared }" />
        </a>
      </t-tooltip>
      <t-popup placement="bottom" v-model="qrcode.visible">
        <a><t-icon name="qrcode" /></a>
        <template #content>
          <div style="padding: 12px 12px 6px 12px">
            <img
              v-if="route.query.id && route.query.component !== 'true'"
              :src="qrcode.url"
            />
            <div
              v-else-if="!route.query.id"
              class="gray center mb-4"
              style="font-size: 10px; margin-bottom: 6px"
            >
              当前项目为本地编辑模式<br />
              请保存为大屏项目后访问
            </div>
            <div
              v-else
              class="gray center mb-4"
              style="font-size: 10px; margin-bottom: 6px"
            >
              仅支持手机访问大屏项目
            </div>
          </div>
        </template>
      </t-popup>

      <t-tooltip content="云发布" placement="bottom">
        <a @click="onShowPublish"><t-icon name="cloud" /></a>
      </t-tooltip>
    </div>
    <div id="meta2d"></div>
    <ContextMenu
      :style="{
        left: contextMenuValue.left,
        top: contextMenuValue.top,
      }"
      v-show="contextMenuVisible"
      :type="contextMenuType"
      @changeVisible="changeContextMenuVisible"
    />
    <t-dialog
      v-if="dataDialog.show"
      width="800px"
      header="数据源管理"
      :visible="true"
      @close="dataDialog.show = false"
    >
      <t-tabs :default-value="1" class="body">
        <t-tab-panel :value="1" label="数据订阅" :destroy-on-hide="false">
          <template #panel>
            <div v-if="!dataDialog.editNetwork">
              <t-row class="mt-16" justify="end">
                <t-space :size="12">
                  <t-select-input
                    placeholder="搜索我的数据源"
                    allow-input
                    clearable
                    :popup-visible="dataDialog.popupVisible"
                    @input-change="onInputNetwork"
                    style="width: 240px"
                  >
                    <template #panel>
                      <ul style="padding: 4px">
                        <li
                          class="hover-background"
                          style="
                            line-height: 1.5;
                            padding: 8px;
                            border-radius: 2px;
                          "
                          v-for="item in dataDialog.networkList"
                          :key="item.url"
                          @click="() => onSelectNetWork(item)"
                        >
                          名称: {{ item.name }}
                          <div class="desc">地址: {{ item.url }}</div>
                        </li>
                        <li
                          v-if="!dataDialog.networkList.length"
                          style="
                            line-height: 1.5;
                            padding: 8px;
                            border-radius: 2px;
                          "
                          :key="-1"
                        >
                          <div class="desc">暂无数据</div>
                        </li>
                      </ul>
                    </template>
                    <template #suffixIcon>
                      <t-icon name="search" class="hover" />
                    </template>
                  </t-select-input>
                  <t-button style="height: 30px" @click="addNetwork">
                    添加数据订阅
                  </t-button>
                </t-space>
              </t-row>
              <t-table
                class="mt-12"
                row-key="id"
                :data="dataDialog.networks"
                :columns="networkColumns"
                :max-height="280"
                size="small"
              >
                <template #actions="{ row, rowIndex }">
                  <a @click="editNetwork(row)"> 编辑 </a>
                  <t-popconfirm
                    content="确认删除吗"
                    @confirm="deleteNetwork(rowIndex)"
                  >
                    <a class="ml-12"> 删除 </a>
                  </t-popconfirm>
                </template>
                <template #empty>
                  <div class="center">
                    <div>暂无数据</div>
                    <div class="mt-8">
                      <a @click="addNetwork"> + 添加数据订阅</a>
                    </div>
                  </div>
                </template>
              </t-table>
            </div>
            <div v-else>
              <div class="mt-8">
                <a
                  @click="dataDialog.editNetwork = false"
                  class="flex middle"
                  style="width: 44px"
                >
                  <t-icon name="rollback" class="mr-4" /> 返回
                </a>
              </div>
              <div style="height: 300px; overflow-y: auto">
                <Network v-model="dataDialog.network" />
              </div>
            </div>
          </template>
        </t-tab-panel>
        <t-tab-panel :value="2" :destroy-on-hide="false">
          <template #label>
            数据集
            <span><label class="vip-label ml-4">VIP</label></span>
          </template>
          <template #panel>
            <div class="form-item mt-12">
              <label>网络地址</label>
              <div class="w-full">
                <t-input v-model="dataDialog.datasetUrl" />
                <div class="desc mt-4">
                  高优先级。存在网络地址时，用网络数据代替自定义数据
                </div>
              </div>
            </div>
            <div class="form-item mt-16">
              <label>自定义</label>
              <div class="w-full">
                <t-button @click="importDataset">从Excel导入</t-button>
                <a href="/data.xlsx" download class="ml-16">下载Excel示例</a>
                <span class="desc ml-16">
                  “自定义”数据集 - 方便构建项目时了解数据结构
                </span>
              </div>
            </div>

            <t-table
              class="mt-12"
              row-key="id"
              :data="dataDialog.dataset"
              :columns="datasetColumns"
              size="small"
              :max-height="210"
            >
              <template #label="{ row }">
                {{ `${row.label}(${row.key})` }}
              </template>
              <template #actions="{ row }"> </template>
              <template #empty>
                <div class="center">
                  <div>暂无数据</div>
                  <div class="mt-8">
                    <a @click="importDataset"> 从Excel导入</a>
                  </div>
                </div>
              </template>
            </t-table>
          </template>
        </t-tab-panel>
      </t-tabs>

      <template #footer>
        <div v-if="dataDialog.editNetwork" class="flex middle">
          <div class="flex-grow"></div>
          <t-checkbox v-model="dataDialog.save">
            同时保存到我的数据源
          </t-checkbox>
          <t-button class="ml-16" @click="onOkNetwork">确定</t-button>
        </div>
        <div v-else class="flex middle">
          <div class="flex-grow"></div>
          <t-button class="ml-16" @click="dataDialog.show = false">
            完成
          </t-button>
        </div>
      </template>
    </t-dialog>

    <t-dialog
      v-if="publishDialog.show"
      width="700px"
      header="云发布"
      :visible="true"
      :cancel-btn="null"
      :confirm-btn="'完成'"
      @close="publishDialog.show = false"
    >
      <div class="body" style="height: 350px">
        <div class="form-item mt-8">
          <label>项目名称</label>
          <div class="flex middle">
            <t-icon name="laptop" class="mr-8" /> {{ publishDialog.name }}
          </div>
        </div>
        <template v-if="publishDialog.data">
          <div class="form-item mt-8">
            <label>发布状态</label>
            <div v-if="publishDialog.data.id" class="flex middle">
              <div v-if="publishDialog.data.isExpired" class="warning">
                <t-icon name="stop-circle-1" class="mr-4" />
                已过期
              </div>
              <div v-else class="primary">
                <t-icon name="play-circle" class="mr-4" />
                正在运行
              </div>
              <div class="gray" style="margin-left: 32px; margin-top: -2px">
                有效期至：{{ publishDialog.data.expired }}
              </div>
              <a class="bland ml-12" @click="publishChargeDialog.show = true">
                续费
              </a>
            </div>
            <div v-else class="flex middle">
              <t-icon name="play-circle-stroke" class="mr-4" />
              未发布
            </div>
          </div>
          <div class="form-item mt-16">
            <label>乐吾乐域名</label>
            <div class="flex w-full">
              <t-input
                v-model="publishDialog.data.subDomain"
                :maxlength="16"
                :status="publishDialog.status"
                :tips="publishDialog.tips"
                class="mr-4"
                style="width: 350px"
                placeholder="子域名"
                @change="onChangeSubdomain"
              />
              <t-tooltip content="随机生成">
                <t-icon
                  name="refresh"
                  class="hover"
                  @click="refreshSubdomain"
                />
              </t-tooltip>
              <div class="mt-4 ml-16">v.le5le.com</div>
            </div>
          </div>
          <div class="form-item mt-24">
            <label>访问域名</label>
            <div class="w-full">
              <div class="flex middle">
                <t-input
                  v-model="publishDialog.data.domain"
                  style="width: 350px"
                  placeholder="支持自定义域名"
                />

                <template v-if="publishDialog.data.domain">
                  <a
                    :href="`http://${publishDialog.data.domain}`"
                    target="_blank"
                    class="hover"
                    style="margin-left: 36px; text-decoration: underline"
                  >
                    点击访问
                  </a>

                  <t-popup
                    placement="bottom"
                    v-model="publishDialog.qrcodeVisible"
                  >
                    <a class="hover" style="margin-left: 32px">
                      <t-icon name="qrcode" />
                      <span
                        style="margin-left: 2px; position: relative; top: 1px"
                      >
                        手机访问
                      </span>
                    </a>
                    <template #content>
                      <div style="padding: 12px 12px 6px 12px">
                        <img :src="publishDialog.url" />
                      </div>
                    </template>
                  </t-popup>
                </template>
              </div>
              <div class="desc mt-12">
                <div class="title desc">- 注意</div>
                <div>仅支持48小时免费试用，到期后需要续费使用。</div>
              </div>
              <div class="desc mt-8">
                <div class="title desc">- 自定义域名</div>
                <div>
                  在域名服务商的DNS控制台设置好对应的CNAME，值为乐吾乐域名。
                  <a
                    href="https://doc.le5le.com/document/126505408"
                    target="_blank"
                  >
                    更多帮助
                  </a>
                </div>
              </div>
            </div>
          </div>
          <div class="form-item mt-16">
            <label></label>
            <div class="w-full">
              <t-button @click="onPublish">发布</t-button>
            </div>
          </div>
        </template>
        <div v-else class="flex center" style="margin-top: 32px">
          <t-loading text="加载中..." size="small"></t-loading>
        </div>
      </div>
    </t-dialog>

    <t-dialog
      v-if="publishChargeDialog.show"
      v-model:visible="publishChargeDialog.show"
      header="云发布续费"
      :close-on-overlay-click="false"
      :width="700"
      :footer="false"
    >
      <ChargeCloudPublish
        :projectId="publishDialog.id"
        @success="onSuccessChargeCloud"
      />
    </t-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, watch, ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import {
  Meta2d,
  Options,
  Pen,
  deepClone,
  PenType,
  HoverType,
} from '@meta2d/core';
import localforage from 'localforage';
import dayjs from 'dayjs';
import QRCode from 'qrcode';
import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';

import { registerBasicDiagram } from '@/services/register';
import { useUser } from '@/services/user';
import { cdn, getLe5leV, updateCollection } from '@/services/api';
import {
  save,
  autoSave,
  newFile,
  SaveType,
  onScaleView,
  onScaleWindow,
  useDot,
} from '@/services/common';
import { useSelection } from '@/services/selections';
import { defaultFormat } from '@/services/defaults';
import { checkData, localStorageName, Meta2dBackData } from '@/services/utils';
import { debounce } from '@/services/debouce';
import { importExcel } from '@/services/excel';
import { s8 } from '@/services/random';

import ContextMenu from './ContextMenu.vue';
import Network from './Network.vue';
import ChargeCloudPublish from './ChargeCloudPublish.vue';

const router = useRouter();
const route = useRoute();
const { user } = useUser();
const { dot, setDot } = useDot();
const { select } = useSelection();

const meta2dOptions: Options = {
  cdn,
  rule: true,
  background: '#1e2430',
  x: 32,
  y: 32,
  width: 1920,
  height: 1080,
  color: '#bdc7db',
  disableAnchor: true,
  defaultFormat: { ...defaultFormat },
};

let timer: any = 0;

const shared = ref<boolean>(false);
const qrcode = reactive({
  visible: false,
  url: '',
});

const publishDialog = reactive<any>({});

const publishChargeDialog = reactive<any>({});

onMounted(() => {
  meta2d = new Meta2d('meta2d', meta2dOptions);
  registerBasicDiagram();
  open(true);
  saveStatusChange();
  // @ts-ignore
  meta2d.on('active', active);
  // @ts-ignore
  meta2d.on('inactive', inactive);
  // @ts-ignore
  meta2d.on('scale', scaleListener);
  // @ts-ignore
  meta2d.on('add', lineAdd);
  meta2d.on('opened', openedListener);

  meta2d.on('undo', patchFlag);
  meta2d.on('redo', patchFlag);
  meta2d.on('add', patchFlag);
  meta2d.on('delete', patchFlag);
  meta2d.on('rotatePens', patchFlag);
  meta2d.on('translatePens', patchFlag);

  // 所有编辑栏所做修改
  meta2d.on('components-update-value', patchFlag);
  // @ts-ignore
  meta2d.on('contextmenu', contextmenu);
  meta2d.on('click', canvasClick);

  timer = setInterval(autoSave, 60000);
});

const watcher = watch(
  () => route.query,
  async () => {
    open();
    saveStatusChange();
  }
);

const canSave = ref(true);
const canSaveComponent = ref(true);

const saveStatusChange = () => {
  if (route.query.id) {
    if (route.query.component === 'true') {
      canSave.value = false;
    } else if (route.query.component === 'false') {
      canSaveComponent.value = false;
    } else {
      canSaveComponent.value = false;
    }
  } else {
    canSave.value = true;
    canSaveComponent.value = true;
  }
};

const open = async (flag: boolean = false) => {
  if (route.query.id) {
    const ret: any = await getLe5leV(route.query.id + '');
    if (ret) {
      meta2d.open(ret);
      shared.value = ret.shared;

      const qr: any = await QRCode.toDataURL(
        `https://view2d.le5le.com/?id=${route.query.id + ''}`
      );
      qrcode.url = qr;
    }
  } else {
    if (flag) {
      const data: string = await localforage.getItem(localStorageName);
      if (data) {
        meta2d.open(JSON.parse(data));
      }
    } else {
      meta2d.open({ pens: [] } as any);
    }
  }
  !meta2d.store.data.x && (meta2d.store.data.x = meta2d.store.options.x || 0);
  !meta2d.store.data.y && (meta2d.store.data.y = meta2d.store.options.y || 0);
};

const openedListener = () => {
  const {
    locked,
    scale: canvasScale,
    fromArrow: canvasFromArrow,
    toArrow: canvasToArrow,
  } = meta2d.store.data;
  isLock.value = locked || 0;
  scale.value = Math.round(canvasScale * 100);
  fromArrow.value = canvasFromArrow || '';
  toArrow.value = canvasToArrow || '';
};

const patchFlag = () => {
  setDot(true);
};

onUnmounted(() => {
  clearInterval(timer);
  watcher();
  if (meta2d) {
    // @ts-ignore
    meta2d.off('active', active);
    // @ts-ignore
    meta2d.off('inactive', inactive);
    // @ts-ignore
    meta2d.off('scale', scaleListener);
    // @ts-ignore
    meta2d.off('add', lineAdd);
    meta2d.on('opened', openedListener);

    meta2d.off('undo', patchFlag);
    meta2d.off('redo', patchFlag);
    meta2d.off('add', patchFlag);
    meta2d.off('delete', patchFlag);
    meta2d.off('rotatePens', patchFlag);
    meta2d.off('translatePens', patchFlag);
    meta2d.off('components-update-value', patchFlag);
    // @ts-ignore
    meta2d.off('contextmenu', contextmenu);
    meta2d.off('click', canvasClick);

    meta2d.destroy();
  }
});

const inactive = () => {
  select();
};

const active = (pens: Pen[]) => {
  select(pens);

  //格式刷处理
  if (one.value || always.value) {
    meta2d.formatPainter();
    one.value = false;
  }
};

const one = ref(false);
const always = ref(false);

const oneFormat = () => {
  if (one.value) {
    one.value = false;
  } else {
    one.value = true;
    meta2d.setFormatPainter();
  }
  if (always.value) {
    always.value = false;
    one.value = false;
  }
};

const alwaysFormat = () => {
  always.value = true;
};

const clearFormat = () => {
  always.value = false;
  one.value = false;
  meta2d.clearFormatPainter();
};

const scale = ref(100);
function scaleListener(newScale: number) {
  scale.value = Math.round(newScale * 100);
}

const dataDialog = reactive<any>({});

const currentLineType = ref('curve');
const lineTypes = reactive([
  { name: '曲线', icon: '#l-curve2', value: 'curve' },
  { name: '线段', icon: '#l-polyline', value: 'polyline' },
  { name: '直线', icon: '#l-line', value: 'line' },
  { name: '脑图曲线', icon: '#l-mind', value: 'mind' },
]);

const changeLineType = (value: string) => {
  currentLineType.value = value;
  if (meta2d) {
    meta2d.store.options.drawingLineName = value;
    meta2d.canvas.drawingLineName && (meta2d.canvas.drawingLineName = value);
    meta2d.store.active?.forEach((pen) => {
      meta2d.updateLineType(pen, value);
    });
  }
};

const fromArrow = ref('');
const fromArrows = [
  { icon: '#l-line', value: '' },
  { icon: '#l-from-triangle', value: 'triangle' },
  { icon: '#l-from-diamond', value: 'diamond' },
  { icon: '#l-from-circle', value: 'circle' },
  { icon: '#l-from-lineDown', value: 'lineDown' },
  { icon: '#l-from-lineUp', value: 'lineUp' },
  { icon: '#l-from-triangleSolid', value: 'triangleSolid' },
  { icon: '#l-from-diamondSolid', value: 'diamondSolid' },
  { icon: '#l-from-circleSolid', value: 'circleSolid' },
  { icon: '#l-from-line', value: 'line' },
];
const toArrow = ref('');
const toArrows = [
  { icon: '#l-line', value: '' },
  { icon: '#l-to-triangle', value: 'triangle' },
  { icon: '#l-to-diamond', value: 'diamond' },
  { icon: '#l-to-circle', value: 'circle' },
  { icon: '#l-to-lineDown', value: 'lineDown' },
  { icon: '#l-to-lineUp', value: 'lineUp' },
  { icon: '#l-to-triangleSolid', value: 'triangleSolid' },
  { icon: '#l-to-diamondSolid', value: 'diamondSolid' },
  { icon: '#l-to-circleSolid', value: 'circleSolid' },
  { icon: '#l-to-line', value: 'line' },
];

const changeFromArrow = (value: string) => {
  fromArrow.value = value;
  // 画布默认值
  meta2d.store.data.fromArrow = value;
  // 活动层的箭头都变化
  if (meta2d.store.active) {
    meta2d.store.active.forEach((pen: Pen) => {
      if (pen.type === PenType.Line) {
        pen.fromArrow = value;
        meta2d.setValue(
          {
            id: pen.id,
            fromArrow: pen.fromArrow,
          },
          {
            render: false,
          }
        );
      }
    });
    meta2d.render();
  }
};

const changeToArrow = (value: string) => {
  toArrow.value = value;
  // 画布默认值
  meta2d.store.data.toArrow = value;
  // 活动层的箭头都变化
  if (meta2d.store.active) {
    meta2d.store.active.forEach((pen: Pen) => {
      if (pen.type === PenType.Line) {
        pen.toArrow = value;
        meta2d.setValue(
          {
            id: pen.id,
            toArrow: pen.toArrow,
          },
          {
            render: false,
          }
        );
      }
    });
    meta2d.render();
  }
};

const oneD = ref<boolean>(false);
const alwaysD = ref<boolean>(false);
const oneDraw = () => {
  if (oneD.value) {
    oneD.value = false;
    if (!alwaysD.value) {
      meta2d.finishDrawLine();
      meta2d.drawLine();
      meta2d.store.options.disableAnchor = true;
    }
  } else {
    oneD.value = true;
    meta2d.drawLine(meta2d.store.options.drawingLineName);
    meta2d.store.options.disableAnchor = false;
  }
  if (alwaysD.value) {
    meta2d.finishDrawLine();
    meta2d.drawLine();
    oneD.value = false;
    alwaysD.value = false;
    meta2d.store.options.disableAnchor = true;
  }
};
const alwaysDraw = () => {
  alwaysD.value = true;
  meta2d.drawLine(meta2d.store.options.drawingLineName);
  meta2d.store.options.disableAnchor = false;
};

const lineAdd = (pens: Pen[]) => {
  if (pens.length === 1 && pens[0].name === 'line') {
    //连线类型
    if (oneD.value && !alwaysD.value) {
      if (meta2d.canvas.drawingLineName) {
        oneD.value = false;
        setTimeout(() => {
          meta2d.finishDrawLine();
          meta2d.drawLine();
          meta2d.store.options.disableAnchor = true;
        }, 100);
      }
    }
  }
};

const onAddShape = (event: DragEvent | MouseEvent, name: string) => {
  let data: any;
  if (name === 'text') {
    data = {
      text: 'text',
      width: 100,
      height: 20,
      name: 'text',
    };
  } else if (name === 'line') {
    data = {
      anchors: [
        { id: '0', x: 0, y: 0.5 },
        { id: '1', x: 1, y: 0.5 },
      ],
      width: 100,
      height: 1,
      name: 'line',
      lineName: 'line',
      type: 1,
    };
  }
  if (!(event as DragEvent).dataTransfer) {
    meta2d.canvas.addCaches = deepClone([data]);
  } else {
    (event as DragEvent).dataTransfer?.setData('Meta2d', JSON.stringify(data));
  }
  event.stopPropagation();
};

const isLock = ref(0);
function onLock(lock: number) {
  isLock.value = lock;
  meta2d.lock(lock);
  meta2d.hideInput();
}

const preview = async () => {
  meta2d.stopAnimate();
  // @ts-ignore
  const data: Meta2dBackData = meta2d.data();
  checkData(data);
  if (dot && user && data._id) {
    // 有 id ，是修改后保存
    await save(SaveType.Save);
  }
  if (!data._id) {
    await localforage.setItem(localStorageName, JSON.stringify(data));
  }
  router.push({
    path: '/preview',
    query: {
      r: Date.now() + '',
      id: data._id,
    },
  });
};

const contextMenuVisible = ref(false);
const contextMenuValue = ref({
  left: '0px',
  top: '0px',
});
const contextMenuType = ref('');

const contextmenu = ({ e, rect }: { e: any; rect: any }) => {
  contextMenuType.value = '';
  contextMenuValue.value.left = e.clientX + 'px';
  contextMenuValue.value.top = e.clientY + 'px';
  if (
    meta2d.store.hoverAnchor &&
    meta2d.canvas.hoverType === HoverType.LineAnchor
  ) {
    contextMenuType.value = 'anchor';
  } else {
    //其他右键菜单
    contextMenuType.value = 'pen';
  }

  if (!contextMenuVisible.value && contextMenuType.value) {
    contextMenuVisible.value = true;
  }
  if (!contextMenuType.value) {
    contextMenuVisible.value = false;
  }
};

const canvasClick = () => {
  contextMenuVisible.value = false;
};

const changeContextMenuVisible = (e: boolean) => {
  contextMenuVisible.value = e;
};

const networkColumns = ref([
  {
    colKey: 'name',
    title: '名称',
    ellipsis: true,
    width: 160,
  },
  {
    colKey: 'type',
    title: '类型',
    width: 120,
  },
  {
    colKey: 'url',
    title: 'URL地址',
    ellipsis: true,
  },
  { colKey: 'actions', title: '操作', width: 100 },
]);

const onShowDataDialog = () => {
  // @ts-ignore
  dataDialog.networks = meta2d.store.data.networks || [];
  // @ts-ignore
  dataDialog.dataset = meta2d.store.data.dataset;
  dataDialog.networkList = [];
  dataDialog.editNetwork = false;
  dataDialog.save = true;
  dataDialog.show = true;
  getNetworks();
};

const onSelectNetWork = (item: any) => {
  dataDialog.networks.push(item);
  dataDialog.popupVisible = false;
};

const onInputNetwork = (text: string) => {
  debounce(getNetworks, 300);
};

// 请求我的数据源接口
const getNetworks = async () => {
  // const ret: any = await axios.get(`/api/xxx`);
  // if (ret) {
  //   dataDialog.networkList = ret.list
  // }
};

const addNetwork = () => {
  dataDialog.network = {
    name: '',
    type: '',
    url: '',
    options: {
      clientId: '',
      username: '',
      password: '',
      customClientId: false,
    },
  };
  dataDialog.editNetwork = 1;
};

const editNetwork = (data: any) => {
  dataDialog.network = data;
  dataDialog.editNetwork = 2;
};

const deleteNetwork = (index: number) => {
  dataDialog.networks.splice(index, 1);
  meta2d.connectSocket();
};

const onOkNetwork = () => {
  if (dataDialog.editNetwork === 1) {
    dataDialog.networks.push(dataDialog.network);
  }
  dataDialog.editNetwork = false;

  // 保存到我的数据源
  if (dataDialog.save) {
    // todo
  }
};

const datasetColumns = ref([
  {
    colKey: 'label',
    title: '名称（数据ID）',
    ellipsis: true,
  },
  {
    colKey: 'type',
    title: '类型',
    ellipsis: true,
  },
  {
    colKey: 'value',
    title: '值',
    ellipsis: true,
  },
]);

const importDataset = async () => {
  let columns: any = [
    {
      header: '名称',
      key: 'label',
    },
    {
      header: '数据ID',
      key: 'key',
    },
    {
      header: '类型',
      key: 'type',
    },
    {
      header: '场景',
      key: 'case',
    },
    {
      header: '值',
      key: 'value',
    },
  ];
  const data: any = await importExcel(columns);
  dataDialog.dataset = data;
};

const share = async () => {
  if (!route.query.id) {
    MessagePlugin.error('请先保存！');
    return;
  }

  const ret: any = await updateCollection('le5leV', {
    _id: route.query.id,
    shared: !shared.value,
  });
  if (ret) {
    shared.value = ret.shared;
  }
};

let qrTimer: any;
const onEnterQrcode = () => {
  if (!qrcode.visible && !qrTimer) {
    qrTimer = setTimeout(() => {
      qrTimer = undefined;
      qrcode.visible = true;
    }, 300);
  }
};

const onLeaveQrcode = () => {
  if (qrTimer) {
    clearTimeout(qrTimer);
    qrTimer = undefined;
  }
};

const onShowPublish = async () => {
  // @ts-ignore
  publishDialog.name = meta2d.store.data.name;
  publishDialog.status = '';
  publishDialog.tips = '';
  publishDialog.id = route.query.id + '';
  publishDialog.show = true;

  const ret: any = await axios.post(`/api/domain/get`, {
    id: publishDialog.id,
  });
  if (ret) {
    if (ret.expired) {
      const expired = new Date(ret.expired);
      if (expired > new Date()) {
        ret.isExpired = false;
      } else if (expired > new Date('2023-01-17T08:00:00+08:00')) {
        ret.isExpired = true;
      } else {
        ret.expired = undefined;
      }
      if (ret.expired) {
        ret.expired = dayjs(ret.expired).format('YYYY-MM-DD HH:mm:ss');
      }
    }
    publishDialog.data = ret;
    makePublishQrcode();
  }
};

const refreshSubdomain = async () => {
  publishDialog.data.subDomain = s8();
  onChangeSubdomain();
};

const onChangeSubdomain = async () => {
  if (!publishDialog.data.subDomain) {
    publishDialog.status = 'error';
    publishDialog.tips = '请填写子域名';
  }
  const ret: any = await axios.post(`/api/domain/exists`, {
    subDomain: publishDialog.data.subDomain,
  });
  if (ret && ret.id) {
    publishDialog.status = 'error';
    publishDialog.tips = '已经存在相同子域名';
  } else {
    publishDialog.status = '';
    publishDialog.tips = '';
  }

  if (
    !publishDialog.data.domain ||
    publishDialog.data.domain.indexOf('.v.le5le.com') >= 0
  ) {
    publishDialog.data.domain = publishDialog.data.subDomain + '.v.le5le.com';
  }

  makePublishQrcode();
};

const onPublish = async () => {
  if (publishDialog.status) {
    return;
  }
  if (!publishDialog.data.subDomain) {
    publishDialog.status = 'error';
    publishDialog.tips = '请填写子域名';
  }

  if (!publishDialog.data.domain) {
    publishDialog.data.domain = publishDialog.data.subDomain + '.v.le5le.com';
  }

  const ret: any = await axios.post(`/api/domain/set`, {
    id: route.query.id,
    subDomain: publishDialog.data.subDomain,
    domain: publishDialog.data.domain,
  });
  if (ret) {
    if (ret.expired) {
      const expired = new Date(ret.expired);
      if (expired > new Date()) {
        ret.isExpired = false;
      } else if (expired > new Date('2023-01-17T08:00:00+08:00')) {
        ret.isExpired = true;
      } else {
        ret.expired = undefined;
      }
      if (ret.expired) {
        ret.expired = dayjs(ret.expired).format('YYYY-MM-DD HH:mm:ss');
      }
    }

    publishDialog.data = ret;
    makePublishQrcode();
  }
};

const makePublishQrcode = async () => {
  const qr: any = await QRCode.toDataURL(`http://${publishDialog.data.domain}`);
  publishDialog.url = qr;
};

const onSuccessChargeCloud = () => {
  publishChargeDialog.show = false;
  onShowPublish();
};
</script>
<style lang="postcss" scoped>
.meta2d {
  display: flex;
  flex-direction: column;
  background-color: var(--color-background-editor);
  border-left: 1px solid var(--color-border);

  .tools {
    display: flex;
    font-size: 12px;
    background-color: var(--color-background);
    height: 40px;
    flex-shrink: 0;
    padding: 0 12px;

    a {
      display: flex;
      align-items: center;
      height: 100%;
      padding: 0 10px;
      color: var(--color);
      text-decoration: none;

      .l-icon {
        width: 16px;
        height: 16px;
      }

      &:hover {
        color: var(--color-primary);
      }
    }

    .t-icon {
      font-size: 16px;
    }
  }

  #meta2d {
    border-top: 1px solid var(--color-background-input);
    height: calc(100vh - 81px);

    :deep(.meta2d-map) {
      background: var(--color-background);
    }
  }
}
</style>
