<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
            :class="{ gray: route.query.c }"
            dot
            :showZero="false"
            :count="dot ? 1 : 0"
          >
            <t-icon
              name="save"
              @click="!route.query.c && save(SaveType.Save, false, true)"
            />
          </t-badge>
        </a>
      </t-tooltip>
      <t-tooltip content="保存为我的组件" placement="bottom">
        <a :class="{ gray: route.query.id && !route.query.c }">
          <t-icon
            name="layers"
            @click="
              (!route.query.id || route.query.c) &&
                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="onAddShape($event, 'line')"
          ><t-icon name="slash"
        /></a>
      </t-tooltip>
      <t-tooltip content="文字" placement="bottom">
        <a
          :draggable="true"
          @dragstart="onAddShape($event, 'text')"
          @click="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="onScaleFull"><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.c" :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
      v-if="contextmenu.visible"
      :type="contextmenu.type"
      :style="contextmenu.style"
      @changeVisible="changeContextMenuVisible"
    />
    <t-dialog
      v-if="dataDialog.show"
      width="800px"
      header="数据源管理"
      :visible="true"
      @close="dataDialog.show = false"
    >
      <t-tabs v-model="dataDialog.tab" class="body">
        <t-tab-panel :value="1" label="实时数据" :destroy-on-hide="false">
          <template #panel>
            <div v-if="!dataDialog.editNetwork">
              <div class="mt-16 flex between middle">
                <div>
                  <t-checkbox
                    v-model="dataDialog.enableMock"
                    @change="onChangeMock"
                  >
                    开启模拟数据
                  </t-checkbox>
                </div>
                <div>
                  <t-select-input
                    v-model:inputValue="dataDialog.input"
                    placeholder="搜索我的实时数据"
                    allow-input
                    clearable
                    :popup-visible="dataDialog.popupVisible"
                    @focus="dataDialog.popupVisible = true"
                    @blur="dataDialog.popupVisible = undefined"
                    @input-change="onInputNetwork"
                    style="width: 240px"
                  >
                    <template #panel>
                      <ul style="padding: 4px">
                        <li
                          class="hover-background item"
                          v-for="(item, i) in dataDialog.networkList"
                          :key="item.url"
                          @click="onSelectNetWork(item)"
                        >
                          名称: {{ item.name }}
                          <div class="desc">地址: {{ item.url }}</div>
                          <span class="del" @click.stop="onDelNetWork(item, i)">
                            <t-icon name="delete" />
                          </span>
                        </li>
                        <li
                          v-if="dataDialog.networkList.length >= 10"
                          style="
                            line-height: 1.5;
                            padding: 8px;
                            border-radius: 2px;
                          "
                          :key="-1"
                        >
                          <div class="desc">...</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
                    class="ml-12"
                    style="height: 30px"
                    @click="addNetwork"
                  >
                    添加实时数据
                  </t-button>
                </div>
              </div>
              <t-table
                class="mt-12"
                row-key="id"
                :data="dataDialog.networks"
                :columns="networkColumns"
                :max-height="280"
                size="small"
              >
                <template #protocol="{ row, rowIndex }">
                  {{ row.protocol || 'MQTT' }}
                </template>
                <template #actions="{ row, rowIndex }">
                  <a @click="editNetwork(row)"> 编辑 </a>
                  <a class="ml-12" @click="deleteNetwork(rowIndex)"> 删除 </a>
                </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.network = dataDialog.networkBak;
                    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> 数据集 </template>
          <template #panel>
            <template v-if="!dataDialog.editDataset">
              <div class="form-item mt-16">
                <label style="width: 100px"> 当前数据集 </label>
                <div class="flex w-full">
                  <t-select
                    class="flex-grow"
                    v-model="dataDialog.datasetId"
                    filterable
                    placeholder="选择数据集"
                    :on-search="onInputDatasets"
                    :popup-props="{ overlayClassName: 'select-options' }"
                    @change="onSelDataset()"
                  >
                    <t-option
                      v-for="(item, i) in dataDialog.datasetList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    >
                      <div class="hover-background item">
                        名称: {{ item.name }}
                        <div v-if="item.url" class="desc">
                          URL: {{ item.url }}
                        </div>
                        <div v-else class="desc">自定义</div>
                        <span class="del" @click.stop="onDelDataset(item, i)">
                          <t-icon name="delete" />
                        </span>
                      </div>
                    </t-option>
                    <t-option
                      v-if="dataDialog.datasetList.length >= 10"
                      :disabled="true"
                    >
                      <div class="ml-8 gray">...</div>
                    </t-option>
                  </t-select>

                  <t-button
                    class="ml-12 shrink-0"
                    style="height: 30px"
                    @click="addDataset"
                  >
                    添加数据集
                  </t-button>
                </div>
              </div>

              <t-table
                class="mt-12"
                row-key="id"
                :data="dataDialog.dataset.data"
                :columns="datasetColumns"
                size="small"
                :max-height="280"
              >
                <template #type="{ row }">
                  {{ row.type || 'string' }}
                </template>
              </t-table>
            </template>
            <div v-else>
              <div class="mt-8">
                <a
                  @click="
                    dataDialog.dataset = dataDialog.datasetBak;
                    dataDialog.datasetId = dataDialog.dataset.id;
                    dataDialog.editDataset = 0;
                  "
                  class="flex middle"
                  style="width: 44px"
                >
                  <t-icon name="rollback" class="mr-4" /> 返回
                </a>
              </div>
              <div style="height: 300px; overflow-y: auto">
                <Dataset v-model="dataDialog.dataset" />
              </div>
            </div>
          </template>
        </t-tab-panel>
      </t-tabs>

      <template #footer>
        <div
          v-if="dataDialog.tab === 1 && dataDialog.editNetwork"
          class="flex middle"
        >
          <div class="flex-grow"></div>
          <t-checkbox v-model="dataDialog.save" class="mr-12">
            同时保存到我的实时数据
          </t-checkbox>
          <t-button @click="onOkNetwork">确定</t-button>
        </div>
        <div v-else-if="dataDialog.tab === 2" class="flex middle">
          <template v-if="dataDialog.editDataset === 1">
            <div class="flex-grow"></div>
            <t-checkbox v-model="dataDialog.save" class="mr-12">
              同时保存为我的数据集
            </t-checkbox>
            <t-button @click="onOkDataset()">保存</t-button>
          </template>
          <template v-else-if="dataDialog.editDataset === 2">
            <div class="flex-grow"></div>
            <t-button @click="onOkDataset(true)"> 另外为新数据集 </t-button>
            <t-button @click="onOkDataset()">保存</t-button>
          </template>
          <template v-else>
            <a v-if="dataDialog.dataset.id" @click="editDataset">
              编辑当前数据集
            </a>
            <div class="flex-grow"></div>

            <t-button @click="dataDialog.show = false"> 完成 </t-button>
          </template>
        </div>
        <div v-else class="flex middle">
          <div class="flex-grow"></div>
          <t-button @click="onFinishDataDialog"> 完成 </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"
      @confirm="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,
  getComponents,
  getLe5leV,
  updateCollection,
} from '@/services/api';
import {
  save,
  autoSave,
  newFile,
  SaveType,
  onScaleFull,
  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 { s8 } from '@/services/random';
import { setCookie } from '@/services/cookie';

import ContextMenu from './ContextMenu.vue';
import Network from './Network.vue';
import Dataset from './Dataset.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);
  meta2d.on('active', active);
  meta2d.on('inactive', inactive);
  meta2d.on('scale', scaleSubscriber);
  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);
  meta2d.on('contextmenu', onContextmenu);
  meta2d.on('click', canvasClick);

  timer = setInterval(autoSave, 60000);

  window.onbeforeunload = () => {
    autoSave();
  };
});

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

