<template>
  <div class="graphics">
    <div class="group-asset">
      <t-radio-group
        v-model="activeAssets"
        @change="assetsChange"
        variant="primary-filled"
      >
        <t-radio-button value="system">{{$t( '系统资源' )}}</t-radio-button>
        <t-radio-button value="user">{{$t( '我的资源' )}}</t-radio-button>
        <t-radio-button value="data">{{$t( '数据' )}}</t-radio-button>
        <t-radio-button value="structure">{{$t( '结构' )}}</t-radio-button>
      </t-radio-group>
    </div>
    <div class="groups-panel">
      <div class="groups">
        <div
          v-for="group in groups"
          :class="group.name === activedGroup ? 'active' : ''"
          @click="groupChange(group.name)"
        >
          <template v-if="group.type === 'iconfont'">
            <i class="l-icon" :class="group.icon"> </i>
            <span> {{$t( group.name) }}</span>
          </template>
          <template v-else>
            <!-- <t-icon :name="group.icon" /> -->
            <DesktopIcon v-if="group.icon==='desktop'" />
            <RootListIcon v-else-if="group.icon==='root-list'"/>
            <ImageIcon v-else-if="group.icon==='image'"/>
            <ControlPlatformIcon v-else-if="group.icon==='control-platform'"/>
            <ChartIcon v-else-if="group.icon==='chart'"/>
            <RelativityIcon v-else-if="group.icon==='relativity'"/>
            <ChartBubbleIcon v-else-if="group.icon==='chart-bubble'"/>
            <LayersIcon v-else-if="group.icon==='layers'"/>
            <TagIcon v-else-if="group.icon==='tag'" />
            <DataIcon v-else-if="group.icon==='data'"/>
            <!-- <InstallIcon v-else-if="group.icon==='install'"/> -->
            <RssIcon v-else-if="group.icon==='install'"/>
            <ArrowUpDown3Icon v-else-if="group.icon==='code'"/>
            <SystemInterfaceIcon v-else-if="group.icon==='system-interface'"/>
            <span> {{ $t(group.name) }}</span>
          </template>
        </div>
      </div>
      <Data v-if="activeAssets === 'data'"  :group="activedGroup" />
      <Structure v-else-if="activeAssets === 'structure'" :group="activedGroup"/>
      <template v-else>
      <div class="list" :class="groupType ? 'two-columns' : ''">
        <div class="input-search">
          <div class="btn">
            <!-- <t-icon name="search" /> -->
            <img src="/img/icon_search_gray.svg" />
          </div>
          <t-input
            v-model="search"
            @change="onSearch"
            @enter="onSearch"
            :placeholder="$t('搜索')"
          />

          <div class="ml-16">
            <t-tooltip :content="$t('展开/折叠')">
              <menu-fold-icon class="hover"
                style="font-size: 16px"
                @click="onFold"/>
              <!-- <t-icon
                name="menu-fold"
                class="hover"
                style="font-size: 16px"
                @click="onFold"
              /> -->
            </t-tooltip>
          </div>
        </div>
        <div v-if="loading" class="center mt-16">
          <t-loading :text="$t('加载中...')" size="small" :indicator="false" />
        </div>
        <template v-else>
          <div
            v-if="
              activedGroup === '图片' ||
              (activeAssets === 'user' &&
                (activedGroup === '方案' || activedGroup === '模板' || activedGroup === '组件'))
            "
            class="px-16 mt-12 mb-8 ml-4"
          >
            <a @click="onCreateFolder">+ {{$t( '新建文件夹' )}}</a>
          </div>
          <t-collapse v-model="activedPanels[activedGroup]">
            <t-collapse-panel
              :value="item.name"
              v-for="item in subGroups"
              :key="item.name"
              v-show="item.visible !== false"
            >
              <template #header>
                <div class="flex middle">
                  <div v-if="item.edited" @click.stop>
                    <t-input
                      v-model="item.label"
                      style="width: 140px"
                      @blur="createFoder"
                      @enter="createFoder"
                      @keyup="onKeyHeader"
                      :autofocus="true"
                    />
                  </div>
                  <div v-else>
                    {{ $t(item.name) }}
                  </div>
                </div>
              </template>
              <template #headerRightContent>
                <t-space size="small" @click.stop tabindex="0">
                  <t-upload
                    v-if="item.canEdited && activedGroup === '图片'"
                    action="/api/image/upload"
                    accept="image/*"
                    :headers="headers"
                    :data="{
                      directory: `/大屏/${activedGroup}/${item.name}`,
                      conflict:'new'
                    }"
                    :auto-upload="true"
                    :upload-all-files-in-one-request="false"
                    :before-upload="beforeUpload"
                    @selectChange="onSelectFiles(item)"
                    allowUploadDuplicateFile
                    @success="fileSuccessed"
                    theme="custom"
                  >
                    <image-icon class="hover" />
                    <!-- <t-icon name="image" class="hover" /> -->
                  </t-upload>
                  <template v-if="item.canEdited">
                    <add-icon   v-if="['组件', '方案', '模板'].includes(activedGroup)" class="hover"
                      @click="onAdd(item)"/>
                    <!-- <t-icon
                      v-if="['组件', '方案', '模板'].includes(activedGroup)"
                      name="add"
                      class="hover"
                      @click="onAdd(item)"
                    /> -->
                    <edit-icon class="hover"
                      @click="onEditHeader(item)"/>
                    <!-- <t-icon
                      name="edit"
                      class="hover"
                      @click="onEditHeader(item)"
                    /> -->
                    <t-popconfirm
                      :content="$t('确认删除该文件夹吗')"
                      placement="left"
                      @confirm="delFolder(item)"
                    >
                      <delete-icon class="hover"/>
                      <!-- <t-icon name="delete" class="hover" /> -->
                    </t-popconfirm>
                  </template>
                </t-space>
              </template>

              <template v-for="elem in item.list">
                <div
                  v-show="elem.visible !== false"
                  class="graphic"
                  :draggable="true"
                  @dragstart="dragStart($event, elem)"
                  @click.stop="dragStart($event, elem)"
                  @dblclick.stop="open(elem)"
                  @contextmenu="onContextMenu($event, item, elem)"
                  @touchstart.passive="dragStart($event, elem)"
                >
                <!-- img 路径这样拼凑避免更新后路径一致图片使用缓存不更新 -->
                  <t-image
                    v-if="!elem.svg && elem.image"
                    :src="elem.image +(activeAssets === 'user'?'':('?' + Math.random()))"
                    :lazy="true"
                    fit="contain"
                    @load="loadImage(elem)"
                  />

                  <div class="svg-box" v-else-if="elem.svg" v-html="elem.svg" />
                  <svg v-else class="l-icon" aria-hidden="true">
                    <use :xlink:href="'#' + elem.icon"></use>
                  </svg>
                  <p :title="elem.name">{{ elem.name }}</p>
                  <div class="price" v-if="elem.price > 0">
                    ￥{{ elem.price }}
                  </div>
                </div>
              </template>
              <div
                v-if="!item.list || !item.list.length"
                class="gray"
                style="white-space: nowrap; margin-left: 34px"
              >
                {{$t( '暂无数据' )}}
              </div>
            </t-collapse-panel>
          </t-collapse>
        </template>
        <!-- <div class="div-manage" v-if="['设备', '素材'].includes(activedGroup)">
          <t-button
            class="w-full"
            @click="onManageGraphic"
            style="height: 30px;color:var(--color) !important;"
          >
            {{ activedGroup }}管理
          </t-button>
        </div> -->
      </div>
      </template>
    </div>

    <div
      class="context-menu-box"
      ref="contextmenuDom"
      v-show="contextmenu.visible"
      tabindex="0"
      :style="contextmenu.style"
      @blur="hideContextmenu"
    >
      <t-menu
        class="context-menu"
        @change="onMenu"
        expandType="popup"
        v-model="contextmenu.activeValue"
      >
        <t-submenu
          value="move"
          :title="$t('移动到')"
          v-if="contextmenu.subMenus.length"
          :disabled="contextmenu.component['3d']"
          :popupProps = "popupProps"
        >
          <t-menu-item
            v-for="subMenu in contextmenu.subMenus"
            :value="'move:' + subMenu.name"
          >
            {{ subMenu.name }}
          </t-menu-item>
        </t-submenu>
        <t-submenu
          value="moveTo"
          :title="$t('移动到')+`${$t(activedGroup==='方案'?'模板':'方案')}`"
          v-if="['方案', '模板'].includes(activedGroup)"
          :disabled="contextmenu.component['3d']"
          :popupProps = "popupProps"
        >
          <t-menu-item
            v-for="subMenu in moveGroups[activedGroup==='方案'?'模板':'方案']"
            :value="'moveTo:' + subMenu.name"
          >
            {{ subMenu.name }}
          </t-menu-item>
        </t-submenu>
        <t-menu-item value="edit" :disabled="activedGroup === '图片'">
          {{$t( '编辑' )}}
        </t-menu-item>
        <t-menu-item value="del" :disabled="contextmenu.component['3d']">
          {{$t( '删除' )}}
        </t-menu-item>
      </t-menu>
    </div>

    <t-dialog
      v-if="delDialog.show"
      theme="danger"
      :header="$t('删除')"
      :visible="true"
      @close="delDialog.show = false"
      @confirm="delComponent"
    >
      {{current?$t('检测到该图纸正在被编辑，'):''}}{{$t( '确定删除该数据吗？' )}}{{current?$t('画布将被清空，'):''}}{{$t( '删除后不可恢复！' )}}
    </t-dialog>
    <!-- <t-dialog
      v-if="chargeDialog.show"
      :header="chargeDialog.data.name"
      :visible="true"
      @close="chargeDialog.show = false"
      width="70%"
      :top="8"
    >
      <t-image :src="chargeDialog.data.image" />
      <template #footer>
        <div class="flex between" style="margin-top: -7px">
          <p>付费项目，购买后查看并使用</p>
          <div>
            <label>金额：</label>
            <label class="bland">￥{{ chargeDialog.data.price }}</label>
            <t-button class="primary ml-12" @click="onSubmitOrder"
              >购买</t-button
            >
          </div>
        </div>
      </template>
    </t-dialog> -->

    <t-dialog
     class="dialog-charge"
      v-if="chargeDialogShow"
      :header="chargeDialog.name"
      :visible="true"
      @close="chargeDialogShow = false"
      width="80%"
      :top="8"
      :footer="false"
      :closeOnOverlayClick="false"
    >
    <iframe
      :src="`https://${rootDomain.slice(1)}/enterprise/preview?product=v&id=${chargeDialog.data.id}`"
      frameborder="no"
      scrolling="no"
      allowtransparency="true"
    />
    </t-dialog>
    <t-dialog
      v-if="wechatPayDialog.show"
      v-model:visible="wechatPayDialog.show"
      class="pay-dialog"
      :header="$t('乐吾乐收银台')"
      :close-on-overlay-click="false"
      :top="95"
      :width="700"
      :confirm-btn="$t('支付完成')"
      :cancel-btn="null"
      @close="getPayResult"
      :footer="false"
    >
      <Pay
        :order="wechatPayDialog.order"
        :alipay-url="wechatPayDialog.order.alipayUrl"
        :code-url="wechatPayDialog.order.codeUrl"
        @success="onChargeSuccess"
      />
    </t-dialog>

    <t-dialog
      class="dialog-manage"
      :header="$t(activedGroup) + $t('管理')"
      :visible="manageDialog.show"
      @close="manageDialog.show = false"
      @confirm="manageConfirm"
      width="90%"
      :top="8"
    >
      <div class="manage-body">
        <t-collapse v-model="activedPanels[activedGroup]">
          <t-collapse-panel
            :value="item.name"
            v-for="item in manageDialog.data"
            :key="item.name"
          >
            <template #header>
              <div class="flex middle">
                {{ item.name }}
              </div>
            </template>
            <template v-for="elem in item.list">
              <div
                :style="{
                  background: elem.visible ? '#42516c' : '',
                }"
                class="graphic manage-list"
              >
                <t-checkbox v-model:checked="elem.visible"></t-checkbox>
                <t-image
                  :src="elem.image"
                  :lazy="true"
                  fit="contain"
                  @load="loadImage(elem)"
                />
              </div>
            </template>
            <div
              v-if="!item.list || !item.list.length"
              class="gray"
              style="white-space: nowrap; margin-left: 34px"
            >
              {{$t( '暂无数据' )}}
            </div>
          </t-collapse-panel>
        </t-collapse>
      </div>
    </t-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { MessagePlugin } from 'tdesign-vue-next';
