<template>
  <div class="meta2d">
    <div class="tools">
      <t-tooltip placement="bottom" :content="$t('新建')">
        <a @click="newFile">
          <!-- <t-icon name="add" @click="newFile" /> -->
          <add-icon  />
        </a>
      </t-tooltip>
      <t-tooltip :content="$t('保存为方案')" placement="bottom">
        <a  @click="!route.query.c && save(SaveType.Save, '', true,1)">
          <t-badge
            :class="{ gray: route.query.c }"
            dot
            :showZero="false"
            :count="!route.query.c && dot ? 1 : 0"
          >
            <save-icon 
              class="hover"
             />
            <!-- <t-icon
              name="save"
              class="hover"
              @click="!route.query.c && save(SaveType.Save, '', true,1)"
            /> -->
          </t-badge>
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('保存为模板')">
        <a @click="!route.query.c && save(SaveType.Save, 'v-template', true,2)">
          <t-badge
            :class="{ gray: route.query.c }"
            dot
            :showZero="false"
            :count="!route.query.c && dot ? 1 : 0"
          >
            <!-- <root-list-icon  class="hover"
              @click="!route.query.c && save(SaveType.Save, 'v-template', true,2)"/> -->
            <!-- <t-icon
              name="root-list"
              class="hover"
              @click="
                !route.query.c && save(SaveType.Save, 'v-template', true,2)
              "
            /> -->
            <RootListIcon class="hover"
              />
          </t-badge>
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('保存为我的组件')">
        <a :class="{ gray: route.query.id && !route.query.c }" @click="save(SaveType.Save, 'v.component', true,1)">
          <t-badge dot :showZero="false" :count="route.query.c && dot ? 1 : 0">
            <!-- <t-icon
              name="app"
              @click="save(SaveType.Save, 'le5leV-components', true)"
            /> -->
            <!-- <LayersIcon  class="hover" @click="save(SaveType.Save, 'v.component', true,1)"/> -->
            <i class="l-icon l-zujian">
            </i>
          </t-badge>
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('格式化（双击可连续使用）')">
        <a @click="oneFormat" @dblclick="alwaysFormat" :style="{
            background: one || always ? '#4480F929' : '',
            color: one || always ?( theme==='light'?'#4480F9':'#4480F9'):''
          }"
        >
          <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 placement="bottom" :content="$t('清除格式')">
        <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 placement="bottom" :content="$t('直线')">
        <a :draggable="true" @dragstart="onAddShape($event, 'line')" @click="onAddShape($event, 'line')">
          <slash-icon></slash-icon>
          <!-- <t-icon name="slash" /> -->
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('文字')">
        <a :draggable="true" @dragstart="onAddShape($event, 'text')" @click="onAddShape($event, 'text')">T</a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('铅笔')">
        <a @click="onPencil" :style="{
          background: pencil ? '#4480F929' : '',
          color: pencil ?( theme==='light'?'#4480F9':'#4480F9'):''
        }">
          <PenBrushIcon />
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('钢笔（双击可连续使用）')">
        <a @click="oneDraw" @dblclick.stop="alwaysDraw" :style="{
            background: oneD || alwaysD ? '#4480F929' : '',
            color: oneD || alwaysD ?( theme==='light'?'#4480F9':'#4480F9'):''
          }"
        >
          <PenIcon />
          <!-- <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 placement="bottom" :content="$t('视图大小')">
        <div style="line-height: 40px; margin-left: 8px;width:34px;">{{ scale }}%</div>
      </t-tooltip>

      <t-tooltip placement="bottom" :content="$t('100%视图')">
        <a @click="onScaleFull">
          <refresh-icon />
          <!-- <t-icon name="refresh" /> -->
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('窗口大小')">
        <a @click="onScaleWindow">
          <fullscreen-exit-icon />
          <!-- <t-icon name="fullscreen-exit" /> -->
        </a>
      </t-tooltip>
      <t-tooltip :content="!canScale ? $t('允许缩放') : $t('禁止缩放')" placement="bottom">
        <a>
          <svg
            v-if="!canScale"
            class="l-icon"
            aria-hidden="true"
            @click="onCanScale(true)"
          >
            <use xlink:href="#l-suofang"></use>
          </svg>
          <svg
            v-else
            class="l-icon"
            aria-hidden="true"
            @click="onCanScale(false)"
          >
            <use xlink:href="#l-jinzhisuofang"></use>
          </svg>
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('自适应设置')">
        <a :style="{
            background: fitFlag ? '#4480F929' : '',
            color: fitFlag ?( theme==='light'?'#4480F9':'#4480F9'):''
          }"
        @click="changeFit">
          <LayoutIcon />
        </a>
      </t-tooltip>
      <div class="flex-grow"></div>
      <!-- <t-tooltip content="数据管理" placement="bottom">
        <a @click="onShowDataDialog">
          <server-icon />
        </a>
      </t-tooltip> -->
      <t-divider style="margin: 15px 4px" layout="vertical"></t-divider>
      <t-tooltip :content="isLock ? $t('浏览模式') : $t('编辑模式')" placement="bottom">
        <a class="a-1">
          <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 placement="bottom" :content="$t('运行（预览）')">
        <a class="a-1" @click="preview">
          <caret-right-icon />
          <!-- <t-icon name="caret-right" /> -->
        </a>
      </t-tooltip>
      <t-tooltip placement="bottom" :content="$t('分享')">
        <a @click="share" :class="{ 'share-primary': shared }">
          <share-icon />
          <!-- <t-icon name="share" :class="{ primary: shared }" /> -->
        </a>
      </t-tooltip>
      <t-popup placement="bottom" v-model="qrcode.visible">
        <a>
          <qrcode-icon />
          <!-- <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">
              {{$t('当前项目为本地编辑模式')}}<br>
              {{$t('请保存为大屏项目后访问')}}
            </div>
            <div v-else class="gray center mb-4" style="font-size: 10px; margin-bottom: 6px">
              {{$t('仅支持手机访问大屏项目')}}
            </div>
          </div>
        </template>
      </t-popup>

      <t-tooltip placement="bottom" :content="$t('云发布')">
        <a @click="onShowPublish">
          <cloud-icon />
          <!-- <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" @replaceScene="replaceScene"></ContextMenu>
    <t-dialog v-if="dataDialog.show" width="800px" :visible="true" @close="closeDataDialog" :header="$t('数据管理')">
      <t-tabs v-model="dataDialog.tab" class="body">
        <t-tab-panel :value="1" :destroy-on-hide="false" :label="$t('数据获取')">
          <template #panel>
            <div v-if="!dataDialog.editNetwork">
              <div class="mt-16 flex between middle">
                <div>
                  
                  <!-- <label class="ml-8"> 轮询间隔 </label>
                  <t-input-number
                    style="width: 100px"
                    v-model="dataDialog.networkInterval"
                    @change="networkIntervalChange"
                    theme="normal"
                    :min="30"
                    placeholder="毫秒"
                    suffix="ms"
                  /> -->
                </div>
                <div>
                  <t-select-input
                    v-model:inputValue="dataDialog.input"
                    :placeholder="$t('搜索我的数据获取')"
                    allow-input
                    clearable
                    @focus="dataDialog.popupVisible = true"
                    @blur="dataDialog.popupVisible = false"
                    @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)"
                        >
                          <div style="font-size: 14px">{{ item.name }}</div>
                          <div class="desc">{{ item.url }}</div>
                          <span class="del" @click.stop="onDelNetWork(item, i)">
                            <delete-icon />
                            <!-- <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">{{$t('暂无数据')}}</div>
                        </li>
                      </ul>
                    </template>
                    <template #suffixIcon>
                      <search-icon class="hover"/>
                      <!-- <t-icon name="search" class="hover" /> -->
                    </template>
                  </t-select-input>
                  <t-button class="ml-12" style="height: 30px" @click="addNetwork">
                    {{$t('添加数据获取')}}
                  </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 #url="{ row, rowIndex }">
                  {{ row.url }}
                </template>
                <template #actions="{ row, rowIndex }">
                  <a @click="editNetwork(row, rowIndex)"> {{$t('编辑')}} </a>
                  <a class="ml-12" @click="deleteNetwork(rowIndex)"> {{$t('删除')}} </a>
                </template>
                <template #empty>
                  <div class="center">
                    <div>{{$t('暂无数据')}}</div>
                    <div class="mt-8">
                      <a @click="addNetwork"> + {{$t('添加数据获取')}}</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"
                >
                  <rollback-icon class="mr-4"/>
                  <!-- <t-icon name="rollback" class="mr-4" />  -->
                  {{$t('返回')}}
                </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> {{$t('变量列表')}} </template>
          <template #panel>
            <template v-if="!dataDialog.editDataset">
              <div class="form-item mt-16 flex between middle">
                <div>
                <a @click="showAddData()"> + {{$t('新建变量')}}</a>
                <a class="ml-16" @click="clearData()"> × {{$t('清空列表')}}</a>
                </div>
                <div class="form-item flex">
                  <!-- <div class="form-item flex"> -->
                    <label style="text-align: end;margin-left: 8px;font-size: 13px;">{{$t('导入变量')}}：</label>
                    <t-select style="width: 120px" v-model="dataDialog.datasetType" :placeholder="$t('选择变量')">
                      <t-option :key="1" :value="1" :label="$t('我的变量列表')"></t-option>
                      <t-option :key="2" :value="2" :label="$t('从Excel导入')"></t-option>
                      <t-option :key="3" :value="3" :label="$t('在线接口')"></t-option>
                    </t-select>
                  <!-- </div> -->
                  <!-- <label style="width: 100px"> 当前变量列表 </label> -->
                  <!-- <div class="flex"> -->
                  <div style="width: 240px;padding-left: 8px;">
                    <t-select
                      v-if="dataDialog.datasetType === 1"
                      v-model="dataDialog.datasetId"
                      filterable
                      :placeholder="$t('选择变量列表')"
                      :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">
                          <div style="font-size: 14px">{{ item.name }}</div>
                          <div v-if="item.url" class="desc">
                            {{ item.url }}
                          </div>
                          <div v-else class="desc">{{$t('自定义')}}</div>
                          <span class="del" @click.stop="onDelDataset(item, i)">
                            <delete-icon />
                            <!-- <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>
                    <div class="flex middle" v-if="dataDialog.datasetType === 2">
                      <t-button class="shrink-0 ml-24" style="width: 90px; height: 30px" @click="importDataset">
                        {{$t('导入')}}Excel
                      </t-button>
                      <a :href="cdn ? cdn + '/v/data.xlsx' : '/data.xlsx'" download class="ml-12 mt-4 nowrap">
                        {{$t('下载')}}Excel{{$t('示例')}}
                      </a>
                    </div>
                    <div v-if="dataDialog.datasetType === 3" class="form-item">
                      <t-input v-model="dataDialog.dataset.url" @blur="getDatas" @enter="getDatas" :label="$t('地址：')" :placeholder="$t('点击图标或回车获取数据')">
                        <template #suffixIcon>
                          <CloudDownloadIcon @click="getDatas" :style="{ cursor: 'pointer' }" />
                        </template>
                      </t-input>
                    </div>
                  </div>
                </div>
                  <!-- <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.devices"
                :columns="datasetColumns"
                size="small"
                :max-height="280"
              >
                <template #type="{ row }">
                  {{ row.type || 'string' }}
                </template>
                <template  #actions="{ row, rowIndex }">
                  <edit-icon class="hover" @click="showAddData(row, rowIndex)"/>
                  <delete-icon class="ml-12 hover"
                    @click="dataDialog.dataset.devices.splice(rowIndex, 1)"/>
                </template>
              </t-table>
            </template>
            <div v-else>
              <div class="mt-8">
                <a @click="backDataset" class="flex middle" style="width: 44px">
                  <rollback-icon class="mr-4"/>
                  <!-- <t-icon name="rollback" class="mr-4" />  -->
                  {{$t('返回')}}
                </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('同时保存到我的数据获取')}}
          </t-checkbox>
          <t-button @click="onOkNetwork">{{$t('确定')}}</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('同时保存为我的变量列表')}}
            </t-checkbox>
            <t-button @click="onOkDataset()">{{$t('保存')}}</t-button>
          </template>
          <template v-else-if="dataDialog.editDataset === 2">
            <div class="flex-grow"></div>
            <t-button @click="onOkDataset(true)"> {{$t('另存为新变量列表')}} </t-button>
            <t-button @click="onOkDataset()">{{$t('保存')}}</t-button>
          </template>
          <template v-else>
            <!-- <a
              v-if="dataDialog.dataset && dataDialog.dataset.id"
              @click="editDataset"
            >
              编辑当前变量列表
            </a> -->
            <t-checkbox style="display: inline;" v-model="dataDialog.enableMock" @change="onChangeMock">
              {{$t('开启模拟数据')}}
            </t-checkbox>
            <div class="flex-grow"></div>
            <t-button @click="downloadAsJson" variant="outline" theme="primary"> 
              <template #icon><FileIcon></FileIcon></template>
              {{$t('下载为')}}JSON 
            </t-button>
            <t-button @click="downloadAsExcel" variant="outline" theme="primary"> 
              <template #icon><FileExcelIcon></FileExcelIcon></template>
              {{$t('下载为')}}Excel 
            </t-button>
            <t-button @click="onOkDataset()"> {{$t('保存为我的变量列表')}} </t-button>

            <!-- <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('完成')}} </t-button>
        </div>
      </template>
    </t-dialog>

    <t-dialog
      v-if="publishDialog.show"
      width="700px"
      :header="$t('云发布')"
      :visible="true"
      :cancel-btn="null"
      :confirm-btn="$t('完成')"
      @close="publishDialog.show = false"
      @confirm="publishDialog.show = false"
    >
      <div class="body" style="height: 350px">
        <div class="form-item mt-8">
          <label>{{$t('项目名称')}}</label>
          <div class="flex middle">
            <laptop-icon class="mr-8"></laptop-icon>
            <!-- <t-icon name="laptop" class="mr-8" />  -->
            {{ publishDialog.name }}
          </div>
        </div>
        <template v-if="publishDialog.data">
          <div class="form-item mt-8">
            <label>{{$t('发布状态')}}</label>
            <div v-if="publishDialog.data.id" class="flex middle">
              <div v-if="publishDialog.data.isExpired" class="warning">
                <stop-circle-icon  class="mr-4" />
                <!-- <t-icon name="stop-circle-1" class="mr-4" /> -->

                {{$t('已过期')}}
              </div>
              <div v-else class="primary">
                <play-circle-icon class="mr-4" />
                <!-- <t-icon name="play-circle" class="mr-4" /> -->
                {{$t('正在运行')}}
              </div>
              <div class="gray" style="margin-left: 32px; margin-top: -2px">
{{$t('                有效期至：')}}{{ publishDialog.data.expired }}
              </div>
              <p>{{$t('需要开通高级会员')}}</p>
              <!-- <a class="bland ml-12" @click="publishChargeDialog.show = true">
                续费
              </a> -->
            </div>
            <div v-else class="flex middle">
              <play-circle-stroke-icon class="mr-4" />
              <!-- <t-icon name="play-circle-stroke" class="mr-4" /> -->
              {{$t('未发布')}}
            </div>
          </div>
          <div class="form-item mt-16">
            <label>{{$t('乐吾乐域名')}}</label>
            <div class="flex w-full">
              <t-input :value="publishDialog.data.subDomain ? publishDialog.data.subDomain.split('.')[0] : ''" :maxlength="16" :status="publishDialog.status" :tips="publishDialog.tips" class="mr-4" style="width: 350px" @change="onChangeSubdomain" :placeholder="$t('子域名')"></t-input>
              <t-tooltip :content="$t('随机生成')">
                <refresh-icon class="hover" @click="refreshSubdomain"></refresh-icon>
                <!-- <t-icon
                  name="refresh"
                  class="hover"
                  @click="refreshSubdomain"
                /> -->
              </t-tooltip>
              <div class="mt-4 ml-16">{{`v${rootDomain}`}}</div>
            </div>
          </div>
          <div class="form-item mt-24">
            <label>{{$t('访问域名')}}</label>
            <div class="w-full">
              <div class="flex middle">
                <t-input v-model="publishDialog.data.domain" style="width: 350px" :placeholder="$t('支持自定义域名')"></t-input>

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

                  <t-popup
                    placement="bottom"
                    v-model="publishDialog.qrcodeVisible"
                  >
                    <a class="hover" style="margin-left: 32px">
                      <qrcode-icon />
                      <!-- <t-icon name="qrcode" /> -->
                      <span style="margin-left: 2px; position: relative; top: 1px">
                        {{$t('手机访问')}}
                      </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">- {{$t('注意')}}</div>
                <div>{{$t('仅支持')}}48{{$t('小时免费试用')}}，{{$t('到期后需要续费使用')}}。</div>
              </div>
              <div class="desc mt-8">
                <div class="title desc">- {{$t('自定义域名')}}</div>
                <div>
                  {{$t('在域名服务商的')}}DNS{{$t('控制台设置好对应的')}}CNAME，{{$t('值为乐吾乐域名')}}。
                  <a :href="`https://doc${rootDomain}/document/126505408`" target="_blank">
                    {{$t('更多帮助')}}
                  </a>
                </div>
              </div>
            </div>
          </div>
          <div class="form-item mt-16">
            <label></label>
            <div class="w-full">
              <t-button @click="onPublish">{{$t('发布')}}</t-button>
              <t-button v-if="publishDialog.data.id&&!publishDialog.data.isExpired" @click="onCancelPublish" class="ml-16">{{$t('取消发布')}}</t-button>
            </div>
          </div>
        </template>
        <div v-else class="flex center" style="margin-top: 32px">
          <t-loading size="small" :text="$t('加载中...')"></t-loading>
        </div>
      </div>
    </t-dialog>

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

    <!-- 分享弹窗 -->
    <ShareModal  :shared="shared" v-model:visible="shareVisible" />
    <t-dialog
      v-if="addDataDialog.show"
      :visible="true"
      class="data-dialog"
      :header="addDataDialog.header"
      @close="addDataDialog.show = false"
      @confirm="onOkAddData"
    >
      <!-- <div class="form-item mt-16">
        <label>设备</label>
        <t-input v-model="addDataDialog.data.device" placeholder="设备名称" />
      </div> -->
      <div class="form-item mt-16">
        <label>{{$t('显示名称')}}</label>
        <t-input @change="changeDataLabel($event)" :value="addDataDialog.data.label" :placeholder="$t('变量简短描述')"></t-input>
      </div>
      <div class="form-item mt-16">
        <label>{{$t('变量名')}}</label>
        <t-input @change="changeDataID($event)" :value="addDataDialog.data.id" :placeholder="$t('变量名')"></t-input>
      </div>
      <div class="form-item mt-16">
        <label>{{$t('类型')}}</label>
        <t-select class="w-full" :options="typeOptions" v-model="addDataDialog.data.type" @change="addDataDialog.data.value = null" :placeholder="$t('字符串')"></t-select>
      </div>
      <div class="form-item mt-16">
        <label>{{$t('值范围')}}</label>
        <div class="w-full">
          <t-input v-model="addDataDialog.data.mock" :placeholder="$t('值范围')"></t-input>
          <h6 class="desc mt-8">{{$t('值范围说明')}}</h6>
          <ul class="desc ml-16">
            <li>
              <label class="inline" style="width: 80px">{{$t('固定值')}}：</label>
              {{$t('直接填写')}}，{{$t('例如')}}：10
            </li>
            <li>
              <label class="inline" style="width: 80px">{{$t( '随机值' )}}：</label>
              { {{$t( '值1,值2,' )}}...}。{{$t( '例如' )}}：{1,2,3,4,5}
            </li>
            <li>
              <label class="inline" style="width: 80px">{{$t('范围数字')}}：</label>
              {{$t('最小值')}}-{{$t('最大值')}}。{{$t('例如')}}：0-1.0 {{$t('或')}} 0-100
            </li>
            <li>
              <label class="inline" style="width: 80px">{{$t('随机字符串')}}：</label>
              [{{$t('长度')}}]。{{$t('例如')}}：[8]
            </li>
          </ul>
        </div>
      </div>
    </t-dialog>
    <t-dialog v-model:visible="replaceDialog.show" class="project-dialog" :width="700" @close="replaceDialog.show = false" @confirm="onReplace" :header="$t('方案列表')">
      <t-tabs :value="replaceDialog.collection" @change="sceneChange">
        <t-tab-panel
          v-for="item in replaceList"
          :value="item.key"
          :label="item.label"
          :destroy-on-hide="false"
          style="max-height: 420px"
        >
        <div class="flex box-list"  style="flex-wrap:wrap;justify-content: flex-start;">
          <template v-if="replaceDialog.list?.length">
            <div class="box" :class="{active:replaceDialog.select?.id===_item.id}" @click="selectScene(_item)" v-for="_item in replaceDialog.list">
              <div class="box-img">
                <img :src="_item.image"></img>
              </div>
              <div class="item-title" :title="_item.name">{{_item.name}}</div>
            </div>
          </template>
          <template v-else >
             <div class="item-title" style="height:50px;">
               暂无数据
             </div>
          </template>
        </div>
        <t-pagination :pageSizeOptions="[15,30,60]" :total="replaceDialog.total"  v-model="replaceDialog.current" :pageSize="replaceDialog.pageSize" @change="pageChange" />
        </t-tab-panel>
      </t-tabs>
    </t-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, watch, ref, reactive, toRaw, computed, getCurrentInstance } 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, getDomain } from '@/services/user';