const open = async (flag: boolean = false) => {
  if (route.query.token) {
    localStorage.setItem('token', route.query.token + '');
    setCookie('token', route.query.token + '');
    const newQuery = { ...route.query };
    delete newQuery.token;
    router.replace({
      path: '/',
      query: newQuery,
    });
    return;
  }
  if (route.query.id) {
    let ret: any;
    if (route.query.c) {
      ret = await getComponents(route.query.id + '');
    } else {
      ret = await getLe5leV(route.query.id + '');
    }
    if (ret) {
      meta2d.open(ret);
      if (!route.query.c) {
        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 if (!sessionStorage.getItem('opening')) {
    meta2d.open({ name: '新建项目', pens: [], enableMock: true } as any);
  }
  sessionStorage.removeItem('opening');
  !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();
};

onUnmounted(() => {
  clearInterval(timer);
  watcher();
  if (meta2d) {
    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);
const scaleSubscriber = (val: number) => {
  scale.value = Math.round(val * 100);
};

const dataDialog = reactive<any>({
  tab: 1,
});

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) => {
  event.stopPropagation();
  let data: any;
  if (name === 'text') {
    data = {
      text: 'text',
      width: 100,
      height: 20,
      name: 'text',
    };
  } else if (name === 'line') {
    data = {
      anchors: [
        { id: '0', x: 1, y: 0 },
        { id: '1', x: 0, y: 1 },
      ],
      width: 100,
      height: 100,
      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));
  }
};

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 contextmenu = reactive<any>({
  visible: false,
  type: '',
  style: {},
});

const onContextmenu = ({ e, rect }: { e: any; rect: any }) => {
  contextmenu.type = '';
  contextmenu.style = {
    left: e.clientX + 'px',
    top: e.clientY + 'px',
  };

  if (
    meta2d.store.hoverAnchor &&
    meta2d.canvas.hoverType === HoverType.LineAnchor
  ) {
    contextmenu.type = 'anchor';
    if (document.body.clientHeight - e.clientY < 128) {
      contextmenu.style = {
        left: e.clientX + 'px',
        bottom: '4px',
      };
    }
  } else {
    contextmenu.type = 'pen';
    if (document.body.clientHeight - e.clientY < 450) {
      contextmenu.style = {
        left: e.clientX + 'px',
        bottom: '4px',
      };
    }
  }

  if (contextmenu.type) {
    contextmenu.visible = true;
  } else {
    contextmenu.visible = false;
  }
};

const canvasClick = () => {
  contextmenu.visible = false;
};

const changeContextMenuVisible = (e: boolean) => {
  contextmenu.visible = e;
};

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

const onShowDataDialog = async () => {
  dataDialog.input = '';
  dataDialog.networks = meta2d.store.data.networks || [];
  // @ts-ignore
  dataDialog.dataset = meta2d.store.data.dataset || {};
  dataDialog.datasetId = dataDialog.dataset.id;
  // @ts-ignore
  dataDialog.enableMock = meta2d.store.data.enableMock;
  dataDialog.networkList = [];
  dataDialog.datasetList = [];
  dataDialog.editNetwork = false;
  dataDialog.save = true;
  dataDialog.show = true;
  getNetworks();
  await getDatasets();
  onSelDataset(true);
};

const onFinishDataDialog = () => {
  dataDialog.show = false;
  meta2d.connectNetwork();
};

const onChangeMock = () => {
  // @ts-ignore
  meta2d.store.data.enableMock = dataDialog.enableMock;
};

const onSelectNetWork = (item: any) => {
  const network: any = dataDialog.networks.find(
    (elem: any) => item.id === elem.id
  );
  if (!network) {
    dataDialog.networks.push(item);
    meta2d.store.data.networks = dataDialog.networks;
    meta2d.connectNetwork();
    setDot(true);
  }

  dataDialog.popupVisible = false;
};

const onDelNetWork = async (item: any, i: number) => {
  const ret: any = await axios.post(`/api/data/datasources/delete`, {
    id: item._id || item.id,
  });
  if (ret) {
    dataDialog.networkList.splice(i, 1);
  }
};

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

// 请求我的实时数据
const getNetworks = async () => {
  const ret: any = await axios.post(
    `/api/data/datasources/list`,
    {
      q: {
        name: dataDialog.input,
      },
      query: {
        type: 'subscribe',
      },
      projection: { updatedAt: 0 },
    },
    {
      params: {
        current: 1,
        pageSize: 10,
      },
    }
  );
  if (ret?.list) {
    for (const item of ret.list) {
      item.id = item.id || item._id;
    }
    dataDialog.networkList = ret.list;
  }
};

const onInputDatasets = (name: string) => {
  debounce(getDatasets, 300, name);
};

// 请求我的数据集
const getDatasets = async (name?: string) => {
  const body: any = {
    query: {
      type: 'dataset',
    },
    projection: { updatedAt: 0 },
  };
  if (name) {
    body.q = { name };
  }
  const ret: any = await axios.post(`/api/data/datasources/list`, body, {
    params: {
      current: 1,
      pageSize: 10,
    },
  });
  if (ret?.list) {
    let found = false;
    for (const item of ret.list) {
      item.id = item.id || item._id;
      if (dataDialog.dataset?.id === item.id) {
        found = true;
      }
    }
    if (dataDialog.dataset?.id && !found) {
      ret.list.push(dataDialog.dataset);
    }

    dataDialog.datasetList = ret.list;
  }
};

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

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

const deleteNetwork = (index: number) => {
  dataDialog.networks.splice(index, 1);
  meta2d.store.data.networks = dataDialog.networks;
  meta2d.connectNetwork();
  setDot(true);
};

const onOkNetwork = async () => {
  if (dataDialog.editNetwork === 1) {
    if (dataDialog.save) {
      const ret: any = await axios.post(
        `/api/data/datasources/add`,
        dataDialog.network
      );
      if (!ret) {
        return;
      }
      ret.id = ret.id || ret._id;
      dataDialog.network._id = dataDialog.network.id = ret.id;
    }
    dataDialog.networks.push(dataDialog.network);
    dataDialog.networkList.push(dataDialog.network);
  } else if (dataDialog.editNetwork === 2) {
    if (dataDialog.save) {
      const ret: any = await axios.post(
        `/api/data/datasources/update`,
        dataDialog.network
      );
      if (!ret) {
        return;
      }
    }
  }

  meta2d.store.data.networks = dataDialog.networks;
  meta2d.connectNetwork();
  setDot(true);

  dataDialog.editNetwork = false;
  delete dataDialog.networkBak;
};

const datasetColumns = ref([
  {
    colKey: 'device',
    title: '设备',
    ellipsis: true,
  },
  {
    colKey: 'label',
    title: '数据点名称',
    ellipsis: true,
  },
  {
    colKey: 'id',
    title: '数据点ID',
    ellipsis: true,
  },
  {
    colKey: 'type',
    title: '类型',
    ellipsis: true,
  },
  {
    colKey: 'mock',
    title: '值范围',
    ellipsis: true,
  },
]);

const addDataset = () => {
  dataDialog.dataset = {
    name: '',
    type: 'dataset',
    mode: 'api',
    url: '',
    data: [],
  };
  dataDialog.editDataset = 1;
};

const editDataset = () => {
  dataDialog.datasetBak = dataDialog.dataset;
  dataDialog.dataset = JSON.parse(JSON.stringify(dataDialog.dataset));
  dataDialog.editDataset = 2;
};

const onOkDataset = async (saveas = false) => {
  if (!dataDialog.dataset.name) {
    MessagePlugin.error('名称不能为空');
    return;
  }

  const dataset = JSON.parse(JSON.stringify(dataDialog.dataset));

  // 保存到我的数据源
  if (saveas || dataDialog.editDataset === 1) {
    delete dataset.id;
    delete dataset._id;
    const ret: any = await axios.post(`/api/data/datasources/add`, dataset);
    if (!ret) {
      return;
    }
    ret.id = ret.id || ret._id;
    dataDialog.datasetId = ret.id;
    dataset._id = dataset.id = ret.id;
    dataDialog.datasetList.push(dataset);
  } else {
    const ret: any = await axios.post(`/api/data/datasources/update`, dataset);
    if (!ret) {
      return;
    }
  }

  delete dataset.data;
  // @ts-ignore
  meta2d.store.data.dataset = dataset;

  setDot(true);

  dataDialog.editDataset = false;
  delete dataDialog.datesetBak;
};

const onDelDataset = async (item: any, i: number) => {
  const ret: any = await axios.post(`/api/data/datasources/delete`, {
    id: item.id,
  });
  if (ret) {
    dataDialog.datasetList.splice(i, 1);
  }
};

const onSelDataset = async (init = false) => {
  if (dataDialog.datasetId) {
    const dataset = dataDialog.datasetList.find((item: any) => {
      return item.id === dataDialog.datasetId;
    });

    if (!dataset) {
      return;
    }

    if (dataset.url) {
      const ret = await axios.get(dataset.url);
      if (ret) {
        dataset.data = ret;
      }
    } else {
      const ret = await axios.post(`/api/data/datasources/get`, {
        id: dataset.id,
      });
      if (ret?.data) {
        dataset.data = ret.data;
      }
    }

    dataDialog.dataset = dataset;

    if (!init) {
      const d = JSON.parse(JSON.stringify(dataset));
      delete d.data;
      // @ts-ignore
      meta2d.store.data.dataset = d;

      setDot(true);
    }
  }
};

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;
    z-index: 2;

    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);
    z-index: 1;

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