import axios from 'axios';
import { deepClone } from '@meta2d/core';

import { cases, shapes, formComponents, templates } from '@/services/defaults';
import { charts } from '@/services/echarts';
import { getFolders, makeSvg } from '@/services/png';
import {
  addCollection,
  delImage,
  getComponentsList,
  getLe5leV,
  updateCollection,
  getCollectionList,
  imageDrive,
} from '@/services/api';
import { convertPen } from '@/services/upgrade';
import { isGif } from '@/services/utils';
import { autoSave, delAttrs, blank, useFolder, chargeDialogShow } from '@/services/common';
import { debounce, throttle } from '@/services/debouce';
import { searchObjectPinyin } from '@/services/pinyin';
import { getCookie } from '@/services/cookie';
import { parseSvg } from '@meta2d/svg';
import Pay from './Pay.vue';
import { filename } from '@/services/file';
import { useUser } from '@/services/user';
import { iframeCustom, rootDomain } from '@/services/defaults';
import { getLe5le3d } from '@/services/api';
import { useSelection } from '@/services/selections';
import localforage from 'localforage';
import { 
  MenuFoldIcon, 
  ImageIcon, 
  AddIcon, 
  EditIcon, 
  DeleteIcon, 
  DesktopIcon, 
  RootListIcon, 
  ControlPlatformIcon,
  ChartIcon, 
  RelativityIcon, 
  ChartBubbleIcon,
  TagIcon, 
  LayersIcon,
  SystemInterfaceIcon,
  TerminalRectangle1Icon,
  RssIcon,
  DataIcon,
  ArrowUpDown3Icon,
  WifiIcon
} from 'tdesign-icons-vue-next';
import { getNetJsDiagram } from '@/services/material';
import Data from './Data.vue';
import Structure from './Structure.vue';
import { useDot } from '@/services/common';

const { dot } = useDot();
const { user } = useUser();
const { setFolder, getFolder } = useFolder();
const router = useRouter();
const route = useRoute();
const { select } = useSelection();
const activedGroup = ref('');
const activeAssets = ref('system');
let groups = reactive([]);
let moveGroups = reactive<any>({
  '方案':[],
  '模板':[]
});
const systemGroups = [
  {
    icon: 'desktop',
    name: '方案',
    key: '',
    class: 'tow',
  },
  {
    icon: 'root-list',
    name: '模板',
    key: '',
  },
  {
    icon: 'relativity',
    name: '控件',
    key: '',
  },
  {
    icon: 'control-platform',
    name: '设备',
    key: '',
  },
  
  {
    icon: 'chart',
    name: '图表',
    key: 'chart',
  },
  {
    icon: 'image',
    name: '素材',
    key: '',
  },


  {
    icon: 'chart-bubble',
    name: '图形',
    key: 'shape',
  },
  {
    icon: 'l-zujian',
    name: '组件',
    key: 'chart',
    type: 'iconfont',
  },
  // {
  //   icon: 'app',
  //   name: '我的',
  //   key: '',
  // },
];
const userGroups = [
  {
    icon: 'desktop',
    name: '方案',
    key: '',
    class: 'tow',
  },
  {
    icon: 'root-list',
    name: '模板',
    key: '',
  },
  {
    icon: 'l-zujian',
    name: '组件',
    key: 'chart',
    type: 'iconfont',
  },
  {
    icon: 'image',
    name: '图片',
    key: '',
  },
  {
    icon: 'control-platform',
    name: '3D',
    key: '',
  },
];

const dataGroups = [
  {
    icon: 'data',
    name: '数据源',
    key: '',
  },
  {
    icon: 'install',
    name: '属性',
    key: '',
  },
  {
    icon: 'code',
    name: '解析',
    key: 'chart',
  },
  // {
  //   icon: 'system-interface',
  //   name: '数据模拟',
  //   key: '',
  // }
];
const structureGroups = [
  {
    icon: 'layers',
    name: '图层',
    key: '',
  },
  {
    icon: 'tag',
    name: '分组',
    key: '',
  }
];

groups = systemGroups;
const subGroups = ref<any[]>([]);
const groupType = ref(0);
const activedPanels = reactive<any>({});

const caseCaches = [];
const templateCaches = [];
const componentCaches = [];
const materials = [];
const pngs = [];
let jsDiagrams = [];

const components = [
  {
    name:"默认",
    list:[]
  }
];

let dropped = false;
const chargeDialog = reactive<any>({});
const wechatPayDialog = reactive<any>({
  show: false,
});
const manageDialog = reactive<any>({
  name: '',
  data: [],
  show: false,
});

const search = ref('');

const loading = ref(false);

const headers = {
  Authorization: 'Bearer ' + (getCookie('token') || ''),
};
const updataData = { directory: '/大屏/默认' };
let lastName = '方案';
let userLastName = '方案';
const assetsChange = (value) => {
  if (value === 'system') {
    groups = systemGroups;
    activedGroup.value = lastName;
  } else if (value === 'user') {
    groups = userGroups;
    activedGroup.value = userLastName;
  }else if(value === 'data'){
    groups = dataGroups;
    activedGroup.value = '数据源';
  }else if(value === 'structure'){
    groups = structureGroups;
    activedGroup.value = '图层';
  }
  groupChange(activedGroup.value);
};