import {
  cdn,
  getComponents,
  getLe5leV,
  updateCollection,
} from '@/services/api';
import {
  save,
  autoSave,
  newFile,
  SaveType,
  onScaleFull,
  onScaleWindow,
  useDot,
  // autoSaveAS,
  
} from '@/services/common';
import { useSelection } from '@/services/selections';
import { defaultFormat, fromArrows, toArrows, rootDomain } from '@/services/defaults';
import { checkData, localStorageName, Meta2dBackData, noLoginTip } from '@/services/utils';
import { debounce } from '@/services/debouce';
import { s8 } from '@/services/random';
import { setCookie, deleteCookie } from '@/services/cookie';
import ShareModal from '@/views/components/common/ShareModal.vue';
import ContextMenu from './ContextMenu.vue';
import Network from './Network.vue';
import Dataset from './Dataset.vue';
import ChargeCloudPublish from './ChargeCloudPublish.vue';
import { AddIcon, EditIcon, SaveIcon, RootListIcon,SlashIcon, RefreshIcon, ServerIcon, CaretRightIcon, ShareIcon, QrcodeIcon, CloudIcon, DeleteIcon, SearchIcon, RollbackIcon, LaptopIcon, StopCircleIcon , PlayCircleIcon, PlayCircleStrokeIcon, LayersIcon, FullscreenExitIcon, FileIcon, FileExcelIcon, CloudDownloadIcon, PenBrushIcon, PenIcon, LayoutIcon } from 'tdesign-icons-vue-next';
import {transformData} from '@/services/utils';
import { importExcel, saveAsExcel } from '@/services/excel';
import { typeOptions } from '@/services/common';
import { upload } from '@/services/file';
import { getCollectionList } from '@/services/api';