const groupChange = async (name: string) => {
  activedGroup.value = name;
  groupType.value = 0;
  switch (name) {
    case '方案':
      if (activeAssets.value === 'system') {
        if (!caseCaches.length) {
          loading.value = true;
          caseCaches.push(...(await getCaseProjects('系统方案',true,false)));
          for (const group of cases) {
            group.list = [];
            for (const item of caseCaches) {
              if (item.case === group.name) {
                group.list.push(item);
              }
            }
          }
          loading.value = false;
        }

        groupType.value = 1;
        subGroups.value = cases;
        lastName = name;
      } else {
        // subGroups.value = await getUserProjects('le5leV');
        // groupType.value = 1;
        // await getPrivateProjects('le5leV');
        // userLastName = name;

        //用户方案
        subGroups.value = await getCollectionImageList('方案', 'v',false,false);
        moveGroups['方案'] = [];
        subGroups.value.forEach((item)=>{if(item.name!=='默认'){ moveGroups['方案'].push({name:item.name})}});
        groupType.value = 1;
        userLastName = name;
      }
      break;
    case '模板':
      if (activeAssets.value === 'system') {
        if (!templateCaches.length) {
          loading.value = true;
          templateCaches.push(...(await getCaseProjects('系统模板',true,true)));
          for (const group of templates) {
            group.list = [];
            for (const item of templateCaches) {
              if (item.case === group.name) {
                group.list.push(item);
              }
            }
          }
          loading.value = false;
        }

        groupType.value = 1;
        subGroups.value = templates;
        lastName = name;
      } else {
        // subGroups.value = await getUserProjects('le5leV-template');
        // groupType.value = 1;
        // await getPrivateProjects('le5leV-template');
        // userLastName = name;
        subGroups.value = await getCollectionImageList('模板', 'v',false,true);
        moveGroups['模板'] = [];
        subGroups.value.forEach((item)=>{if(item.name!=='默认'){ moveGroups['模板'].push({name:item.name})}});
        groupType.value = 1;
        userLastName = name;
      }
      break;
    case '图表':
      subGroups.value = charts;
      lastName = name;
      break;
    case '控件':
      subGroups.value = formComponents;
      lastName = name;
      break;
    case '素材':
      groupType.value = 1;
      if (!materials.length) {
        loading.value = true;
        materials.push(...(await getFolders('v/material')));
        loading.value = false;
        const _materials: string = await localforage.getItem(
          'le5leV-materials'
        );
        if (_materials) {
          Object.assign(materials, JSON.parse(_materials));
        }
      }
      subGroups.value = materials;
      lastName = name;
      break;
    case '设备':
      if (!pngs.length) {
        loading.value = true;
        pngs.push(...(await getFolders('png')));
        pngs.push(...(await getFolders('svg', true)));
        pngs.push(...jsDiagrams);
        loading.value = false;
        const _pngs: string = await localforage.getItem('le5leV-pngs');
        if (_pngs) {
          Object.assign(pngs, JSON.parse(_pngs));
        }
      }
      subGroups.value = pngs;
      lastName = name;
      break;
    case '图形':
      subGroups.value = shapes;
      lastName = name;
      break;
    case '组件':
      if (activeAssets.value === 'system') {
        if (!componentCaches.length) {
          loading.value = true;
          componentCaches.push(...(await getCaseProjects('系统组件',true,false)));
          loading.value = false;
          for (const component of componentCaches) {
            if(component.case){
             let group =  components.filter((item)=>{item.name===component.case});
             if(group&&group.length){
              group[0].list.push(component);
             }else{
              components.push({
                name:component.case,
                list:[component]
              })
             }
            }else{
              components[0].list.push(component);
            }
          }
        }
        groupType.value = 1;
        subGroups.value = components;
        lastName = name;
      } else {
          // subGroups.value = await getUserComponents();
        // groupType.value = 1;
        // await getPrivateGraphics();
        // userLastName = name;
        subGroups.value = await getCollectionImageList(
          '组件',
          'v.component',
          false,
          false
        );
        groupType.value = 1;
        userLastName = name;
      }
      break;
    case '图片':
      loading.value = true;
      subGroups.value = await getImageList();
      loading.value = false;
      userLastName = name;
      break;
    case '3D':
      subGroups.value = [
        {
          name: '3D',
          list: [],
        },
      ];
      groupType.value = 1;
      await getPrivateGraphics();
      userLastName = name;
      break;
  }
  // if (!activedPanels[name]) {
  activedPanels[name] = [];
  if(['素材','设备'].includes(name)){
    activedPanels[name].push(subGroups.value[0]?.name);
  }else{
    for (const item of subGroups.value) {
      activedPanels[name].push(item?.name);
    }
  }
  // }

  searchGraphics();
};
// TODO 获取方案文件
//获取方案文件夹
const getCollectionImageList = async (name?: string, collection?: string, system?:boolean, template?:boolean) => {
  //1. 获取网盘文件夹
  const fullpath = `/大屏/${name}`;
  let ret: { list: any[] } = await axios.post('/api/directory/list', {
    fullpath,
  });
  if (!ret) {
    return [];
  }
  let list = [];
  for (let i of ret.list) {
    if (
      i.fullpath !== `${fullpath}/默认` &&
      i.fullpath.split('/').length === 4
    ) {
      //不取当前文件夹
      list.push(i);
    }
  }
  const data = {
    // directory: `/大屏/${name}`,
    // query: {
    //   // folder: '',
    //   tags: name !== '组件' ? name : undefined,
    // },
    // userFlag,
    system,
    template
    // projection: {
    //   image: 1,
    //   id: 1,
    //   name: 1,
    //   tags: 1,
    //   folder: 1,
    //   component: 1,
    //   filename: 1,
    // },
  };
  if(!data.system){
    delete data.system;
  }
  const config = {
    params: {
      current: 1,
      pageSize: 1000,
    },
  };
  //2.请求所有图纸/组件数据
  const res: any = await getCollectionList(collection, data, config);

  //3.将数据对应到云盘文件夹
  const results = [];
  const resultsMap = {
    默认: [],
  };
  for (const item of list) {
    let folder = item.fullpath.split('/')[3];
    if (!resultsMap[folder]) {
      resultsMap[folder] = [];
    }
  }

  for (const item of res.list) {
    if(collection === 'v.component') {
      item.component = true;
    }
    if (item.folder && resultsMap[item.folder]) {
      resultsMap[item.folder].push(item);
    } else {
      resultsMap['默认'].push(item);
    }
  }
  for (const item of list) {
    let folder = item.fullpath.split('/')[3];

    results.push({
      name: folder,
      canEdited: true,
      id: item.id,
      list: resultsMap[folder],
    });
  }
  results.push({
    name: '默认',
    list: resultsMap['默认'],
  });

  return results;
};

const getImageList = async () => {
  let ret: { list: any[] } = await axios.post('/api/directory/list', {
    fullpath: '/大屏/图片',
  });
  if (!ret) {
    return [];
  }
  let list = [];
  for (let i of ret.list) {
    if (i.fullpath.split('/').length === 4) {
      //不取当前文件夹
      list.push(i);
    }
  }
  return await Promise.all(
    list.map(async (item) => {
      let secondDir = item.fullpath.split('/');
      const _ret: { list: any[]; total: number } = await axios.post(
        '/api/file/list',
        {
          type: '图片',
          directory: item.fullpath,
        },
        {
          params: {
            current: 1,
            pageSize: 100,
          },
        }
      );
      let list = _ret.list.map((_item) => {
        return {
          ..._item,
          image: _item.url || `/file${_item.filename}`,
          visible: true,
          folder: item.fullpath,
          id: _item.id || _item._id,
        };
      });
      return {
        name: secondDir[3],
        id: item.id || item._id,
        canEdited: secondDir[3] !== '默认',
        list: list,
      };
    })
  );
};

const getCaseProjects = async (name: string, system:boolean, template:boolean, current = 1, pageSize = 1000) => {
  const query: any = { tags: name };
  let collection = name == '系统组件' ? 'v.component' : 'v';
  let data = { system, template };
  if(!data.system){
    delete data.system;
  }
  const ret: any = await axios.post(
    `/api/data/${collection}/list`,
    data ,
    // {
    //   // query: {
    //   //   tags: "系统方案"
    //   // },
    //   //shared: true,
    //   // projection: "id,_id,name,image,price,case",
    //   // sort: { createdAt: 1 },
    //   // systemFlag
    //   system,
    //   template
    // },
    {
      params: {
        current,
        pageSize,
      },
    }
  );

  if (!ret) {
    return [];
  }
  for (const item of ret.list) {
    if (!item.id) {
      item.id = item._id;
    }
    if(name !== '系统组件'){
      item.draggable = false;
    }else{
      item.component = true;
    }
  }
  return ret.list;
};

// const getUserProjects = async (name: string, current = 1, pageSize = 1000) => {
//   const query: any = { tags: name };

//   const ret: any = await axios.post(
//     '/api/data/le5leV/list',
//     {
//       query,
//       projection: {
//         id: 1,
//         _id: 1,
//         name: 1,
//         image: 1,
//         price: 1,
//         case: 1,
//         folder: 1,
//       },
//       sort: { createdAt: 1 },
//     },
//     {
//       params: {
//         current,
//         pageSize,
//       },
//     }
//   );

//   if (!ret) {
//     return [];
//   }
//   for (const item of ret.list) {
//     if (!item.id) {
//       item.id = item._id;
//     }
//     item.draggable = false;
//   }
//   return ret.list;
// };

const getPrivateGroups = async () => {
  const list = [
    {
      name: '默认',
      list: [],
    },
  ];
  const config = {
    params: {
      current: 1,
      pageSize: 1000,
    },
  };
  let ret: any = await axios.post(
    '/api/data/folders/list',
    {
      // projection: {
      //   image: 1,
      //   _id: 1,
      //   name: 1,
      //   list: 1,
      // },
      projection:'image,id,name,list',
      // query: {
      //   type: `v-components`,
      // },
      sort: { createdAt: 1 },
    },
    config
  );
  if (!ret) {
    ret = { list: [] };
  }

  for (const item of ret.list) {
    item.canEdited = true;
  }

  list.push(...ret.list);
  list.push({
    name: '3D',
    list: [],
  });

  return list;
};

const getUserComponents = async () => {
  const list = [
    {
      name: '默认',
      list: [],
    },
  ];
  const config = {
    params: {
      current: 1,
      pageSize: 1000,
    },
  };
  let ret: any = await axios.post(
    '/api/data/folders/list',
    {
      // projection: {
      //   image: 1,
      //   _id: 1,
      //   name: 1,
      //   list: 1,
      // },
      projection:'image,id,name,list',
      // query: {
      //   type: `v.component`,
      // },
      sort: { createdAt: 1 },
    },
    config
  );
  if (!ret) {
    ret = { list: [] };
  }

  for (const item of ret.list) {
    item.canEdited = true;
  }
  list.push(...ret.list);
  return list;
};

const getUserProjects = async (type: string) => {
  const list = [
    {
      name: '默认',
      list: [],
    },
  ];
  const config = {
    params: {
      current: 1,
      pageSize: 1000,
    },
  };
  let ret: any = await axios.post(
    '/api/data/folders/list',
    {
      // projection: {
      //   image: 1,
      //   _id: 1,
      //   name: 1,
      //   list: 1,
      // },
      projection:'image,id,name,list',
      // query: {
      //   type,
      // },
      sort: { createdAt: 1 },
    },
    config
  );
  if (!ret) {
    ret = { list: [] };
  }
  for (const item of ret.list) {
    item.canEdited = true;
  }
  list.push(...ret.list);
  return list;
};

const getPrivateProjects = async (type: string) => {
  for (const item of subGroups.value) {
    if (!item.list.length) {
      item.loading = true;
      //TODO 方案/模板分类
      if (item.name === '默认') {
        const data = {
          // query: {
          //   folder: '',
          //   tags: type === 'v-template' ? '模板' : '方案',
          // },
          // projection: {
          //   image: 1,
          //   _id: 1,
          //   name: 1,
          //   tags: 1,
          // },
          projection:'image,id,name,tags'
        };
        const config = {
          params: {
            current: 1,
            pageSize: 1000,
          },
        };
        const res: any = await getCollectionList('v', data, config);
        if (res?.list) {
          // res.list.forEach((item) => {
          //   item.draggable = false;
          // })
          item.list = res.list;
          // if (type === 'le5leV') {
          //   //过滤模板
          //   // item.list = res.list.filter((item) => !item.isTemplate);
          // }
        }
      }
      item.loading = false;
    }
  }
};

const dragStart = async (event: DragEvent | MouseEvent|TouchEvent, item: any) => {
  // event.stopPropagation();
  if (!item) {
    return;
  }

  meta2d.canvas.addCaches = [];
  dropped = false;

  let data = null;
  const id = item.id || item._id;
  let isAsync: boolean;
  if (
    activeAssets.value === 'user' &&
    ['方案', '模板'].includes(activedGroup.value)
  ) {
    if (!item._id) {
      item._id = item.id;
    }
    item.draggable = false;
    data = item.data || item;
    dropped =true;
  } else if (item.draggable === false) {
    //方案
    data = item.data || item;
    dropped =true;
  } else if (item['3d']) {
    const res: any = await getLe5le3d(item.id || item._id, "id, name, image");
    let iframe = (location.host.indexOf('.le5le')!==-1? 'https://view.le5le.com/3d?id=' :(location.origin+'/view/3d/?id=')) + (item.id || item._id)
    data = {
      name: 'iframe',
      x: 0,
      y: 0,
      tags: ['meta3d'],
      zIndex: 1,
      operationalRect: {
        x: 0.2,
        y: 0.2,
        height: 0.8,
        width: 0.6,
      },
      props: {
        custom: iframeCustom,
      },
      width: meta2d.store.data.width || meta2d.store.options.width,
      height: meta2d.store.data.height || meta2d.store.options.height,
      externElement: true,
      thumbImg: res.image,
      iframe,
    };
  } else if (item.component) {
    // 默认
    if (!item.componentDatas && !item.componentData) {
      isAsync = true;
      const ret: any = await axios.post(`/api/data/v.component/get`, {
        id,
      });
      ret.data.componentDatas[0].componentId = id;
      ret.data.componentDatas.forEach((item)=>{
          item.originId = item.id;
      });
      item.componentDatas = ret.data.componentDatas;
      item.componentData = ret.data.componentData;
    }
    if (item.componentData) {
      const pens = convertPen([item.componentData]);
      data = deepClone(pens);
    } else if (item.componentDatas) {
      data = deepClone(item.componentDatas);
    }
  } else if (item.data) {
    // 普通图元
    if(item.fullname || item.subClassName){
      // data = item;
      item.name = item.fullname;
      item.width = item.data.rect.width*4;
      item.height = item.data.rect.height*4;
      delete item.rect;
      data = item;
    }else{
      // 普通图元
      data = item.data;
      if(data.name==='tablePlus'){
        if(data.tableType === 'longlist'){
          const _data = new Array(100).fill(0)
          .map((_, row) => new Array(10).fill(0)
          .map((_, column) => `${row}, ${column}`));
          // _data.splice(0, 0, new Array(10).fill(0).map((_, i) =>String.fromCharCode(65+i)));
          _data.forEach((item,index)=>{
              item.splice(0, 0, index+1+'');
          })
          const columns = new Array(10).fill(0).map((_, i) =>{return {text:String.fromCharCode(65+i)}});
          columns.splice(0, 0, {text:''});
          data.data = _data;
          data.columns = columns;
        }
      }
    }
  } else if (item.image) {
    // 拖拽图片
    let target: any = event.target;
    target.children[0] && (target = target.children[0].children[0]);
    // firefox naturalWidth svg 图片 可能是 0
    const width = target.naturalWidth || target.width;
    const height = target.naturalHeight || target.height;
    const [name, lockedOnCombine] = await isGif(item.image)
      ? ['gif', 0]
      : ['image', undefined];

    data = {
      name,
      width,
      height,
      isBottom:true,
      image: item.image,
      imageRatio: true,
      ratio: true,
      lockedOnCombine,
    };
  } else {
    return;
  }

  if (!Array.isArray(data)) {
    data = deepClone([data]);
  }

  !dropped && (meta2d.canvas.addCaches = data);

  if (event instanceof DragEvent) {
    event.dataTransfer.setData(
      'Meta2d',
      isAsync ? undefined : JSON.stringify(data)
    );
  }
};

const dragstart = (event: any) => {
  event.target.style.opacity = 0.5;
};

const dragend = (event: any) => {
  event.target.style.opacity = 1;
};

const open = async (item: any) => {
  if (!item || item.draggable !== false) {
    return;
  }
  if(meta2d.store.data.pens.length && dot.value){
    MessagePlugin.info('请先保存当前画布或新建清空画布');
    return;
  }
  if (activeAssets.value === 'user') {
    router.push({
      path: '/',
      query: {
        r: Date.now() + '',
        id:item.id || item._id,
      },
    });
  } else {
    const ret: any = await getLe5leV(item._id || item.id);
    // if (!ret) {
    //   if (item.price > 0) {
    //     chargeDialog.data = item;
    //     chargeDialog.show = true;
    //   }
    //   return;
    // }
    if(!ret.data&&ret.price>0){
      chargeDialog.data = item;
      chargeDialogShow.value = true;
      return;
    }
    sessionStorage.setItem('opening', '1');
    router.push({
      path: '/',
      query: {
        r: Date.now() + '',
      },
    });

    for (const k of delAttrs) {
      delete ret[k];
      delete ret.data[k];
    }
    ret.data.name = ret.name;
    ret.data.case = ret.case;
    autoSave();
    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);
    meta2d.fitView();
  }
  select();
};