const router = useRouter();
const route = useRoute();
const { user, getUser } = useUser();
const { dot, setDot } = useDot();
const { select, selections } = useSelection();
const { proxy } = getCurrentInstance();
const $t = proxy.$t

const meta2dOptions: Options = {
  cdn,
  rule: true,
  ruleColor:'#222E47',
  // background: '#1e2430',
  rotateCursor: cdn + '/v/rotate.cur', //'https://assets.le5lecdn.com/2d/rotate.cur',
  rightCursor: cdn + '/v/right.cur', 
  downCursor: cdn + '/v/down.cur', 
  ruleOptions:{
    background:'#121924',
    underline:true,
    baseline:'bottom',
    textTop:6,
    textLeft:-24,
    textColor:'#6E7B91'
  },
  x: 32,
  y: 32,
  width: 1920,
  height: 1080,
  // color: '#bdc7db',
  disableAnchor: true,
  defaultFormat: { ...defaultFormat },
  uploadFn: async (file: File) => {
    if (!(user&&user.id)) {
      MessagePlugin.warning(noLoginTip);
      return;
    }
    const res:any = await upload(
      file,
      true,
      file.name,
      `/大屏/图片/默认`,
      'new'
    );
    return res.url;
  },
};

let timer: any = 0;

const shared = ref<boolean>(false);
const shareVisible = 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('fit',fit);
  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();
  };
});