const getPrivateGraphics = async () => {
  for (const item of subGroups.value) {
    if (!item.list.length) {
      item.loading = true;
      if (item.name === '默认') {
        const data = {
          // query: { folder: '' },
          // projection: {
          //   image: 1,
          //   _id: 1,
          //   name: 1,
          //   component: 1,
          // },
          projection:'image,id,name,component'
        };
        const config = {
          params: {
            current: 1,
            pageSize: 1000,
          },
        };
        const res: any = await getComponentsList(data, config);
        if (res?.list) {
          item.list = res.list;
        }
      } else if (item.name === '3D') {
        const data = {
          // projection: {
          //   image: 1,
          //   _id: 1,
          //   name: 1,
          // },
          projection:"id, name, image"
        };
        const config = {
          params: {
            current: 1,
            pageSize: 1000,
          },
        };
        const res: any = await axios.post(
          '/api/data/3d/list',
          data,
          config
        );
        if (res?.list) {
          for (const item of res.list) {
            item['3d'] = true;
            item['draggable'] = true;
          }
          item.list = res.list;
        }
      }
      item.loading = false;
    }
  }
};

const editedFolder = ref<any>(undefined);
const onCreateFolder = () => {
  activedPanels[activedGroup.value].splice(
    0,
    activedPanels[activedGroup.value].length
  );

  editedFolder.value = {
    _id: '',
    name: '',
    label: '新建文件夹',
    list: [],
    edited: true,
    canEdited: true,
  };
  subGroups.value.splice(subGroups.value.length - 1, 0, editedFolder.value);
};

const createFoder = async () => {
  if (!editedFolder.value.label) {
    return;
  }
  if (editedFolder.value.label === editedFolder.value.name) {
    editedFolder.value.edited = false;
    return;
  }
  const found = subGroups.value.findIndex(
    (group: any) => group.name === editedFolder.value.label
  );
  if (found >= 0) {
    MessagePlugin.error('已经存在相同名称文件夹');
    return;
  }
  if (activeAssets.value !== 'user') {
    return;
  }
  if (editedFolder.value.id || editedFolder.value._id) {
    const ret: any = await axios.post('/api/directory/update', {
      oldFullpath: `/大屏/${activedGroup.value}/` + editedFolder.value.oldLabel,
      newFullpath: `/大屏/${activedGroup.value}/` + editedFolder.value.label,
    });
    if (ret) {
      editedFolder.value.name = editedFolder.value.label;
      editedFolder.value.edited = false;
    }
    //更新图纸的folder
    if (['组件', '方案', '模板'].includes(activedGroup.value)) {
      const collection =
        activedGroup.value === '组件' ? 'v.component' : 'v';
      editedFolder.value.list?.forEach(async (item) => {
        item.folder = editedFolder.value.label;
        await updateCollection(collection, {
          id: item.id || item._id,
          folder: editedFolder.value.label,
        });
      });
    }
  } else {
    const ret: any = await axios.post('/api/directory/add', {
      fullpath: `/大屏/${activedGroup.value}/` + editedFolder.value.label,
    });
    if (ret) {
      editedFolder.value.name = editedFolder.value.label;
      editedFolder.value.id = ret.id;
      editedFolder.value.edited = false;
    }
  }
};

const _createFoder = async () => {
  if (!editedFolder.value.label) {
    return;
  }
  if (editedFolder.value.label === editedFolder.value.name) {
    editedFolder.value.edited = false;
    return;
  }
  const found = subGroups.value.findIndex(
    (group: any) => group.name === editedFolder.value.label
  );
  if (found >= 0) {
    MessagePlugin.error('已经存在相同名称文件夹');
    return;
  }
  if (activeAssets.value !== 'user') {
    return;
  }

  if (['组件', '方案', '模板'].includes(activedGroup.value)) {
    if (editedFolder.value._id) {
      const ret: any = await axios.post('/api/data/folders/update', {
        _id: editedFolder.value._id,
        name: editedFolder.value.label,
      });
      if (ret) {
        editedFolder.value.name = editedFolder.value.label;
        editedFolder.value.edited = false;
      }
    } else {
      let type =
        activedGroup.value === '组件'
          ? 'v.component'
          : activedGroup.value === '模板'
          ? 'v-template'
          : 'v';
      const ret: any = await axios.post('/api/data/folders/add', {
        name: editedFolder.value.label,
        type,
        list: [],
      });
      if (ret) {
        editedFolder.value.name = editedFolder.value.label;
        editedFolder.value._id = ret._id;
        editedFolder.value.edited = false;
      }
    }
  } else if (activedGroup.value === '图片') {
    if (editedFolder.value._id) {
      const ret: any = await axios.post('/api/directory/update', {
        oldFullpath: '/大屏/' + editedFolder.value.oldLabel,
        newFullpath: '/大屏/' + editedFolder.value.label,
      });
      if (ret) {
        editedFolder.value.name = editedFolder.value.label;
        editedFolder.value.edited = false;
      }
    } else {
      const ret: any = await axios.post('/api/directory/add', {
        fullpath: '/大屏/' + editedFolder.value.label,
      });
      if (ret) {
        editedFolder.value.name = editedFolder.value.label;
        editedFolder.value._id = ret.id || ret._id;
        editedFolder.value.edited = false;
      }
    }
  }
};

const onEditHeader = (item: any) => {
  item.label = item.name;
  item.edited = true;
  item.oldLabel = item.name;
  editedFolder.value = item;
};

const onAdd = (item: any) => {
  blank();
  if (activedGroup.value === '方案') {
    item.vType = 'v';
  } else if (activedGroup.value === '模板') {
    item.vType = 'v-template';
  } else if (activedGroup.value === '组件') {
    item.vType = 'v.component';
  }
  setFolder(item);
  const query: any = {
    r: Date.now() + '',
    folder: item.name,
    tags: activedGroup.value,
  };
  if (activedGroup.value === '组件') {
    query.c = 1;
  }
  router.push({
    path: '/',
    query,
  });
  activeAssets.value = 'system';
  assetsChange('system');
  // meta2d.open({
  //   name: '新建项目',
  //   pens: [],
  //   enableMock: true,
  //   tags: activedGroup.value,
  //   folder: item.name,
  // } as any);
};

const onKeyHeader = (text: string, event: any) => {
  if (event.e.key === 'Escape') {
    editedFolder.value.edited = false;
  }
};

// 默认右键菜单
const contextmenu = reactive<any>({
  visible: false,
  style: {},
  // 子分类
  group: undefined,
  // 组件图纸
  component: {},
  // 右键二级子菜单
  subMenus: [],
});
const contextmenuDom = ref<any>(null);
const onContextMenu = async (e: MouseEvent, group: any, item: any) => {
  e.preventDefault();
  e.stopPropagation();

  if (activeAssets.value === 'system') {
    return;
  }

  contextmenu.group = group;
  contextmenu.component = item;

  if (document.body.clientHeight - e.clientY < 128) {
    contextmenu.style = {
      left: e.clientX + 'px',
      bottom: '4px',
    };
  } else {
    contextmenu.style = {
      left: e.clientX + 'px',
      top: e.clientY + 'px',
    };
  }

  if(!(moveGroups['模板']&&moveGroups['模板'].length)){
    let ret: { list: any[] } = await axios.post('/api/directory/list', {
        fullpath:"/大屏/模板",
    });
    moveGroups['模板'] = [];
    ret.list.forEach((item)=>{
      if(item.fullpath!=='/大屏/模板/默认'){
         moveGroups['模板'].push({name:item.fullpath.split('/')[3]})
      }
    });
  }
  if(!(moveGroups['方案']&&moveGroups['方案'].length)){
    let ret: { list: any[] } = await axios.post('/api/directory/list', {
        fullpath:"/大屏/方案",
    });
    moveGroups['方案'] = [];
    ret.list.forEach((item)=>{
      if(item.fullpath!=='/大屏/方案/默认'){
         moveGroups['方案'].push({name:item.fullpath.split('/')[3]})
      }
    });
  }
  contextmenu.subMenus = [];
  for (const elem of subGroups.value) {
    if (elem === group || elem.name === '默认' || elem.name === '3D') {
      continue;
    }
    contextmenu.subMenus.push(elem);
  }
  if(document.body.clientHeight/2<e.clientY){
    popupProps.value.overlayClassName = 'submenu-popup-overlay'
  }else{
    popupProps.value.overlayClassName = ''
  }
  contextmenu.visible = true;
  setTimeout(() => {
    if (contextmenuDom.value) {
      contextmenuDom.value.focus();
    }
  }, 500);
};

const delDialog = reactive<any>({
  contextmenuObj: {},
});
// TODO 右键菜单移动图纸
const onMenu = async (val: string) => {
  const id = contextmenu.component.id || contextmenu.component._id;
  setTimeout(() => {
    contextmenu.group = '';
    contextmenu.component = {};
    contextmenu.subMenus = [];
  }, 500);
  switch (val) {
    case 'edit':
      if (
        contextmenu.component.tags &&
        contextmenu.component.tags.includes('svg')
      ) {
        MessagePlugin.warning('解析的svg图元不允许编辑！');
        hideContextmenu();
        contextmenu.activeValue = 0;
        return;
      }
      // if (contextmenu.component.component) {
      if (activedGroup.value == '组件') {
        autoSave();
        router.push({
          path: '/',
          query: {
            id,
            c: 1,
            r: Date.now() + '',
          },
        });
      } else if (contextmenu.component['3d']) {
        let url = `https://3d${rootDomain}/?id=`;
        if (window.url3D) {
          url = window.url3D;
        }
        window.open(url + id, '_blank');
      } else {
        if ((contextmenu.group.id||contextmenu.group._id) && contextmenu.group.name !== '默认') {
          setFolder(contextmenu.group);
        }
        autoSave();
        //文件夹
        router.push({
          path: '/',
          query: {
            id,
            r: Date.now() + '',
          },
        });
      }
      hideContextmenu();
      break;
    case 'del':
      if(route.query.id===id){
        current.value = true;
      }else{
        current.value = false;
      }
      delDialog.show = true;
      Object.assign(delDialog.contextmenuObj, contextmenu);
      break;
    default:
      if(val.startsWith('moveTo:')){
        val = val.replace('moveTo:', '');

        //更新前端
        contextmenu.group.list.forEach((item: any, index: number, arr: any[]) => {
          if (id === item._id || id === item.id) {
            arr.splice(index, 1);
          }
        });

        //更新后端图纸
        let ret = await updateCollection('v', {
          id,
          folder: val === '默认' ? '' : val,
          system:false,
          template:activedGroup.value === '方案' ? true : false
          // userFlag:activedGroup.value === '方案' ? 2 : 1
        });
        if (!ret) {
          return;
        }
        (meta2d.store.data as any).isTemplate = activedGroup.value === '方案' ? true : false;
        (meta2d.store.data as any).template = activedGroup.value === '方案' ? true : false;
        (meta2d.store.data as any).folder = val === '默认' ? '' : val;
        
        //更新后端 图片
        let path: string =
        contextmenu.component.filename || contextmenu.component.image;
        if (imageDrive && path?.startsWith(imageDrive)) {
          path = path.slice(imageDrive.length);
        }
        if(path.startsWith('/file')) {
          path = '/api' + path;
        } else if(!path.startsWith('/api/file')) {
          path = '/api/file' + path;
        }
        await axios.patch(`${path}`, {
          // filenames: [filename],
          directory: `/大屏/${activedGroup.value==='方案'?'模板':'方案' }/${val || '默认'}`,
        });
        break;
      }
      if (val.indexOf('move:')) {
        return;
      }

      val = val.replace('move:', '');
      const group = contextmenu.subMenus.find(
        (element: any) => element.name === val
      );
      if (!group) {
        return;
      }
      // 前端: 添加组件到目标文件夹
      let data: any;
      if (contextmenu.component.component) {
        data = {
          component: true,
          image: contextmenu.component.image,
          name: contextmenu.component.name,
          visible: true,
          _id: contextmenu.component._id || contextmenu.component.id,
          filename: contextmenu.component.filename,
        };
      } else {
        data = {
          image: contextmenu.component.image,
          name: contextmenu.component.name,
          tags: contextmenu.component.tags,
          visible: true,
          _id: contextmenu.component._id || contextmenu.component.id,
          filename: contextmenu.component.filename,
        };
      }
      group.list.push(data);
      // 前端：从源文件夹移出组件
      contextmenu.group.list.forEach((item: any, index: number, arr: any[]) => {
        if (id === item._id || id === item.id) {
          arr.splice(index, 1);
        }
      });
      if (activedGroup.value !== '图片') {
        let collection = activedGroup.value === '组件'
          ? 'v.component'
          : 'v';
        // 更新后端组件信息
        let ret = await updateCollection(collection, {
          id,
          folder: val === '默认' ? '' : val,
        });
        if (!ret) {
          return;
        }
      }

      // // 更新后端源文件夹列表
      // if (contextmenu.group.name !== '默认') {
      //   await axios.post('/api/data/folders/update', {
      //     _id: contextmenu.group._id || contextmenu.group.id,
      //     list: contextmenu.group.list,
      //   });
      // }

      // 更新后端目标文件夹列表
      // if (group.name !== '默认') {
      //   await axios.post('/api/data/folders/update', {
      //     _id: group._id || group.id,
      //     list: group.list,
      //   });
      // }
      // let filename: string =
      //   contextmenu.component.filename || contextmenu.component.image;
      // if (imageDrive && filename.startsWith(imageDrive)) {
      //   filename = filename.slice(imageDrive.length);
      // }
      let path: string =
        contextmenu.component.filename || contextmenu.component.image;
      //更新缩略图位置
      // await axios.post('/api/files/update', {
      //   filenames: [filename],
      //   'metadata.directory': `/大屏/${activedGroup.value}/${val || '默认'}`,
      // });
      // 原接口路径是 /api/file/{fullname}
      // 因为img的路径中包含file，所以做如下拼接
      
      if (imageDrive && path.startsWith(imageDrive)) {
        path = path.slice(imageDrive.length);
      }
      if(path.startsWith('/file')) {
        path = '/api' + path;
      } else if(!path.startsWith('/api/file')) {
        path = '/api/file' + path;
      }
      await axios.patch(`${path}`, {
        // filenames: [filename],
        directory: `/大屏/${activedGroup.value}/${val || '默认'}`,
      });
      break;
  }
  contextmenu.activeValue = 0;
};

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

const _delComponent = async () => {
  // const id = contextmenu.component._id || contextmenu.component.id;
  if (['组件', '方案', '模板'].includes(activedGroup.value)) {
    let collection = delDialog.contextmenuObj.component.component
      ? 'v.component'
      : 'v';
    const id =
      delDialog.contextmenuObj.component._id ||
      delDialog.contextmenuObj.component.id;
    try {
      await axios.post(`/api/data/${collection}/delete`, {
        id,
      });
    } catch (e) {
      console.error(e);
      return;
    }
    //删除缩略图
    if (delDialog.contextmenuObj.component.image) {
      await delImage(delDialog.contextmenuObj.component.image);
    }

    // 前端：从源文件夹移出组件
    delDialog.contextmenuObj.group.list.forEach(
      (item: any, index: number, arr: any[]) => {
        if (id === item._id || id === item.id) {
          arr.splice(index, 1);
        }
      }
    );

    // 更新后端源文件夹列表
    if (delDialog.contextmenuObj.group.name !== '默认') {
      await axios.post('/api/data/folders/update', {
        _id:
          delDialog.contextmenuObj.group._id ||
          delDialog.contextmenuObj.group.id,
        list: delDialog.contextmenuObj.group.list,
      });
    }
  } else {
    const id =
      delDialog.contextmenuObj.component._id ||
      delDialog.contextmenuObj.component.id;
    delDialog.contextmenuObj.group.list.forEach(
      (item: any, index: number, arr: any[]) => {
        if (id && (id === item._id || id === item.id)) {
          arr.splice(index, 1);
        }
        if (!id) {
          if (item.url === delDialog.contextmenuObj.component.url) {
            arr.splice(index, 1);
          }
        }
      }
    );
    await axios.post(`/api/files/delete`, {
      fullnames: [delDialog.contextmenuObj.component.filename],
      physically: true,
    });
  }
  delDialog.show = false;
  delDialog.contextmenuObj = {};

  MessagePlugin.success('删除成功');
};
const current = ref(false);
const delComponent = async () => {
  // const id = contextmenu.component._id || contextmenu.component.id;
  if (['组件', '方案', '模板'].includes(activedGroup.value)) {
    // let collection = delDialog.contextmenuObj.component.component
    //   ? 'v.component'
    //   : 'v';
    let collection = '';
    if(activedGroup.value == '组件') {
      collection = 'v.component'
    } else {
      collection = 'v'
    }
    const id =
      delDialog.contextmenuObj.component._id ||
      delDialog.contextmenuObj.component.id;
    try {
      await axios.post(`/api/data/${collection}/delete`, {
        id,
      });
    } catch (e) {
      console.error(e);
      return;
    }
    // 前端：从源文件夹移出组件
    delDialog.contextmenuObj.group.list.forEach(
      (item: any, index: number, arr: any[]) => {
        if (id === item._id || id === item.id) {
          arr.splice(index, 1);
        }
      }
    );
    if(current.value){
      router.push({
        path: '/',
        query: {
          r: Date.now() + '',
        },
      });
    };
  } else {
    const id =
      delDialog.contextmenuObj.component._id ||
      delDialog.contextmenuObj.component.id;
    delDialog.contextmenuObj.group.list.forEach(
      (item: any, index: number, arr: any[]) => {
        if (id && (id === item.id || id === item._id)) {
          arr.splice(index, 1);
        }
        if (!id) {
          if (item.url === delDialog.contextmenuObj.component.url) {
            arr.splice(index, 1);
          }
        }
      }
    );
  // }
  let fullname: string =
    delDialog.contextmenuObj.component.fullname ||
    delDialog.contextmenuObj.component.image;
  //if (imageDrive && fullname.startsWith(imageDrive)) {
  //  fullname = fullname.slice(imageDrive.length);
  //}
  if(fullname.startsWith('/file')) {
    fullname = fullname.slice('/file'.length);
  }
  if(fullname.startsWith('/api/file/')) {
    fullname = fullname.slice('/api/file/'.length);
  }
  await axios.post(`/api/files/delete`, {
    fullnames: [fullname],
    physically: true,
  });
  }
  delDialog.show = false;
  delDialog.contextmenuObj = {};

  MessagePlugin.success('删除成功');
};