onUnmounted(()=>{
  meta2d.off('active', active);
  meta2d.off('inactive', inactive);
  meta2d.off('fit',fit);
  meta2d.off('scale', scaleSubscriber);
  meta2d.off('add', lineAdd);
  meta2d.off('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);
  meta2d.off('contextmenu', onContextmenu);
  meta2d.off('click', canvasClick);
  // meta2d.off('business-showPayDiagram',showPayDiagram);
})

const watcher = watch(
  () => route.query,
  async () => {
    open();
  }
);
//TODO 打开图纸
const open = async (flag: boolean = false) => {
  if (route.query.token) {
    setCookie('token', route.query.token + '', {
      path: '/',
      domain: getDomain(),
    });
    getUser();
    const newQuery = { ...route.query };
    delete newQuery.token;
    router.replace({
      path: '/',
      query: newQuery,
    });
    return;
  }
  // if(route.query.saveas){
  //   //id需要
  //   await autoSaveAS((route.query.id)as string);
  //   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 + '',undefined , route.query.historyId as string);
    }
    if (ret) {
      if (!(ret.data.pens && ret.data.pens.length)) {
        //获取不到pen说明是parse svg
        MessagePlugin.warning($t('解析的svg图元不允许编辑！'));
        newFile();
        return;
      }
      ret.data.id = ret.id || route.query.id;;
      ret.data.folder = ret.folder;
      ret.data.name = ret.name;
      ret.data.image = ret.image;
      ret.data.ownerId = ret.ownerId;
      ret.data.ownerName = ret.ownerName;
      ret.data.case = ret.case;
      ret.data.isSystem = ret.system;
      ret.data.isTemplate = ret.template;
      if(!ret.data.background){
        ret.data.background = '#1e2430';
      }
      if(!ret.data.color){
        ret.data.color = '#bdc7db';
      }
      if(!ret.data.width){ret.data.width= 1920};
      if(!ret.data.height){ret.data.height= 1080};
      meta2d.open(ret.data);
      if (!route.query.c) {
        shared.value = ret.shared;

        const qr: any = await QRCode.toDataURL(
          `https://view2d${rootDomain}/?id=${route.query.id + '&tag=v'}`
        );
        qrcode.url = qr;
      }
    }
  } else if (flag) {
    const data: any =JSON.parse(await localforage.getItem(localStorageName));
    if(!data){
      meta2d.open({
        name: $t('新建项目'),
        pens: [],
        background: '#1e2430',
        color: '#bdc7db',
        width:1920,
        height:1080,
        enableMock: true,
        folder: route.query.folder,
        tags: route.query.tags ? [route.query.tags] : null,
      } as any);
    }else{
      if(!data.background){
        data.background = '#1e2430';
      }
      if(!data.color){
        data.color = '#bdc7db';
      }
      if(!data.width){data.width= 1920};
      if(!data.height){data.height= 1080};
      if (data) {
        meta2d.open(data);
      }
    }
  } else if (!sessionStorage.getItem('opening')) {
    meta2d.open({
      name: $t('新建项目'),
      pens: [],
      background: '#1e2430',
      color: '#bdc7db',
      width:1920,
      height:1080,
      enableMock: true,
      folder: route.query.folder,
      tags: route.query.tags ? [route.query.tags] : null,
    } 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 || '';
  deal2DToV();
  meta2d.centerView();
  meta2d.canvas.hideFit();
  fitFlag.value = false;
};

const deal2DToV = ()=>{
  if(!meta2d.store.data.width||!meta2d.store.data.height){
    let rect = meta2d.getRect();
    if(!meta2d.store.data.pens.length){
      return;
    }
    let scale = meta2d.store.data.scale;
    if(!(meta2d.store.data as any).oldV&&Math.abs(rect.width/scale-1920)<5&&Math.abs(rect.height/scale-1080)<5){ //1920 1080
      //大致估算范围是大屏默认范围
      return;
    }

    let origin = meta2d.store.data.origin;
    if(rect.width/scale > 1920 || rect.height/scale > 1080){
      //超出大屏默认范围
      meta2d.store.data.width = rect.width/scale;
      meta2d.store.data.height = rect.height/scale;
    }
    meta2d.store.data.pens.forEach((pen)=>{
      if(pen.locked){
        pen.locked = 0;
      }
    });
    let pens = meta2d.store.data.pens.filter((pen)=>!pen.parentId);
    meta2d.canvas.opening = false;
    meta2d.translatePens(pens,origin.x - rect.x,origin.y - rect.y);
    meta2d.store.data.pens.forEach((pen)=>{
      if(!pen.type){
        meta2d.canvas.updateLines(pen);
      }
    });
    meta2d.render(true);
  }
}

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

onUnmounted(() => {
  clearInterval(timer);
  watcher();
  if (meta2d) {
    meta2d.destroy();
  }
});

const inactive = () => {
  if(fitFlag.value){
    return;
  }
  select();
};

const active = (pens: Pen[]) => {
  if(fitFlag.value){
    return;
  }
  select(pens);

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

const fit = (fit) => {
  select(undefined, fit);
}

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: $t('曲线'), icon: '#l-curve2', value: 'curve' },
  { name: $t('线段'), icon: '#l-polyline', value: 'polyline' },
  { name: $t('直线'), icon: '#l-line', value: 'line' },
  { name: $t('脑图曲线'), 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(meta2d.canvas.pencil){
    //关掉铅笔
    pencil.value = false;
    meta2d.stopPencil();
  }
  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 = () => {
  if(meta2d.canvas.pencil){
    //关掉铅笔
    pencil.value = false;
    meta2d.stopPencil();
  }
  alwaysD.value = true;
  meta2d.drawLine(meta2d.store.options.drawingLineName);
  meta2d.store.options.disableAnchor = false;
};

const pencil = ref(false);
const onPencil = () => {
  // 开了铅笔需要关掉钢笔
  if(meta2d.canvas.drawingLineName){
    meta2d.finishDrawLine();
    meta2d.drawLine();
    oneD.value = false;
    alwaysD.value = false;
  }
  if (!meta2d.canvas.pencil) {
    meta2d.drawingPencil();
  } else {
    meta2d.stopPencil();
  }
  pencil.value = meta2d.canvas.pencil;
}

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 canScale = ref(true);
function onCanScale(can: boolean) {
  canScale.value = can;
  meta2d.setOptions({
    disableScale: !can,
  });
}

const preview = async () => {
  meta2d.stopAnimate();
  // @ts-ignore
  const data: Meta2dBackData = meta2d.data();
  checkData(data);
  if (dot && user && data.id&&data.ownerId=== user.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,
  //   },
  // });
  // let screenWidth = window.screen.width;
  // let screenHeight = window.screen.height;
  let width = meta2d.store.data.width||meta2d.store.options.width||1920;
  let height = meta2d.store.data.height||meta2d.store.options.height||1080;
  let minScle  = Math.min(window.innerWidth/width,window.innerHeight/height);
  let url = import.meta.env.BASE_URL.slice(0, -1) + `/preview?r=${Date.now() + ''}`;
  if (data.id) {
    url += `&id=${data.id}`;
  }
  if(route.query.c||data.component){
    url += '&c=1';
  }
  window.open(
    url,
    '',
    `height=${minScle*height},width=${minScle*width},top=0,left=${(window.innerWidth-minScle*width)/2},toolbar=no,menubar=no, scrollbars=no,resizable=no,location=no, status=no`
  );
};

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: $t('名称'),
    ellipsis: true,
    width: 160,
  },
  {
    colKey: 'protocol',
    title: $t('通信方式'),
    width: 120,
  },
  {
    colKey: 'url',
    title: $t('URL地址'),
    ellipsis: true,
  },
  { colKey: 'actions', title: $t('操作'), 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.networkInterval = meta2d.store.data.networkInterval;
  dataDialog.networkList = [];
  dataDialog.datasetList = [];
  dataDialog.editNetwork = false;
  dataDialog.save = true;
  dataDialog.show = true;
  if(!dataDialog.datasetType){
    dataDialog.datasetType = 1;
  }
  await getNetworks();
  await getDatasets();
  // onSelDataset(true);
};

const onFinishDataDialog = () => {
  dataDialog.show = false;
  if (dataDialog.networkInterval) {
    meta2d.store.data.networkInterval = dataDialog.networkInterval;
  }
  meta2d.connectNetwork();
};

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

const networkIntervalChange = (e) =>{
  meta2d.store.data.networkInterval = e;
  // meta2d.closeNetwork();
  meta2d.connectNetwork();
}

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 = toRaw(dataDialog.networks);
    meta2d.connectNetwork();
    setDot(true);
  }

  dataDialog.popupVisible = false;
};