const drop = (obj: any) => {
  dropped = true;

  if (obj) {
    Array.isArray(obj) && open(obj[0]);
  } else {
    MessagePlugin.warning('正在请求网络数据中，请稍后重试');
  }
};

const onSubmitOrder = async () => {
  const result: any = await axios.post('/api/order/datas/submit', {
    collection: 'v',
    id: chargeDialog.data.id||chargeDialog.data._id,
  });
  if (result) {
    wechatPayDialog.order = result;
    wechatPayDialog.show = true;
  }
};

const getPayResult = async () => {
  const result: { state: number } = await axios.post('/api/order/pay/state', {
    id: wechatPayDialog.order.id || wechatPayDialog.order._id,
  });
  if (result && result.state) {
    return true;
  }
};

const onChargeSuccess = () => {
  MessagePlugin.success('支付成功！');
  wechatPayDialog.show = false;
  chargeDialog.show = false;
};

const onSearch = () => {
  debounce(searchGraphics, 300);
};

const searchGraphics = async () => {
  if (search.value) {
    activedPanels[activedGroup.value].splice(
      0,
      activedPanels[activedGroup.value].length
    );
  }

  for (const group of subGroups.value) {
    let flag = true;
    for (const item of group.list) {
      if (search.value) {
        if(['方案','模版','3D','图片','组件'].includes(activedGroup.value)){
          item.visible = item.name.indexOf(search.value) > -1
        }else{
          item.visible = searchObjectPinyin(item, 'name', search.value);
        }
        if(item.visible){
          flag = false;
        }
      } else {
        item.visible = true;
        flag = false;
      }
    }
    if(!search.value && !group.list.length){
      flag = false;
    }
    if(flag){
      group.visible = false;
    }else{
      group.visible = true;
    }
    if (search.value) {
      activedPanels[activedGroup.value].push(group.name);
    }
  }
};

const onFold = () => {
  if (!activedPanels[activedGroup.value]) {
    return;
  }

  if (activedPanels[activedGroup.value].length) {
    activedPanels[activedGroup.value] = [];
  } else {
    activedPanels[activedGroup.value] = [];
    for (const item of subGroups.value) {
      activedPanels[activedGroup.value].push(item.name);
    }
  }
};

const loadImage = (elem: any) => {
  if (elem.isSvg) {
    makeSvg(elem);
    if (activedGroup.value === '设备') {
      throttle(renderPngGroup, 100);
    }
  }
};

const renderPngGroup = () => {
  subGroups.value = pngs;
};

let uploadGroup: any;
const onSelectFiles = (item: any) => {
  uploadGroup = item;
};

const beforeUpload = (file: any) => {
  if (!(user && user.id)) {
    MessagePlugin.warning('请先登录！');
    return false;
  }
  return true;
};

/*
 * @description 根据上传的文件处理为meta2d能够识别的内容
 * */
function processFileObj(fileObj, c) {
  return new Promise((resolve) => {
    if (fileObj.name.endsWith('.svg')) {
      let fileReader = new FileReader();
      fileReader.readAsText(fileObj.raw);
      fileReader.onload = async () => {
        let svgText = fileReader.result;
        c.componentDatas = parseSvg(svgText as string);
        c.component = true;
        c.tags = ['svg'];
        resolve(c);
      };
    } else {
      // 除了svg 其他一律按照图片处理，这样是否会有问题？
      resolve(c);
    }
  });
}

const fileSuccessed = async (content: any) => {
  // 组件中去掉了上传图片入口
  // if (activedGroup.value === '组件') {
  //   const c: any = {
  //     name: filename(content.file.name),
  //     image:
  //       content.response.url ||
  //       content.response.metadata.url ||
  //       `/file${content.response.filename}`,
  //     folder: uploadGroup.name === '默认' ? '' : uploadGroup.name,
  //   };
  //   let rst = await processFileObj(
  //     { raw: content.file.raw, name: content.file.name },
  //     c
  //   );
  //   const ret: any = await addCollection('v.component', rst);
  //   c._id = ret._id || ret.id;
    // if (ret && uploadGroup.name !== '默认') {
    //   if (!uploadGroup.list) {
    //     uploadGroup.list = [];
    //   }

    //   uploadGroup.list.push(c);
    //   await axios.post('/api/data/folders/update', {
    //     _id: uploadGroup._id || uploadGroup.id,
    //     list: uploadGroup.list,
    //   });
    // } else {
    //   if (!uploadGroup.list) {
    //     uploadGroup.list = [];
    //   }
    //   uploadGroup.list.push(c);
    // }
  //   uploadGroup.list.push(c);
  // } else if (activedGroup.value === '图片') {
    uploadGroup.list.push({
      ...content.response,
      image:
        content.response.url ||
        content.response.metadata.url ||
        `/file${content.response.filename}`,
      visible: true,
      folder: content.response.directory || content.response.metadata.directory,
    });
  // }
  MessagePlugin.success('上传成功');
};

const delFolder = async (item: any) => {
  if (item.list?.length) {
    MessagePlugin.error('文件夹不为空！');
    return;
  }

  const id = item.id || item._id;
  let ret: any;
  if (activeAssets.value !== 'user') {
    return;
  }
  // if (['组件', '方案', '模板'].includes(activedGroup.value)) {
  //   ret = await axios.post('/api/data/folders/delete', {
  //     id,
  //   });
  // } else if (activedGroup.value === '图片') {
  //   ret = await axios.post('/api/directory/delete', {
  //     fullpaths: [`/大屏/${item.name}`],
  //   });
  // }

  ret = await axios.post('/api/directory/delete', {
    fullpaths: [`/大屏/${activedGroup.value}/${item.name}`],
    physically: true
  });
  if (ret) {
    const i = subGroups.value.findIndex(
      (elem: any) => id === elem._id || id === elem.id
    );
    i >= 0 && subGroups.value.splice(i, 1);
  }
};

const reloadCurrent = () => {
  groupChange(activedGroup.value);
};

const updateAfterSave = (e) => {
  if (activeAssets.value === 'user') {
    if (e === 'v.component' && activedGroup.value === '组件') {
      groupChange('组件');
    } else if (e === 'v-template' && activedGroup.value === '模板') {
      groupChange('模板');
    } else if (e === '' && activedGroup.value === '方案') {
      groupChange('方案');
    }
  }
};

const onManageGraphic = () => {
  if (activedGroup.value === '素材') {
    materials.forEach((item) => {
      item.list.forEach((_item) => {
        if(_item.visible === undefined){
          _item.visible = true;
        }
      });
    });
    manageDialog.data = deepClone(materials);
  } else if (activedGroup.value === '设备') {
    pngs.forEach((item) => {
      item.list.forEach((_item) => {
        if(_item.visible === undefined){
          _item.visible = true;
        }
      });
    });
    manageDialog.data = deepClone(pngs);
  }
  manageDialog.show = true;
};

const manageConfirm = () => {
  //TODO 后续存放到后端 目前本地存储
  if (activedGroup.value === '素材') {
    localforage.setItem('le5leV-materials', JSON.stringify(manageDialog.data));
    materials.length = 0;
    materials.push(...manageDialog.data);
  } else if (activedGroup.value === '设备') {
    localforage.setItem('le5leV-pngs', JSON.stringify(manageDialog.data));
    pngs.length = 0;
    pngs.push(...manageDialog.data);
  }
  subGroups.value = manageDialog.data;
  manageDialog.show = false;
};