const onDelNetWork = async (item: any, i: number) => {
  const ret: any = await axios.post(`/api/data/datasource/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/datasource/list`,
    {
      // q: {
        name: dataDialog.input,
      // },
      type: 'subscribe',
      projection: "id,data,name,type",
    },
    {
      params: {
        current: 1,
        pageSize: 10,
      },
    }
  );
  if (ret?.list) {
    const list = [];
    for (const item of ret.list) {
      item.id = item.id || item._id;
      list.push(transformData(item,'toMetaNetwork'));
    }
    dataDialog.networkList = list;
  }
};

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

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

    dataDialog.datasetList = list;
  }
};

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

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

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

const onOkNetwork = async () => {
  const data = transformData(dataDialog.network,'toNetwork');
  if (dataDialog.editNetwork === 1) {
    if(!dataDialog.network.url) {
      MessagePlugin.error($t('URL地址不能为空！'));
      return;
    }
    if(!dataDialog.network.name) {
      MessagePlugin.error($t('名称不能为空！'));
      return;
    }
    if (dataDialog.save) {
      const ret: any = await axios.post(
        `/api/data/datasource/add`,
        data
      );
      if (!ret) {
        return;
      }
      ret.id = ret.id || ret._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/datasource/update`,
        data
      );
      if (!ret) {
        return;
      }
    }
    //替换
    let index = dataDialog.editNetworkIndex;
    if (index !== undefined) {
      dataDialog.networks.splice(index, 1, dataDialog.network);
      dataDialog.networkList.splice(index, 1, dataDialog.network);
    }
  }
  dataDialog.editNetwork = false;
  meta2d.store.data.networks =  toRaw(dataDialog.networks);
  meta2d.connectNetwork();
  setDot(true);

  delete dataDialog.networkBak;
};

const datasetColumns = ref([
  // {
  //   colKey: 'device',
  //   title: '设备',
  //   ellipsis: true,
  // },
  {
    colKey: 'label',
    title: $t('显示名称'),
    ellipsis: true,
  },
  {
    colKey: 'id',
    title: $t('变量名'),
    ellipsis: true,
  },
  {
    colKey: 'type',
    title: $t('类型'),
    ellipsis: true,
  },
  {
    colKey: 'mock',
    title: $t('值范围'),
    ellipsis: true,
  },
  {
    colKey: 'actions',
    title: $t('操作'),
    width: 100,
  },
]);

const importDataset = async () => {
  let columns: any = [
    // {
    //   header: $t('设备'),
    //   key: 'device',
    // },
    {
      header: $t('显示名称'),
      key: 'label',
    },
    {
      header: $t('变量名'),
      key: 'id',
    },
    {
      header: $t('类型'),
      key: 'type',
    },
    {
      header: $t('值范围'),
      key: 'mock',
    },
  ];
  const data: any = await importExcel(columns);
  // dataDialog.dataset.devices = data;
  mergeDataset(dataDialog.dataset, data);
  // modelValue.devices = data;
  // emit('update:modelValue', modelValue);
  // emit('change', modelValue);
};

const getDatas = async () => {
  if (!dataDialog.dataset.url) {
    return;
  }
  const ret = await axios.get(dataDialog.dataset.url);
  let flattenRet = flattenTree(ret);
  if (flattenRet) {
    // dataDialog.dataset.devices = flattenRet;
    mergeDataset(dataDialog.dataset,flattenRet);
  }
};

//展开树
const flattenTree = (root) =>{
  if (!root) return []; // 空树返回空数组

  const result = []; // 存储展开后的数组

  // 递归遍历树
  function dfs(node) {
    result.push({
      id: node.id,
      label: node.label||node.name,
      device: node.device||node.id,
      type: node.type,
      mock: node.mock,
      // children: node.children,
    }); // 将当前节点值添加到结果数组
    // 遍历当前节点的子节点
    if(node.children){
      for (let child of node.children) {
        dfs(child); // 递归调用DFS
      }
    }
  }
  root.forEach((item) => {
    dfs(item);
  });
  // dfs(root); // 从根节点开始遍历

  return result;
}

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

const showAddData = (row?: any, index?: number) => {
  if (row) {
    addDataDialog.header = '编辑数据';
    addDataDialog.data = JSON.parse(JSON.stringify(row));
    addDataDialog.index = index;
  } else {
    addDataDialog.header = $t('添加数据');
    addDataDialog.data = { type: 'string' };
  }

  addDataDialog.show = true;
};

const clearData = () => {
  dataDialog.datasetId = undefined;
  dataDialog.dataset.id = undefined;
  dataDialog.dataset.name = undefined;
  dataDialog.dataset.url = undefined;
  dataDialog.dataset.devices = [];
  setDot(true);
}

const closeDataDialog = () => {
  (meta2d.store.data as any).dataset = dataDialog.dataset;
  dataDialog.show = false;
  meta2d.connectNetwork();
}


const onOkAddData = () => {
  if (!addDataDialog.data.label) {
    MessagePlugin.error($t('请填写名称'));
    return;
  }
  if (!addDataDialog.data.id) {
    MessagePlugin.error($t('请填写数据ID'));
    return;
  }
  if (addDataDialog.header === $t('添加数据')) {
    dataDialog.dataset.devices.push(addDataDialog.data);
  } else {
    dataDialog.dataset.devices[addDataDialog.index] = addDataDialog.data;

    //更新所有绑定该id的pen label
    let binds = meta2d.store.bind[addDataDialog.data.id];
    if (binds) {
      binds.forEach((item) => {
        const pen: Pen = meta2d.findOne(item.id);
        pen.realTimes &&
          pen.realTimes.forEach((_realTime) => {
            if (_realTime.key === item.key) {
              _realTime.bind.label = addDataDialog.data.label;
            }
          });
      });
    }
  }

  addDataDialog.show = false;
};

const changeDataID = (value) => {
  if (!value) {
    MessagePlugin.error($t('变量名不能为空！'));
    return;
  }
  let item =  dataDialog.dataset.devices.filter((item) => item.id === value);
  if (item && item.length) {
    MessagePlugin.error($t('变量名重复！'));
    return;
  }
  addDataDialog.data.id = value;
};

const changeDataLabel = (value) => {
  if (!value) {
    MessagePlugin.error($t('显示名称不能为空！'));
    return;
  }
  let item =  dataDialog.dataset.devices.filter((item) => item.label === value);
  if (item && item.length) {
    MessagePlugin.error($t('显示名称重复！'));
    return;
  }
  addDataDialog.data.label = value;
};

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

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

const backDataset = () => {
  if (dataDialog.editDataset === 1 && !dataDialog.dataset._id) {
    dataDialog.dataset = {};
  }
  dataDialog.datasetBak && (dataDialog.dataset = dataDialog.datasetBak);
  dataDialog.dataset && (dataDialog.datasetId = dataDialog.dataset.id);
  dataDialog.editDataset = 0;
};

const onOkDataset = async (saveas = false) => {
  // if (!dataDialog.dataset.name) {
  //   MessagePlugin.error('名称不能为空');
  //   return;
  // }
  if(!(dataDialog.dataset.devices&&dataDialog.dataset.devices.length)){
    MessagePlugin.error($t('变量列表不能为空'));
    return;
  }
  const dataset = JSON.parse(JSON.stringify(dataDialog.dataset));
  let data = dataset;
  data.type = 'dataset';
  if(!data.name){
    data.name = meta2d.store.data.name;
  }
  data = transformData(dataset,'toNetwork');
  // 保存到我的数据源
  if (saveas || !dataset.id) {
    delete dataset.id;
    delete dataset._id;
    dataset.type = 'dataset';
    const ret: any = await axios.post(`/api/data/datasource/add`, data);
    if (!ret) {
      return;
    }
    ret.id = ret.id || ret._id;
    dataDialog.datasetId = ret.id;
    dataset.id = ret.id;
    dataDialog.dataset.id = ret.id;
    dataDialog.datasetList.push(dataset);
    MessagePlugin.success($t('保存新增成功！'));
  } else {
    const ret: any = await axios.post(`/api/data/datasource/update`, data);
    if (!ret) {
      return;
    }
    dataDialog.datasetList.forEach((item: any, index: number) => {
      if (item.id === dataset.id || (item._id === dataset._id && dataset._id != undefined)) {
        dataDialog.datasetList.splice(index, 1, dataset);
      }
    });
    MessagePlugin.success($t('保存更新成功！'));
  }
  delete dataset.devices;
  // @ts-ignore
  // console.log("dataset",dataset);
  // meta2d.store.data.dataset = dataset;

  // setDot(true);

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

const downloadAsExcel = () => {
  if(!(dataDialog.dataset.devices&&dataDialog.dataset.devices.length)){
    MessagePlugin.error($t('变量列表不能为空！'));
    return;
  }
  const name = meta2d.store.data.name;
  const columns:any[] = [{
    key: 'label',
    header: $t('显示名称'),
  },
  {
    key: 'id',
    header: $t('变量名'),
  },
  {
    key: 'type',
    header: $t('类型'),
  },
  {
    key: 'mock',
    header: $t('值范围'),
  }];
  saveAsExcel(name,columns,dataDialog.dataset.devices);
}

const downloadAsJson = () => {
  if(!(dataDialog.dataset.devices&&dataDialog.dataset.devices.length)){
    MessagePlugin.error($t('变量列表不能为空！'));
    return;
  }
  import('file-saver').then(({ saveAs }) => {
    saveAs(
      new Blob(
        [JSON.stringify(dataDialog.dataset)],
        {
          type: 'text/plain;charset=utf-8',
        }
      ),
      `${dataDialog.dataset.name || $t('未命名')}.json`
    );
  });
}

const onDelDataset = async (item: any, i: number) => {
  const ret: any = await axios.post(`/api/data/datasource/delete`, {
    id: item.id,
  });
  if (
    (meta2d.store.data as any).dataset &&
    (meta2d.store.data as any).dataset.id === item.id
  ) {
    //@ts-ignore
    meta2d.store.data.dataset = {};
    dataDialog.dataset = {};
    dataDialog.datasetId = undefined;
  }
  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.devices = ret;
      }
    } else {
      const ret = await axios.post(`/api/data/datasource/get`, {
        id: dataset.id,
      });
      if (ret?.data) {
        Object.assign(dataset,{...ret.data});
      }
    }
    mergeDataset(dataDialog.dataset,dataset.devices);
    // dataDialog.dataset = dataset;

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

      setDot(true);
    }
  }
};

const mergeDataset = (arr1:any,arr2:any[]) => {
  if(!(arr2&&arr2.length)){
    return;
  }
  if(!arr1.devices){
    arr1.devices = [];
  }
  arr2.forEach((item)=>{
    let index = arr1.devices.findIndex((elem)=>elem.id === item.id);
    if(index>=0){
      Object.assign(arr1.devices[index],item); 
    }else{
      arr1.devices.push(item);
    }
  });
}

const share = async () => {
  if (!(user && user.id)) {
    MessagePlugin.warning($t('请先登录！'));
    return false;
  }
  if (!route.query.id) {
    MessagePlugin.error($t('请先保存！'));
    return;
  }
  if(route.query.c){
    MessagePlugin.error($t('组件不允许分享！'));
    return;
  }
  shareVisible.value = true;
};

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;
  publishDialog.data = {
    detail:''
  };

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

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

  if (
    !publishDialog.data.domain ||
    publishDialog.data.domain.indexOf(`.v${rootDomain}`) >= 0
  ) {
    publishDialog.data.domain = publishDialog.data.subDomain;
  }

  makePublishQrcode();
};

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

  if (!publishDialog.data.domain) {
    publishDialog.data.domain = publishDialog.data.subDomain;
  }
  if(!route.query.id) {
    MessagePlugin.warning($t('请选择将要发布的方案'));
    return;
  }

  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 onCancelPublish = async () => {
  const ret: any = await axios.post(`/api/domain/remove`, {
    id: route.query.id,
  });
  onShowPublish();
}

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

const onSuccessChargeCloud = () => {
  publishChargeDialog.show = false;
  onShowPublish();
};

const theme = computed(() => {
  return localStorage.getItem('theme') || 'dark';
});

const fitFlag = ref(false);

const changeFit = () => {
  fitFlag.value = !fitFlag.value;
  if(fitFlag.value){
    meta2d.canvas.showFit();
  }else{
    meta2d.store.data.pens.forEach((pen) => {
      if (!selections.fit.children?.includes(pen.id)) {
        meta2d.setValue(
          { id: pen.id, visible: true },
          { render: false, doEvent: false, history: false }
        );
      }
    });
    meta2d.canvas.hideFit();
    meta2d.canvas.canvasImage.init();
    meta2d.canvas.canvasImageBottom.init();
    meta2d.render();
    select();
  }
}

const replaceDialog = reactive<any>({
  show:false,
  list:[],
  current:1,
  pageSize:15,
  total:0,
  collection:'v',
  select:{}
});

const replaceList = reactive([
  {
    key:'v',
    label:$t('大屏')
  },
  {
    key:'3d',
    label:'3D'
  },
  {
    key:'2d',
    label:'2D'
  },
]);

const replaceScene = ()=>{
  replaceDialog.show = true;
  sceneChange('v');
}

const sceneChange = async(e?:any) => {
   let collection = e;
   if(!collection){
     collection = replaceDialog.collection;
   }else{
    replaceDialog.collection = e;
    replaceDialog.current = 1;
   }
   const data = {
    // template:false
  };
  
  // if(collection === '3d'){
  //   delete data.template;
  // }
  const config = {
    params: {
      current: replaceDialog.current,
      pageSize: replaceDialog.pageSize,
    },
  };
  //2.请求所有图纸/组件数据
  const res: any = await getCollectionList(collection, data, config);
  replaceDialog.list = res.list;
  replaceDialog.total = res.total;
}

const pageChange = (e) => {
  replaceDialog.current = e.current;
  replaceDialog.pageSize = e.pageSize;
  sceneChange();
}

const selectScene = (_item) => {
  replaceDialog.select = _item;
  replaceDialog.select.collection = replaceDialog.collection;
}

const onReplace = ()=>{
  let id = meta2d.store.active[0].id;
  let url =location.origin+ `/view`;
  meta2d.setValue({
    id:id,
    iframe:`${url}/${replaceDialog.select.collection}/?id=${replaceDialog.select.id}`,
    thumbImg:replaceDialog.select.image
  });
  replaceDialog.show = false;
  meta2d.inactive();
  setTimeout(()=>{
    meta2d.active(meta2d.find(id))
  },10)
}

</script>
<style lang="postcss" scoped>
.meta2d {
  display: flex;
  flex-direction: column;
  background-color:#080b0f;
  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; */
    overflow-x: scroll;
    overflow-y: hidden;
    border-bottom: 1px solid var(--color-background-editor);
    a {
      display: flex;
      align-items: center;
      /* height: 100%; */
      padding: 6px;
      margin: 4px;
      border-radius: 4px;
      color: var(--color);
      text-decoration: none;
      &:hover{
        background-color: var(--color-background-views-hover);
        color: var(--color) !important;
      }
      /* .l-icon {
        width: 16px;
        height: 16px;
      } */

      /* &:hover {
        color: var(--color-primary);
      } */
      svg{
        width: 16px ;
        height: 16px;
        &:hover{
        color: var(--color) !important;
      }
      }
      font-size: 16px;
    }
    .a-1{
      svg{
        width: 16px;
        height: 16px ;
      }
    }

    .t-icon {
      font-size: 16px;
    }
    .l-icon {
      font-size: 18px;
      width: 18px ;
      height: 18px ;
    }
  }

  .share-primary{
    color:  var(--color-primary) !important;
    background-color:#4480F929;
  }
  #meta2d {
    /* border-top: 1px solid var(--color-background-input); */
    height: calc(100vh - 81px);
    /* height: calc(100% - 40px); */
    /* height: 100%; */
    z-index: 1;
    overflow: hidden;

    :deep(.meta2d-map) {
      background: var(--color-background);
    }
  }
}

.select-options{
  .t-popup__content{
    /* width: 240px !important; */
  }
}
:deep(.t-dialog__ctx){
  z-index:100;

  .watermark-span{
    color: var(--color-primary);
    cursor: pointer;
    &:hover{
      color: var(--color-primary-hover);
    }
  }
}

:deep(.project-dialog){
  .t-dialog__body{
    .box-list{
       flex-wrap: wrap;
       padding:8px;
       margin-bottom:12px;
       background-color: var(--color-background-active);
       overflow:scroll;
       max-height:375px;
      .box{
        width:125px;
        height:110px;
        padding:8px;
        .box-img{
          width:100%;
          height:70px;
        }
        /* .title{
          text-align:center; 
           white-space: nowrap;
           overflow: hidden;
           text-overflow:ellipsis;
           font-size:12px;
           color: var(--td-text-color-secondary);
        } */
        &:hover{
          border-radius: 4px;
          border:1px solid var(--color-primary);
        }
      }

      .item-title{
        text-align:center; 
        white-space: nowrap;
        overflow: hidden;
        text-overflow:ellipsis;
        font-size:12px;
        color: var(--td-text-color-secondary);
      }
      .active{
        border-radius: 4px;
        border:1px solid var(--color-primary);
      }
    }
  }
}

</style>