onMounted(() => {
  //js线性图元
  setTimeout(()=>{
    if (globalThis.meta2dTools?.length !== globalThis.jsDiagramNum) {
      let jsLoadInterval = setInterval(() => {
        if (globalThis.meta2dTools?.length == globalThis.jsDiagramNum) {
          getJsDiagram();
          clearInterval(jsLoadInterval);
        }
      }, 500);
    } else {
      getJsDiagram();
    }
  },100);
  groupChange('方案');
  document.addEventListener('dragstart', dragstart, false);
  document.addEventListener('dragend', dragend, false);

  setTimeout(() => {
    meta2d.on('drop', drop);
    meta2d.on('logout', reloadCurrent);
    meta2d.on('business-save', updateAfterSave);
    meta2d.on('business-assets', changeAssets);
  }, 2000);
});

function getJsDiagram() {
  if (globalThis.registerToolsNew) {
    (window as any).registerToolsNew();
    const temJSClass = [];
    const temJSMaterial = [];
    globalThis.meta2dTools.forEach((item: any) => {
      if (temJSClass.indexOf(item.subClassName) === -1) {
        temJSClass.push(item.subClassName);
        temJSMaterial.push({
          name: item.subClassName,
          show: true,
          list: [],
        });
      }
      temJSMaterial.forEach((_class: any) => {
        if (_class.name === item.subClassName) {
          _class.list.push(item);
        }
      });
    });
    jsDiagrams.push(...temJSMaterial);
    // 切换回页面仍需要注册，所以此处不清空
    // window.meta2dTools = undefined;
  }
}

const changeAssets = (e)=>{
  if(e){
    activeAssets.value = 'system';
    assetsChange( activeAssets.value);
  }
}

const popupProps = ref({
  overlayClassName:'',
});

onUnmounted(() => {
  document.removeEventListener('dragstart', dragstart);
  document.removeEventListener('dragend', dragend);

  meta2d.off('drop', drop);
  meta2d.off('logout', reloadCurrent);
  meta2d.off('business-save', updateAfterSave);
  meta2d.off('business-assets', changeAssets);
});
</script>
<style lang="postcss" scoped>
.graphics {
  display: flex;
  flex-direction: column;
  background-color: var(--color-background);
  /* z-index: 2; */
  .group-asset {
    height: 40px;
    justify-content: center;
    align-items: center;
    display: flex;
    .t-radio-group.t-radio-group--filled {
      padding: 0px;
      height: 32px;
      background-color: #fff0;
      .t-radio-button::before{
        content: none;
      }
    }
    :deep(.t-radio-button__label) {
      margin: auto;
    }
    .t-radio-button {
      width: 72px;
      height: 32px;
      color: var(--color);
      padding: 0px;
      &:hover {
        color: var(--color-primary);
      }
      &.t-is-checked {
        background-color: var(--color-primary) !important;
        color: #fff !important;
        border-radius: 3px;
        margin: 1px;
        height: 28px;
      }
    }
  }
  .groups-panel {
    display: grid;
    grid-template-columns: 50px 250px;
    border-top: 1px solid var(--color-background-input);
    flex-grow: 1;
    overflow-y: auto;
    font-size: 12px;
    z-index: 2;

    .groups {
      max-height: calc(100vh - 80px);
      overflow-y: auto;
      background: var(--color-background-groups);
      & > div {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 16px 4px;
        line-height: 1;
        cursor: pointer;
        span{
          width: 6ch;
          line-height: 15px;
          padding-left: 2px;
          text-align: center;
        }
        .t-icon {
          font-size: 20px;
          margin-bottom: 8px;
        }
        .l-icon {
          font-size: 24px;
          margin-bottom: 8px;
        }
        &:hover {
          color: var(--color-primary);
        }
      }

      .active {
        background-color: var(--color-background-active);
        color: var(--color-primary);
        border-left: 2px solid var(--color-primary);
      }
    }

    .list {
      overflow-y: auto;
      max-height: calc(100vh - 80px);
      background-color: var(--color-background-active);
      /* padding-top: 8px; */
      .input-search {
        flex-shrink: 0;
        /* height: 40px; */
        position: sticky;
        top: 0px;
        z-index: 10;
        padding: 16px;
        color: #878f9c;
        margin-top: -10px;
        .btn {
          background: #fff0;
          img {
            background-color: #fff0;
            margin-top: 9px;
          }
          /* .t-icon {
            background: #fff0;
          } */
        }
      }

      .div-manage {
        position: sticky;
        bottom: 2px;
        z-index: 10;
        margin-top: 800px;
      }

      * {
        background-color: var(--color-background-active);
      }

      :deep(.t-collapse) {
        /* min-height: 100vh; */
        border: none;
      }

      :deep(.t-collapse-panel__header) {
        border: none;
        font-size: 12px;
        font-weight: 400;
        padding: 8px 8px 8px 16px;

        & > .t-space {
          display: none;
        }

        & > .t-space:focus {
          display: inline-flex;
        }

        &:hover .t-collapse-panel__icon,
        &:hover > .flex {
          color: var(--color-primary);
        }

        .t-collapse-panel__icon,
        .t-collapse-panel__icon * {
          transition: none;
        }

        .t-icon {
          font-size: 13px;
        }
      }
      :deep(.t-collapse-panel__wrapper:hover) {
        .t-collapse-panel__header > .t-space {
          display: inline-flex;
        }
      }

      :deep(.t-collapse-panel__body) {
        border: none;
      }
      :deep(.t-collapse-panel__content) {
        background-color: var(--color-background-active);
        padding: 4px 4px 20px 4px;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-row-gap: 12px;
      }

      :deep(.t-loading--center) {
        width: 100px;
        .t-loading__text {
          margin-left: 8px;
          height: 24px;
        }
      }

      :deep(.t-image__error) {
        .t-space-item:last-child {
          display: none;
        }
      }

      :deep(.t-image__loading) {
        .t-space-item:last-child {
          display: none;
        }
      }

      .graphic {
        position: relative;
        padding: 10px 0;
        border-radius: 2px;
        border: 1px solid transparent;

        &:hover {
          cursor: pointer;
          border-color: var(--color-primary);
        }
        p {
          margin-top: 10px;
          padding: 0 8px;
          text-align: center;
          font-size: 12px;
          height: 12px;
          line-height: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          word-break: break-all;
          -webkit-box-orient: vertical;
        }
        .t-image__wrapper {
          height: 32px;
          width: 32px;
          margin: auto;
          :deep(.t-image) {
            border-radius: 2px;
          }
        }

        svg {
          color: var(--color);
          height: 32px;
          width: 100%;
          margin: auto;
        }

        .svg-box {
          height: 32px;
          width: 32px;
          margin-left: calc(50% - 16px);
          margin-top: 10px;
          margin-bottom: 10px;
          &:deep(svg) {
            height: 100%;
            width: 100%;
            .cls-1 {
              stroke: var(--color) !important;
              stroke-width: 4px;
              fill: none;
              stroke-dasharray: none;
              opacity: 1;
            }
            path{
              stroke: var(--color) !important;
            }
          }
        }

        .price {
          position: absolute;
          top: 8px;
          right: 8px;
          display: inline-block;
          z-index: 1;
          border-radius: 2px;
          background-color: #ff400060;
          color: var(--color-bland);
          font-size: 10px;
          line-height: 1;
          padding: 3px;
        }
      }
    }

    .two-columns {
      :deep(.t-collapse-panel__content) {
        grid-template-columns: 1fr 1fr;
      }
      .graphic {
        .t-image__wrapper {
          width: 100px;
          height: 56.25px;
          background-color: '#162030';
        }
      }
    }
  }

  .context-menu-box {
    position: fixed;
    z-index: 200;
    & > div {
      width: 140px !important;
      position: static;
    }

    :deep(.t-menu) {
      .t-menu__item {
        &.t-is-opened {
          background-color: var(--color-background-popup-hover);
          transition: none !important;
        }
      }
      .t-fake-arrow {
        transform: rotate(-90deg) !important;
      }

      .t-fake-arrow--active {
        transform: rotate(90deg) !important;
      }
    }
  }

  :deep(.dialog-manage) {
    .t-dialog__body {
      height: 500px;
      overflow: scroll;
    }
    .t-collapse {
      border: 0px;
    }
    .t-collapse-panel__header {
      border: 0px;
    }

    .t-collapse-panel__body {
      border: 0px;
    }
    .t-collapse-panel__content {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr;
      /* grid-template-rows: repeat(100, 100px); */
      grid-auto-rows: minmax(100px, auto);

      grid-row-gap: 20px;
      grid-column-gap: 20px;
    }
    .t-collapse-panel__body {
      background: #fff0;
    }
    .manage-list {
      max-height: 310px;
      border: 1px solid #fff;
      position: relative;
      border: 1px solid #535f79;
      position: relative;
      border-radius: 2px;
      .t-checkbox {
        position: absolute;
        right: 0px;
        top: 10px;
        z-index: 10;
      }
    }
  }

  :deep(.dialog-charge){
    .t-dialog__body {
      iframe{
        width: 100%;
        height: 80vh;
      }
    }
  }
}
</style>
<style lang="postcss">
.submenu-popup-overlay{
  .t-menu__popup{
    bottom: 0 !important;
    top: auto !important;
  }
}
</style>