<template>
  <div class="app-header">
    <a class="logo" :href="enterprise.home" target="_blank">
      <img src="/favicon.ico" />
      <span> {{ enterprise.name }}</span>
    </a>
    <t-dropdown
      :minColumnWidth="200"
      :maxHeight="560"
      :delay2="[10, 150]"
      overlayClassName="header-dropdown"
      trigger1="click"
    >
      <a> 文件 </a>
      <t-dropdown-menu>
        <t-dropdown-item @click="newFile">
          <a>新建文件</a>
        </t-dropdown-item>
        <t-dropdown-item @click="load(true)">
          <a>打开文件</a>
        </t-dropdown-item>
        <t-dropdown-item divider="true" @click="load">
          <a>导入文件</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="save()">保存</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="save(SaveType.SaveAs, '', undefined, 1)">另存为</a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="downloadJson">下载JSON文件</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="downloadZip">
            <div class="flex">
              导出为ZIP文件 <span class="flex-grow"></span>
              <!-- <span><label>VIP</label></span> -->
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="downloadHtml">
            <div class="flex">
              下载离线部署包 <span class="flex-grow"></span>
              <!-- <span><label>企</label></span> -->
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="downloadVue3">
            <div class="flex">
              下载Vue3组件包 <span class="flex-grow"></span>
              <!-- <span><label>企</label></span> -->
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="downloadVue2">
            <div class="flex">
              下载Vue2组件包 <span class="flex-grow"></span>
              <!-- <span><label>企</label></span> -->
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="downloadReact">
            <div class="flex">
              下载React组件包 <span class="flex-grow"></span>
              <!-- <span><label>企</label></span> -->
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="downloadPng">下载为PNG</a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="downloadSvg">下载为SVG</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="switchTheme('light')">明亮主题</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="switchTheme('dark')">暗黑主题</a>
        </t-dropdown-item>
      </t-dropdown-menu>
    </t-dropdown>
    <t-dropdown
      :minColumnWidth="180"
      :maxHeight="500"
      :delay2="[10, 150]"
      overlayClassName="header-dropdown"
    >
      <a> 编辑 </a>
      <t-dropdown-menu>
        <t-dropdown-item>
          <a @click="onUndo">
            <div class="flex">
              撤销 <span class="flex-grow"></span> Ctrl + Z
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="onRedo">
            <div class="flex">
              重做 <span class="flex-grow"></span> Ctrl + Y
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onCut">
            <div class="flex">
              剪切 <span class="flex-grow"></span> Ctrl + X
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onCopy">
            <div class="flex">
              复制 <span class="flex-grow"></span> Ctrl + C
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="onPaste">
            <div class="flex">
              粘贴 <span class="flex-grow"></span> Ctrl + V
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onAll">
            <div class="flex">
              全选 <span class="flex-grow"></span> Ctrl + A
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onDelete">
            <div class="flex">删除 <span class="flex-grow"></span> DELETE</div>
          </a>
        </t-dropdown-item>
      </t-dropdown-menu>
    </t-dropdown>
    <t-dropdown
      :minColumnWidth="180"
      :maxHeight="500"
      :delay2="[10, 150]"
      overlayClassName="header-dropdown"
    >
      <a> 工具 </a>
      <t-dropdown-menu>
        <t-dropdown-item>
          <a @click="onScaleWindow">窗口大小</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onScaleUp">放大</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onScaleDown">缩小</a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="onScaleFull">100%视图</a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="showMap">
            <div class="flex middle">
              鹰眼地图 <span class="flex-grow"></span>
              <!-- <t-icon v-show="map" name="check" /> -->
              <check-icon v-show="map" />
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="showMagnifier">
            <div class="flex middle">
              放大镜 <span class="flex-grow"></span>
              <!-- <t-icon v-show="magnifier" name="check" /> -->
              <check-icon v-show="magnifier" />
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onAutoAnchor">
            <div class="flex middle">
              自动锚点 <span class="flex-grow"></span>
              <!-- <t-icon v-show="autoAnchor" name="check" /> -->
              <check-icon v-show="autoAnchor" />
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a @click="onDisableAnchor">
            <div class="flex middle">
              显示锚点 <span class="flex-grow"></span>
              <!-- <t-icon v-show="showAnchor" name="check" /> -->
              <check-icon v-show="showAnchor" />
            </div>
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="onToggleAnchor">
            <div
              class="flex"
              :style="{
                color: showAnchor ? '' : '#4f5b75',
              }"
            >
              添加/删除锚点 <span class="flex-grow"></span> A
            </div>
          </a>
        </t-dropdown-item>
      </t-dropdown-menu>
    </t-dropdown>
    <t-dropdown
      :minColumnWidth="180"
      :maxHeight="500"
      :delay2="[10, 150]"
      overlayClassName="header-dropdown"
    >
      <a> 帮助 </a>
      <t-dropdown-menu>
        <t-dropdown-item
          v-for="item in enterprise.helps_v"
          :divider="item.divider"
        >
          <a :href="item.url" target="_blank">{{ item.name }}</a>
        </t-dropdown-item>
      </t-dropdown-menu>
    </t-dropdown>

    <!-- <div style="width: 148px; flex-shrink: 0"></div> -->
    <input v-model="meta2dData.name" @change="onInputName($event)" />

    <a :href="enterprise.account" target="_blank">
      <!-- <t-icon name="home" /> -->
      <home-icon />
      账户中心
    </a>
    <a :href="enterprise['v']" target="_blank" class="active">
      <!-- <t-icon name="desktop" /> -->
      <desktop-icon />
      大屏可视化
    </a>
    <a :href="enterprise['3d']" target="_blank">
      <!-- <t-icon name="control-platform" /> -->
      <control-platform-icon />
      3D可视化
    </a>
    <a :href="enterprise['2d']" target="_blank">
      <!-- <t-icon name="app" /> -->
      <app-icon />
      2D可视化
    </a>
    <t-dropdown
      v-if="user.id"
      :minColumnWidth="200"
      :maxHeight="500"
      :delay2="[10, 150]"
      overlayClassName="custom-dropdown header"
    >
      <a style="margin-left: 32px; margin-right: 12px">
        <t-avatar
          size="small"
          :image="user.avatarUrl ? user.avatarUrl : baseUrl + 'img/avatar.png'"
        />
      </a>
      <t-dropdown-menu>
        <t-dropdown-item divider="true">
          <a :href="enterprise.account" target="_blank">
            {{ user.username }}
            <label
              class="ml-16 vip-label"
              :style="{
                color: user.limit > 1 ? '#ff4000' : '#D5C781',
                background: user.limit > 1 ? '#ff400030' : '#D5C78133',
              }"
              >VIP</label
            >
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a :href="`${enterprise.account}/v`" target="_blank"> 我的大屏 </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a :href="`${enterprise.account}/account/teams`" target="_blank">
            我的团队
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a :href="`${enterprise.account}/account/info`" target="_blank">
            账号信息
          </a>
        </t-dropdown-item>
        <t-dropdown-item divider="true">
          <a :href="`${enterprise.account}/account/security`" target="_blank">
            安全设置
          </a>
        </t-dropdown-item>
        <t-dropdown-item>
          <a @click="logout">退出</a>
        </t-dropdown-item>
      </t-dropdown-menu>
    </t-dropdown>
    <div class="flex middle" v-else>
      <a class="button primary solid" style="width: 80px" :href="login()">
        登录
      </a>
    </div>
  </div>
  <t-dialog
    v-if="payListDialog.show"
    v-model:visible="payListDialog.show"
    class="pay-dialog"
    :close-on-overlay-click="false"
    :top="95"
    :width="700"
    :cancel-btn="{
          content: '下载试用',
          variant: 'outline',
          style: {
            width: '100px',
            color:'#707B8F',
            marginRight:'8px'
          }
    }" 
    confirm-btn="去支付"
    @cancel="downloadTrial"
    @close="payListDialog.show = false"
    @confirm="prePay"
  >
  <template #header>
        <div>
          <span style="vertical-align: middle">{{ payListDialog.title }}</span>
          <!-- <t-tooltip  content="这是Tooltip内容"> -->
          <!-- @vue-ignore -->
          <a
            :href="payListDialog.href"
            target="_blank"
            class="hover"
          >
            <HelpCircleIcon class="hover" style="margin-left:12px;" />
          </a>
        <!-- </t-tooltip> -->
        </div>
   </template>
   <div class="pay-box">
     <div class="pay-title">{{ payListDialog.title }}</div>
     <div class="pay-price">
       <p>￥</p>
       <p>{{ data.deploy.price }}</p>
     </div>
   </div>
   <div class="pay-box pay-diagram">
    <div class="pay-up">
     <div class="pay-title">
      <t-checkbox v-model="data.payDiagram.checked"> 企业图形库  
      
    </t-checkbox>
    <ChevronDownIcon @click="data.payDiagram.expend=false" v-if="data.payDiagram.expend" />
      <ChevronRightIcon @click="data.payDiagram.expend=true" v-else />
     </div>
     <div class="pay-price">
       <p>￥</p>
       <p>{{ data.payDiagram.price }}</p>
     </div>
    </div>
    <div v-if="data.payDiagram.expend" class="pay-down">
        <div v-for="item in data.payDiagram.list">
          <img v-if="item.img" :src="item.img" />
          <div v-else-if="item.svg" v-html="item.svg" ></div>
          <svg v-else class="l-icon" aria-hidden="true">
            <use :xlink:href="'#' + iotPensMap[item.name]?.icon"></use>
          </svg>
        </div>
        <p v-if="data.payDiagram.payAll">
          【说明】检查到当前项目为老版本格式，需要购买整套SVG线性图元。
        </p>
    </div>
   </div>
   <div class="pay-footer">
    合计
    <div>
       <p>￥</p>
       <p>{{ data.deploy.price+(data.payDiagram.checked?data.payDiagram.price:0) }}</p>
     </div>
   </div>
</t-dialog>
<t-dialog
    v-if="downloadZipDialog.show"
    v-model:visible="downloadZipDialog.show"
    class="pay-dialog"
    :close-on-overlay-click="false"
    :top="95"
    :width="700"
    :cancel-btn="{
          content: '直接下载',
          variant: 'outline',
          style: {
            width: '100px',
            color:'#707B8F',
            marginRight:'8px'
          }
    }"
    :confirm-btn="downloadZipDialog.checked?'去支付':null"
    @close="downloadZipDialog.show = false"
    @confirm="prePayDownloadZip"
    @cancel="doDownloadZip"
  >
  <template #header>
        <div>
          <span style="vertical-align: middle">导出为Zip文件</span>
          <t-tooltip  content="这是Tooltip内容">
            <a
            :href="`https://doc${rootDomain}/document/155692631#%E5%AF%BC%E5%87%BA%E4%B8%BAZip%E6%96%87%E4%BB%B6`"
            target="_blank"
            class="hover"
            >
              <HelpCircleIcon style="margin-left:12px;" />
            </a>
          </t-tooltip>
        </div>
   </template>
   <div class="pay-box pay-diagram" style="font-size: 14px;
    line-height: 30px;
    color: #6E7B91;">
    Zip包仅包含数据文件和图片文件，不包含js等依赖库。
    <div >- 注意</div>Zip包用于平台（已包含js等依赖库）的快捷导入导出项目，无法作为独立部署包使用。
    <p v-if="downloadZipDialog.hasJs">
      <p>- 当前图纸包含js企业图形依赖库。</p>
      项目中打开如果没有js企业图形依赖库，对应的图元将无法显示。
      推荐下载为离线部署包（包含js企业图形依赖库）。
  </p>
   </div>
   <div class="pay-box pay-diagram">
    <div class="pay-up">
     <div class="pay-title">
      <t-checkbox v-model="downloadZipDialog.checked"> 企业图形库  
      
    </t-checkbox>
    <ChevronDownIcon @click="downloadZipDialog.expend=false" v-if="downloadZipDialog.expend" />
      <ChevronRightIcon @click="downloadZipDialog.expend=true" v-else />
     </div>
     <div class="pay-price">
       <p>￥</p>
       <p>{{ downloadZipDialog.price }}</p>
     </div>
    </div>
    <div v-if="downloadZipDialog.expend" class="pay-down">
        <div v-for="item in downloadZipDialog.list">
          <img :src="item" />
        </div>
    </div>
   </div>
   <div class="pay-footer">
    合计
    <div>
       <p>￥</p>
       <p>{{downloadZipDialog.checked? downloadZipDialog.price:0 }}</p>
     </div>
   </div>
</t-dialog>
  <t-dialog
    v-if="wechatPayDialog.show"
    v-model:visible="wechatPayDialog.show"
    class="pay-dialog"
    header="乐吾乐收银台"
    :close-on-overlay-click="false"
    :top="95"
    :width="700"
    confirm-btn="支付完成"
    :cancel-btn="null"
    @close="wechatPayDialog.show = false"
    :footer="false"
  >
    <Pay
      :order="data.order"
      :alipay-url="data.order.alipayUrl"
      :code-url="data.order.codeUrl"
      @success="onSuccess"
    />
  </t-dialog>
</template>

<script lang="ts" setup>
import {
  reactive,
  ref,
  onBeforeMount,
  onUnmounted,
  nextTick,
  computed,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUser } from '@/services/user';
import { MessagePlugin } from 'tdesign-vue-next';
import {
  Meta2dBackData,
  dealwithFormatbeforeOpen,
  gotoAccount,
  checkData,
} from '@/services/utils';
import { readFile } from '@/services/file';
import { compareVersion, baseVer, upgrade } from '@/services/upgrade';
import { parseSvg } from '@meta2d/svg';
import { Pen, getGlobalColor, isShowChild } from '@meta2d/core';
import { cdn, upCdn, addCollection } from '@/services/api';
// import JSZip from 'jszip';
import axios from 'axios';
import { switchTheme } from '@/services/theme';
import { noLoginTip } from '@/services/utils';
import {
  save,
  blank,
  newFile,
  SaveType,
  onScaleFull,
  onScaleWindow,
  showMagnifier,
  showMap,
  drawPen,
  map,
  magnifier,
  useDot,
  delAttrs,
  // useAssets,
  autoSaveAS,
  queryURLParams,
  dealDataBeforeOpen
} from '@/services/common';
import { useEnterprise } from '@/services/enterprise';
import {
  CheckIcon,
  HomeIcon,
  DesktopIcon,
  ControlPlatformIcon,
  AppIcon,
  ChevronRightIcon,
  ChevronDownIcon,
  HelpCircleIcon
} from 'tdesign-icons-vue-next';
import {
  getDownloadList,
  getPayList,
  getComponentPurchased,
  get2dComponentJs,
  getTemPngs,
  getGoods,
  // preFrameDownload,
  zipBkImg,
  zipImages,
  Frame,
  img_cdn,
  img_upCdn,
  getDeployGoods,
  getFrameDownloadList,
  getDownloadZipList
} from '@/services/download';
import { formComponents, rootDomain } from '@/services/defaults';
import Pay from './Pay.vue';
import {getNetJsDiagram} from '@/services/material';
import { useMeta2dData } from '@/services/common';
import { upload } from '@/services/file';
import { load3d } from '@/services/load3d';

const { enterprise } = useEnterprise();
const router = useRouter();
const route = useRoute();
const { meta2dData, setMeta2dData } = useMeta2dData();
const baseUrl = import.meta.env.BASE_URL || '/';
// const { assets, getAssets } = useAssets();

const { user, signout } = useUser();
const { setDot } = useDot();
const data = reactive<any>({
  name: '新建项目',
  order: {
    codeUrl: '',
    id: '', //订单id
  },
  goods: [], //所有商品类型
  purchasedList: [], //已经购买的列表
  deploy:{
    price:400,
  },
  payDiagram: {
    price: 400,
    checked:true,
    expend:false,
    list:[],
    payAll:false
  },
  zips:{

  },
  payGoods:{},
});

onBeforeMount(async () => {
  // getAssets();
  // getNetJsDiagram();
});

const logout = () => {
  signout();
  meta2d.emit('logout');
};
const onInputName = (e) => {
  // (meta2d.store.data as Meta2dBackData).name = data.name;
  setMeta2dData({ name: e.target.value });
  setDot(true);
};

const initMeta2dName = () => {
  data.name = (meta2d.store.data as Meta2dBackData).name || '';
  setMeta2dData({ name: (meta2d.store.data as Meta2dBackData).name || '新建项目' });
};

let downloadList = new Set<any>();
let downloadZip3dList:any[] = [];
let iframeNum = 0;
let compareNum = 0;
const prePayList = reactive({
  pngs: new Set<string>(),
  jsPens: new Set<string>(),
  iotPens: new Set<string>(),
  svgPens: new Set<string>(),
});
let payListNum = 0;
let comparePayListNum = 0;
// let purchasedList = []; //已购买列表
const iotPensMap = {};
let downloadType: Frame = null;
// const payPrice = ref(0);

const getIotPensMap = () => {
  formComponents.forEach((item) => {
    item.list.forEach((_item) => {
      iotPensMap[_item.data.name] = { name: _item.name, icon: _item.icon };
    });
  });
};
nextTick(() => {
  meta2d.on('opened', initMeta2dName);
  window.addEventListener('message', dealWithMessage);
  getIotPensMap();
});

const dealWithMessage = async (e) => {
  if (
    typeof e.data !== 'string' ||
    !e.data ||
    e.data.startsWith('setImmediate')
  ) {
    return;
  }
  try {
    let data = JSON.parse(e.data);
    if (typeof data === 'object') {
      if (data.type) {
        if (data.name === 'download') {
          let list = data.data;
          if(downloadType === Frame.zip){
            compareNum += 1;
            downloadZip3dList = [...downloadZip3dList, ...list];
            if (compareNum >= iframeNum) {
              doDownloadZip();
            }
            
          }else{
            let folderName =downloadType===Frame.vue3?'meta2d-vue3':downloadType===Frame.vue2?'meta2d-vue2': 'meta2d-react';
            list.forEach((item) => {
              // if(item.path.startsWith('/meta3d/')){
              //   item.path = `/${folderName}/public/${item.path}`;
              // }
              if(item.path.startsWith('/vue3/')||item.path.startsWith('/vue2/')||item.path.startsWith('/react/')){
                item.path = item.path.replace('vue3',folderName).replace('vue2',folderName).replace('react',folderName);
              }
            });
            downloadList = new Set([...downloadList, ...list]);
            compareNum += 1;
            if (compareNum >= iframeNum) {
              saveDownload();
            }
          }
        } else if (data.name === 'payList') {
          prePayList.pngs = new Set([...prePayList.pngs, ...data.data.pngs]);
          prePayList.jsPens = new Set([
            ...prePayList.jsPens,
            ...data.data.jsPens,
          ]);
          prePayList.iotPens = new Set([
            ...prePayList.iotPens,
            ...data.data.iotPens,
          ]);
          prePayList.svgPens = new Set([
            ...prePayList.svgPens,
            ...data.data.svgPens,
          ]);

          comparePayListNum += 1;
          if (comparePayListNum >= payListNum) {
              await showPayListDialog();
          }
        }
        // else if(data.name==='saveas'){
        //   await autoSaveAS(data.id);
        // }
      } else {
        // meta2d.emit(data.name);
      }
    } else {
      // meta2d.emit(data);
    }
  } catch (e) {
    console.info(e);
  }
};

onUnmounted(() => {
  meta2d.off('opened', initMeta2dName);
  window.removeEventListener('message', dealWithMessage);
});

const login = () => {
  if(import.meta.env.BASE_URL.startsWith('/') ){
    return `${enterprise['account']}?cb=${encodeURIComponent(location.href)}`;
  }else{
    return `https://account${rootDomain}/login?cb=${encodeURIComponent(location.href)}`;
  }
};

function load(isNew = false) {
  const input = document.createElement('input');
  input.type = 'file';
  input.onchange = (event) => {
    const elem = event.target as HTMLInputElement;
    if (elem.files && elem.files[0]) {
      // 路由跳转 可能在 openFile 后执行
      if (elem.files[0].name.endsWith('.json')) {
        blank();
        openJson(elem.files[0]);
        if (isNew) {
          router.push({
            path: '/',
            query: {
              r: Date.now() + '',
            },
          });
        }
      } else if (elem.files[0].name.endsWith('.svg')) {
        MessagePlugin.info(
          '可二次编辑但转换存在损失，若作为图片使用，请使用右侧属性面板的上传图片功能'
        );
        openSvg(elem.files[0]);
      } else if (elem.files[0].name.endsWith('.zip')) {
        blank();
        router.push({
          path: '/',
          query: {
            r: Date.now() + '',
          },
        });
        setTimeout(() => {
          openZip(elem.files[0]);
        }, 500);
      } else {
        MessagePlugin.info('打开文件只支持 json，svg，zip 格式');
      }
    }
  };
  input.click();
}

const openJson = async (file: File) => {
  const text = await readFile(file);
  try {
    let data: Meta2dBackData = JSON.parse(text);
    if (!data.name) {
      data.name = file.name.replace('.json', '');
    }
    if (!data.version || compareVersion(data.version, baseVer) === -1) {
      // 如果版本号不存在或者版本号 version < 1.0.0
      data = upgrade(data, baseVer);
    }
    dealwithFormatbeforeOpen(data);
    for (const k of delAttrs) {
      delete (data as any)[k];
    }
    if(!data.background){
      data.background = '#1e2430';
    }
    if(!data.color){
      data.color = '#bdc7db';
    }
    dealDataBeforeOpen(data);
    if(!(data as any).oldV){
      if(!data.width){data.width= 1920};
      if(!data.height){data.height= 1080};
    }
    meta2d.open(data);
  } catch (e) {
    console.error(e);
  }
};

const openSvg = async (file: File) => {
  const text = await readFile(file);
  const pens: Pen[] = parseSvg(text);
  meta2d.canvas.addCaches = pens;
  MessagePlugin.info('svg转换成功，请点击画布决定放置位置');
};

const openZip = async (file: File) => {
  if (!(user && user.id)) {
    MessagePlugin.warning(noLoginTip);
    return;
  }

  // if (!user.isVip) {
  //   gotoAccount();
  //   return;
  // }
  // if (!user.vip) {
  //   MessagePlugin.info('需要开通会员~');
  //   gotoAccount();
  //   return;
  // }
  MessagePlugin.loading('正在读取...',0);
  const { default: JSZip } = await import('jszip');
  const zip = new JSZip();
  await zip.loadAsync(file,{base64:true});
  let fileName = file.name.slice(0, -4)
  let dataStr = '';
  for (const key in zip.files) {
    if (zip.files[key].dir) {
      continue;
    }
    if (key.endsWith('.json')) {
      // 认为只有一个 json 文件
      dataStr = await zip.file(key).async('string');
      break;
    }
  }

  if (!dataStr) {
    return false;
  }
  const imgReplaceArr = [];
  const _2dDataMap ={};
  const _3dDataMap ={};
  MessagePlugin.loading('正在上传文件...',0);
  for (const key in zip.files) {
    if (zip.files[key].dir) {
      continue;
    }
    let _keyLower = key.toLowerCase();
    if (
      _keyLower.endsWith('.png') ||
      _keyLower.endsWith('.svg') ||
      _keyLower.endsWith('.gif') ||
      _keyLower.endsWith('.jpg') ||
      _keyLower.endsWith('.jpeg')
    ) {
      let filename = key.substr(key.lastIndexOf('/') + 1);
      // 上传文件
      const form = new FormData();
      form.append('name', filename);
      form.append('directory', '/大屏/图片/默认');
      form.append('shared', true + '');
      form.append('file', await zip.file(key).async('blob'));
      form.append('conflict', 'new');
      const result: any = await axios.post('/api/image/upload', form);
      let arr =  key.split('/');
      arr.shift();
      if(arr[0]===fileName){
        arr.shift();
      }
      let _key ='/'+ arr.join('/');
      if (result) {
        imgReplaceArr.push({ key: _key, url: result.url });
      }
    }else if(_keyLower.endsWith('.json')){
      let arr =  key.split('/');
      arr.shift();
      if(arr[0]===fileName){
        arr.shift();
      }
      let data = await zip.file(key).async('string');
      if(!arr[0].endsWith('.json')){
        _2dDataMap[arr[0]] = data;
      }
    }else{
      // console.log("key",key);
      if(key.indexOf('3d')!==-1&&key.indexOf('files/')===-1){
        let id_3d =   await load3d(zip,key);
        if(id_3d){
          // dataStr = dataStr.replaceAll(key, id_3d);
          let originId = key.split('3d-')[1];
          _3dDataMap[originId] = id_3d;
        }
      }
    }
  }

  //替换2d图片数据
  imgReplaceArr.forEach((item) => {
    dataStr = dataStr.replaceAll(item.key, item.url);
    for (let key in _2dDataMap) {
      _2dDataMap[key] = _2dDataMap[key].replaceAll(item.key, item.url);
    }
  });

  try {
    let domain = location.origin+ '/view';
    let data: Meta2dBackData = JSON.parse(dataStr);
    for(let i=0;i<data.pens.length;i++){
      const pen = data.pens[i];
      if(pen.name==='iframe'){
        let url = pen.iframe.split('?')[1]
        let params = queryURLParams(url);
        if(pen.iframe.indexOf('/2d/')!==-1 || pen.iframe.indexOf('/v/')!==-1 || pen.iframe.indexOf('/2d?')!==-1 ||pen.iframe.indexOf('/v?')!==-1){
          const idata = JSON.parse(_2dDataMap[params.id]);
          const ret:any = await addCollection('v',{
            data:idata,
            image:idata.image||'xxx',
            name:idata.name||'新建项目',
            folder:idata.folder,
            // userFlag:2,
            system:false,
            case:idata.case,
          });
          if(!ret){
            continue;
          }
          pen.iframe = `${domain}/v/?id=${ret.id}`;
        }else if(pen.iframe.indexOf('/3d')!==-1){
          pen.iframe = `${domain}/3d/?id=${_3dDataMap[params.id]}`;
        }
      }
    }
    if (data) {
      if (!data.name) {
        data.name = file.name.replace('.zip', '');
      }
      if (!data.version || compareVersion(data.version, baseVer) === -1) {
        // 如果版本号不存在或者版本号 version < 1.0.0
        data = upgrade(data, baseVer);
      }
      dealwithFormatbeforeOpen(data);
      const delAttrs = [
        'userId',
        'shared',
        'team',
        'owner',
        'username',
        'editor',
        'editorId',
        'editorName',
        'createdAt',
        'folder',
        'image',
        'id',
        '_id',
        'view',
        'updatedAt',
        'star',
        'recommend',
      ];

      for (const k of delAttrs) {
        delete (data as any)[k];
      }
      if(!data.background){
        data.background = '#1e2430';
      }
      if(!data.color){
        data.color = '#bdc7db';
      }

      if(!data.width){data.width= 1920};
      if(!data.height){data.height= 1080};
      dealDataBeforeOpen(data)
      meta2d.open(data);
      MessagePlugin.closeAll();
      MessagePlugin.success('导入成功！');
    }
  } catch (e) {
    return false;
  }
};

const _openZip = async (file: File) => {
  if (!(user && user.id)) {
    MessagePlugin.warning(noLoginTip);
    return;
  }

  // if (!user.isVip) {
  //   gotoAccount();
  //   return;
  // }
  // if (!user.vip) {
  //   MessagePlugin.info('需要开通普通会员~');
  //   gotoAccount();
  //   return;
  // }
  const { default: JSZip } = await import('jszip');
  const zip = new JSZip();
  await zip.loadAsync(file,{base64:true});
  let fileName = file.name.slice(0, -4)
  let dataStr = '';
  for (const key in zip.files) {
    if (zip.files[key].dir) {
      continue;
    }
    if (key.endsWith('.json')) {
      // 认为只有一个 json 文件
      dataStr = await zip.file(key).async('string');
      break;
    }
  }

  if (!dataStr) {
    return false;
  }

  for (const key in zip.files) {
    if (zip.files[key].dir) {
      continue;
    }
    // let _png = key.indexOf('/png');
    // let _img = key.indexOf('/img');
    // let _image = key.indexOf('/image');
    // let _file = key.indexOf('/file');
    let _keyLower = key.toLowerCase();
    // if (!key.endsWith('.json') && (_png !== -1 || _img !== -1 || _image !== -1 || _file !== -1)) {
    if (
      _keyLower.endsWith('.png') ||
      _keyLower.endsWith('.svg') ||
      _keyLower.endsWith('.gif') ||
      _keyLower.endsWith('.jpg') ||
      _keyLower.endsWith('.jpeg')
    ) {
      let filename = key.substr(key.lastIndexOf('/') + 1);
      const extPos = filename.lastIndexOf('.');
      let ext = '';
      if (extPos > 0) {
        ext = filename.substr(extPos);
      }
      filename = filename.substring(0, extPos > 8 ? 8 : extPos);

      // 上传文件
      const result: any = await upload(
        await zip.file(key).async('blob'),
        true,
        filename + ext
      );
      let arr =  key.split('/');
      arr.shift();
      if(arr[0]===fileName){
        arr.shift();
      }
      let _key ='/'+ arr.join('/');
      // if (_png) {
      //   _key = key.substring(_png);
      // } else if (_image) {
      //   _key = key.substring(_png);
      // } else if (_img) {
      //   _key = key.substring(_img);
      // } else if (_file) {
      //   _key = key.substring(_file);
      // }
      if (result) {
        if (dataStr.replaceAll) {
          //'le5le.meta2d'
          dataStr = dataStr.replaceAll(_key, result.url);
        } else {
          while (dataStr.includes(_key)) {
            dataStr = dataStr.replace(_key, result.url);
            // 正则 gm 在特殊情况下报错，例如如下场景
            /**
                 *    
      const data = '{"image":"/image/materials/IoT-Chemical(化学)/Air stripper 2(汽提塔2).svg"}';
      const key = '/image/materials/IoT-Chemical(化学)/Air stripper 2(汽提塔2).svg';
      data.replace(key, '123');
      data.replaceAll(key, '123')
      data.replace(new RegExp(key, 'gm'), '123');
      data.replace(new RegExp(key, 'g'), '123');
                 */
          }
        }
      }
    }
  }

  try {
    let data: Meta2dBackData = JSON.parse(dataStr);
    if (data) {
      if (!data.name) {
        data.name = file.name.replace('.zip', '');
      }
      if (!data.version || compareVersion(data.version, baseVer) === -1) {
        // 如果版本号不存在或者版本号 version < 1.0.0
        data = upgrade(data, baseVer);
      }
      dealwithFormatbeforeOpen(data);
      const delAttrs = [
        'userId',
        'shared',
        'team',
        'owner',
        'username',
        'editor',
        'editorId',
        'editorName',
        'createdAt',
        'folder',
        'image',
        'id',
        '_id',
        'view',
        'updatedAt',
        'star',
        'recommend',
      ];
      for (const k of delAttrs) {
        delete (data as any)[k];
      }
      if(!data.background){
        data.background = '#1e2430';
      }
      if(!data.color){
        data.color = '#bdc7db';
      }
      if(!data.width){data.width= 1920};
      if(!data.height){data.height= 1080};
      meta2d.open(data);
    }
  } catch (e) {
    return false;
  }
};

const downloadJson = () => {
  const data: Meta2dBackData = meta2d.data();
  if (data._id) delete data._id;
  if (data.id) delete data.id;
  checkData(data);
  import('file-saver').then(({ saveAs }) => {
    saveAs(
      new Blob(
        [JSON.stringify(data).replaceAll(cdn, '').replaceAll(upCdn, '')],
        {
          type: 'text/plain;charset=utf-8',
        }
      ),
      `${data.name || 'le5le.meta2d'}.json`
    );
  });
};

const downloadZip = async () => {
  if (!(user && user.id)) {
    MessagePlugin.warning(noLoginTip);
    return;
  }

  // if (!user.isVip) {
  //   // gotoAccount();
  //   return;
  // }
  if(!meta2d.store.data.pens.length){
    MessagePlugin.info('画布没有画笔!');
    return;
  }
  // if (!user.vip) {
  //   MessagePlugin.info('需要开通会员~');
  //   gotoAccount();
  //   return;
  // }
    //提前存储iframe嵌入2d数据
  downloadType = Frame.zip;
  downloadZip3dList = [];
  data.zips = {};
  const pen_pay = meta2d.store.data.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`/2d/`) !== -1 ||
        pen.iframe.indexOf('/2d?') !== -1 || 
        pen.iframe.indexOf(`/v/`) !== -1 ||
        pen.iframe.indexOf('/v?') !== -1)
  );
  if (pen_pay && pen_pay.length) {
    for(let i=0;i<pen_pay.length;i++){
    // pen_pay.forEach(async(pen) => {
      const pen = pen_pay[i];
      let arr = pen.iframe.split('?');
      let params = queryURLParams(arr[1]);
      if(params.id){
        if(arr[0].indexOf('2d') !== -1 ){
          const ret: any = await axios.post('/api/data/2d/get', {
            id:params.id
          });
          if(ret.data){
            let payList = getPayList(ret.data);
            // payList.pngs.forEach(item => pngs.add(item));
            data.zips[params.id] = {
              data:ret.data,
              pngs:payList.pngs
            }
          }
        }else if(arr[0].indexOf('v') !== -1){
          const ret: any = await axios.post('/api/data/v/get', {
            id:params.id
          });
          if(ret.data){
            let payList = getPayList(ret.data);
            // payList.pngs.forEach(item => pngs.add(item));
            data.zips[params.id] = {
              data:ret.data,
              pngs:payList.pngs
            }
          }
        }
      }
    // })
    }
  }
  preDoDownloadZip();
  return;
  // MessagePlugin.info('正在下载打包中，可能需要几分钟，请耐心等待...');
  // const [{ default: JSZip }, { saveAs }] = await Promise.all([
  //   import('jszip'),
  //   import('file-saver'),
  // ]);

  // const zip: any = new JSZip();
  // const data: Meta2dBackData = meta2d.data();
  // let _fileName =
  //   (data.name && data.name.replace(/\//g, '_').replace(/:/g, '_')) ||
  //   'le5le.meta2d';
  // const _zip = zip.folder(`${_fileName}`);
  // if (data._id) delete data._id;
  // if (data.id) delete data.id;
  // checkData(data);
  // _zip.file(
  //   `${_fileName}.json`,
  //   JSON.stringify(data).replaceAll(cdn, '').replaceAll(upCdn, '')
  // );
  // await zipBkImg(_zip);
  // await zipImages(_zip, meta2d.store.data.pens);

  // const blob = await zip.generateAsync({ type: 'blob' });
  // saveAs(blob, `${_fileName}.zip`);
};

const preDownloadZip =async () =>{
  const meta2dData = meta2d.data();
  let payList = getPayList(meta2dData);
  let purchased =await getComponentPurchased({
    pngs: payList.pngs,
    jsPens: [],
    iotPens: [],
    svgPens: [],
  });
  downloadZipDialog.checked = true;
  if(payList.jsPens.length||payList.iotPens.length||payList.svgPens.length){
    downloadZipDialog.hasJs = true;
  }else{
    downloadZipDialog.hasJs = false;
  }
  let names = purchased.map((item) => item.name);
  data.goods = await getGoods();
  let list =  payList.pngs.filter((item) => !names.includes(item));
  if(!list.length){
    doDownloadZip();
  }else{
    let unitPrice = data.goods.find((item)=>item.type==='图片图元').unitPrice; 
    downloadZipDialog.price = unitPrice*list.length;
    downloadZipDialog.show = true;
    downloadZipDialog.list = list;
  }
}

const prePayDownloadZip = async ()=>{
  if(downloadZipDialog.checked){
    const res: any = await axios.post('/api/order/deployment/submit', {
     goods:{},
    '2ds':downloadZipDialog.list.map((item)=>{return { type: '图片图元', name: item}}),
    });
    wechatPayDialog.show = true;
    wechatPayDialog.isZip = true;
    data.order = res;
  }else {
    doDownloadZip();
  }
}
const preDoDownloadZip = async ()=>{
  const meta2dData:any = meta2d.data();
  const pen_3d = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`3d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/3d`) !== -1||
        pen.iframe.indexOf(`/view/3d`) !== -1 //安装包
        ));
  if (pen_3d && pen_3d.length) {
   
      pen_3d.forEach((pen) => {
        //发送消息
        let params = queryURLParams(pen.iframe.split('?')[1]);
        (
          meta2d.store.pens[pen.id].calculative.singleton.div
            .children[0] as HTMLIFrameElement
        ).contentWindow.postMessage(
          JSON.stringify({
            name: 'deployAsZip',
            // id: params.id,
            type: 1,
            path: `3d-${params.id}`,
          }),
          '*'
        );
        // pen.iframe = `/view?data=3d-${params.id}`;
      });
  }else{
    doDownloadZip();
  }
}

const doDownloadZip = async ()=>{
  // downloadZipDialog.show = false;
  MessagePlugin.info('正在下载打包中，可能需要几分钟，请耐心等待...',0);
  const [{ default: JSZip }, { saveAs }] = await Promise.all([
    import('jszip'),
    import('file-saver'),
  ]);
  const zip: any = new JSZip();
  const _data: Meta2dBackData = meta2d.data();
  let _fileName =
    (_data.name && _data.name.replace(/\//g, '_').replace(/:/g, '_')) ||
    'le5le.meta2d';
  const _zip = zip.folder(`${_fileName}`);
  let list = getDownloadZipList(_data,data.zips);
  await Promise.all(
    [...list,...downloadZip3dList].map(async (item: any) => {
      if (item.url) {
        //接口请求
        try{
          let url = item.url.startsWith('/')?(cdn+item.url):item.url;
          if(url.includes('?')){
            url = url + `&r=${Date.now()}`;
          }else{
            url = url + `?r=${Date.now()}`;
          }
          const res: Blob = await axios.get(url, {
            responseType: 'blob',
          });
          _zip.file(item.path.split('?')[0], res, { createFolders: true });
        }catch(e){
          console.log(e);
        }
      } else if (item.data) {
        //直接写数据
        _zip.file(item.path, item.data, { createFolders: true });
      }
    })
  );
  const blob = await zip.generateAsync({ type: 'blob' });
  saveAs(blob, `${_fileName}.zip`);
  MessagePlugin.closeAll();
  MessagePlugin.success('下载成功，请在浏览器下载列表中查看');
  // downloadZipDialog.show = false;
  // MessagePlugin.info('正在下载打包中，可能需要几分钟，请耐心等待...');
  // const [{ default: JSZip }, { saveAs }] = await Promise.all([
  //   import('jszip'),
  //   import('file-saver'),
  // ]);

  // const zip: any = new JSZip();
  // const data: Meta2dBackData = meta2d.data();
  // let _fileName =
  //   (data.name && data.name.replace(/\//g, '_').replace(/:/g, '_')) ||
  //   'le5le.meta2d';
  // const _zip = zip.folder(`${_fileName}`);
  // if (data._id) delete data._id;
  // if (data.id) delete data.id;
  // checkData(data);
  // _zip.file(
  //   `${_fileName}.json`,
  //   JSON.stringify(data).replaceAll(cdn, '').replaceAll(upCdn, '')
  // );
  // await zipBkImg(_zip);
  // await zipImages(_zip, meta2d.store.data.pens);

  // const blob = await zip.generateAsync({ type: 'blob' });
  // saveAs(blob, `${_fileName}.zip`);
}

// const zip3D = (name: string) => {
//   const pen_3d = meta2d.store.data.pens.filter(
//     (pen) =>
//       pen.name === 'iframe' &&
//       (pen.tags.includes('meta3d') || pen.iframe.indexOf('3d') !== -1)
//   );
//   if (pen_3d && pen_3d.length) {
//     //存在3d场景
//     pen_3d.forEach((pen) => {
//       //发送消息
//       let params = queryURLParams(pen.iframe.split('?')[1]);
//       (
//         pen.calculative.singleton.div.children[0] as HTMLIFrameElement
//       ).contentWindow.postMessage(
//         JSON.stringify({
//           type: 1,
//           name,
//           id: params.id,
//         }),
//         '*'
//       );
//     });
//   }
// };

// const zip2D = (name: string) => {
//   const pen_2d = meta2d.store.data.pens.filter(
//     (pen) =>
//       pen.name === 'iframe' &&
//       (pen.iframe.indexOf('2d.le5le.com') !== -1 ||
//         pen.iframe.indexOf('/2d/') !== -1 ||
//         pen.iframe.indexOf('v.le5le.com') !== -1 ||
//         pen.iframe.indexOf('/v/') !== -1)
//   );
//   if (pen_2d && pen_2d.length) {
//     //存在3d场景
//     pen_2d.forEach((pen) => {
//       //发送消息
//       // let params = queryURLParams(pen.iframe.split('?')[1]);
//       (
//         pen.calculative.singleton.div.children[0] as HTMLIFrameElement
//       ).contentWindow.postMessage(
//         JSON.stringify({
//           name,
//           type: 1,
//         }),
//         '*'
//       );
//     });
//   }
// }

// function queryURLParams(value?: string) {
//   let url = value || window.location.href.split('?')[1];
//   const urlSearchParams = new URLSearchParams(url);
//   const params = Object.fromEntries(urlSearchParams.entries());
//   return params;
// }

const downloadHtml = async () => {
  if (!(user && user.id)) {
    MessagePlugin.warning(noLoginTip);
    return;
  }
  downloadType = Frame.html;
  // await preGetPayList();
  preDownload();
};

const preGetPayList = async () => {
  //图形库需要购买
  const meta2dData = meta2d.data();
  if(!meta2dData.pens.length){
    MessagePlugin.info('画布没有画笔!');
    return;
  }
  let list = getPayList(meta2dData);
  prePayList.pngs = new Set(list.pngs);
  prePayList.jsPens = new Set(list.jsPens);
  prePayList.iotPens = new Set(list.iotPens);
  prePayList.svgPens = new Set(list.svgPens);
  downloadList = new Set();
  //向iframe发送消息
  payListNum = 0;
  comparePayListNum = 0;
  const pen_pay = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`2d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf('/2d') !== -1 || pen.iframe.indexOf('data=2d') !== -1 ||
        pen.iframe.indexOf(`v${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/v`) !== -1 ||pen.iframe.indexOf('data=v') !== -1 ||
        pen.iframe.indexOf('/preview') !== -1)
  );
  if (pen_pay && pen_pay.length) {
    pen_pay.forEach((pen) => {
      //发送消息
      (
        meta2d.store.pens[pen.id].calculative.singleton.div
          .children[0] as HTMLIFrameElement
      ).contentWindow.postMessage(
        JSON.stringify({
          name: 'prePayList',
          type: 1,
        }),
        '*'
      );
      payListNum += 1;
    });
  }
  if (payListNum === 0) {
      await showPayListDialog();
  }
};

const showPayListDialog = async () => {
  //下载离线部署包
  const deploys =await getDeployGoods();
  const pen_3d = meta2d.store.data.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`3d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/3d`) !== -1)
  );
  const pen_2d = meta2d.store.data.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`2d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/2d`) !== -1)
  );
  const pen_v = meta2d.store.data.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`v${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/v`) !== -1||pen.iframe.indexOf('data=v') !== -1)
  );
  let price = 0;
  data.payDiagram.checked = true;
  data.payDiagram.expend = false;
  data.payGoods ={}
  deploys.forEach((item) => {
   if(item.name==="3D离线部署下载"){
     price+=item.price*pen_3d.length;
     if(pen_3d.length){
        data.payGoods[item.id]=pen_3d.length;
     }
   }else if(item.name==="2D离线部署下载"){
     price+=item.price*pen_2d.length;
     if(pen_2d.length){
        data.payGoods[item.id]=pen_2d.length;
     }
   }else if(item.name==="大屏离线部署下载"){
     price+=item.price*(pen_v.length+1);
     data.payGoods[item.id]=pen_v.length+1;
   }
  });
  data.deploy.price = price;
  //图形库
  data.goods = await getGoods();
  data.purchasedList = await getComponentPurchased(prePayList);
  data.payDiagram.list =[];
  data.payDiagram.payAll = false;
  data.goods.forEach((goods)=>{
    let purchased = data.purchasedList?.filter(
      (_item) => _item.type === goods.type
    );
    let names = purchased.map((item) => item.name);
    let list = [];
    if(goods.type==='图片图元'){
      list = [...prePayList.pngs];
    }else if(goods.type==='JS线性图元'){
      list = [...prePayList.jsPens];
    }else if(goods.type==='SVG线性图元'){
      list = [...prePayList.svgPens];
    }else if(goods.type==='控件'){
      list = [...prePayList.iotPens];
    }
    let num =0;
    if (goods.type==='SVG线性图元'&&[...prePayList.svgPens].includes('*')) {
      //需要购买全部
        num = goods.count-names.length;
        data.payDiagram.payAll = true;
    }else{
    list.forEach((item)=>{
      if(!names.includes(item)){
        if(goods.type==='控件'){
          data.payDiagram.list.push({
            name:item
          });
        }else if(goods.type==='JS线性图元'){
          data.payDiagram.list.push({
            svg:globalThis.jsPensMap?globalThis.jsPensMap[item]:item
          });
        }else{
          data.payDiagram.list.push({
            img:item
          });
        }
        num+=1;
      }
    })};
    goods.num = num;
  })
   price = 0;
  data.goods.forEach((item, index) => {
      price += item.num * item.unitPrice;
  });
  data.payDiagram.price = price;
  // data.goods.forEach((item, index) => {
  //   item.checked = true;
  //   let purchased = data.purchasedList?.filter(
  //     (_item) => _item.type === item.type
  //   );
  //   if (index === 0) {
  //     item.total = [...prePayList.pngs].length;
  //     item.unPurchased = item.total - purchased.length;
  //   } else if (index === 1) {
  //     item.total = [...prePayList.iotPens].length;
  //     item.unPurchased = item.total - purchased.length;
  //   } else if (index === 3) {
  //     item.total = [...prePayList.jsPens].length;
  //     item.unPurchased = item.total - purchased.length;
  //   } else if (index === 2) {
  //     if (purchased.length === 1 && !purchased[0].name) {
  //       //说明已经购买全部 //TODO
  //       item.total = item.count;
  //       item.unPurchased = 0;
  //     } else {
  //       //需要购买全部
  //       if ([...prePayList.svgPens].includes('*')) {
  //         item.total = item.count;
  //         item.unPurchased = item.total;
  //       } else {
  //         item.total = [...prePayList.svgPens].length;
  //         item.unPurchased = item.total - purchased.length;
  //       }
  //     }
  //   }
  // });
  payListDialog.show = true;
  switch (downloadType) {
    case Frame.html:
      payListDialog.title = '下载离线部署包';
      payListDialog.href = `https://doc${rootDomain}/document/155692631#%E4%B8%8B%E8%BD%BD%E7%A6%BB%E7%BA%BF%E9%83%A8%E7%BD%B2%E5%8C%85`;
      payListDialog.downloadUrl =img_cdn+ '/deployment/大厦电力管理系统(html).zip';
      break;
      case Frame.vue2:
      payListDialog.title = '下载vue2组件包';
      payListDialog.href = `https://doc${rootDomain}/document/155692631#%E4%B8%8B%E8%BD%BDVue2%E7%BB%84%E4%BB%B6%E5%8C%85`;
      payListDialog.downloadUrl = img_cdn+ '/deployment/大厦电力管理系统(vue2).zip';
      break;
      case Frame.vue3:
      payListDialog.title = '下载vue3组件包';
      payListDialog.href = `https://doc${rootDomain}/document/155692631#%E4%B8%8B%E8%BD%BDVue3%E7%BB%84%E4%BB%B6%E5%8C%85`;
      payListDialog.downloadUrl = img_cdn+ '/deployment/大厦电力管理系统(vue3).zip';
      break;
      case Frame.react:
      payListDialog.title = '下载react组件包';
      payListDialog.href = `https://doc${rootDomain}/document/155692631#%E4%B8%8B%E8%BD%BDReact%E7%BB%84%E4%BB%B6%E5%8C%85`;
      payListDialog.downloadUrl = img_cdn+ '/deployment/大厦电力管理系统(react).zip';
      break;
  }
  // let price = 0;

  // if (price === 0) {
  //   skipPay(); //如果计算价格为0，直接下载
  // } else {
  //   payListDialog.show = true;

  // }
};

const preDownload =() => {
  iframeNum = 0;
  compareNum = 0;
  const meta2dData:any = meta2d.data();
  meta2dData.userId = user.id;
  const pen_3d = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`3d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/3d`) !== -1)
  );
  if (pen_3d && pen_3d.length) {
    //存在3d场景
    if (pen_3d.length === 1) {
      let params = queryURLParams(pen_3d[0].iframe.split('?')[1]);
      meta2d.store.pens[
        pen_3d[0].id
      ].calculative.singleton.div.children[0].contentWindow.postMessage(
        JSON.stringify({
          name: 'deploy',
          // id: params.id,
          type: 1, //用于区分是系统消息
          path: `3d`,
        }),
        '*'
      );
      pen_3d[0].iframe ='view/index.html?data=3d';// '/view?data=3d';
    } else {
      pen_3d.forEach((pen) => {
        //发送消息
        let params = queryURLParams(pen.iframe.split('?')[1]);
        (
          meta2d.store.pens[pen.id].calculative.singleton.div
            .children[0] as HTMLIFrameElement
        ).contentWindow.postMessage(
          JSON.stringify({
            name: 'deploy',
            // id: params.id,
            type: 1,
            path: `3d-${params.id}`,
          }),
          '*'
        );
        pen.iframe = `view/index.html?data=3d-${params.id}`;//`/view?data=3d-${params.id}`;
      });
    }
    iframeNum += pen_3d.length;
  }

  const pen_2d = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`2d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/2d`) !== -1)
  );
  if (pen_2d && pen_2d.length) {
    //存在3d场景
    if (pen_2d.length === 1) {
      let params = queryURLParams(pen_2d[0].iframe.split('?')[1]);
      meta2d.store.pens[
        pen_2d[0].id
      ].calculative.singleton.div.children[0].contentWindow.postMessage(
        JSON.stringify({
          name: 'downloadHtml',
          id: params.id,
          type: 1,
          path: `2d`,
        }),
        '*'
      );
      pen_2d[0].iframe = '/view?data=2d';
    } else {
      pen_2d.forEach((pen) => {
        //发送消息
        let params = queryURLParams(pen.iframe.split('?')[1]);
        (
          meta2d.store.pens[pen.id].calculative.singleton.div
            .children[0] as HTMLIFrameElement
        ).contentWindow.postMessage(
          JSON.stringify({
            name: 'downloadHtml',
            // id: params.id,
            type: 1,
            path: `2d-${params.id}`,
          }),
          '*'
        );
        pen.iframe = `/view?data=2d-${params.id}`;
      });
    }
    iframeNum += pen_2d.length;
  }

  const pen_v = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`v${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/v`) !== -1||pen.iframe.indexOf('data=v') !== -1)
  );

  if (pen_v && pen_v.length) {
    //存在3d场景
    pen_v.forEach((pen) => {
      //发送消息
      let params = queryURLParams(pen.iframe.split('?')[1]);
      (
        meta2d.store.pens[pen.id].calculative.singleton.div
          .children[0] as HTMLIFrameElement
      ).contentWindow.postMessage(
        JSON.stringify({
          name: 'downloadHtml',
          // id: params.id,
          type: 1,
          path: `v-${params.id}`,
        }),
        '*'
      );
      pen.iframe = `/view?data=v-${params.id}`;
    });
    iframeNum += pen_v.length;
  }

  downloadList = getDownloadList(meta2dData,undefined);

  if (iframeNum === 0) {
    //如果没有嵌入场景
    saveDownload();
  } else {
    setTimeout(() => {
      if (compareNum < iframeNum) {
        //message阻塞/报错的情况
        saveDownload();
      }
    }, 10000);
  }
};

const preFrameDownload = async () => {
  iframeNum = 0;
  compareNum = 0;
  const meta2dData:any = meta2d.data();
  meta2dData.userId = user.id;
  const pen_3d = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`3d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/3d`) !== -1)
  );
  let name_3d = (downloadType===Frame.vue3?'toVue3':downloadType===Frame.vue2?'toVue2':'toReact');
  let flag_3d = false; //标记是否存在3d场景
  if (pen_3d && pen_3d.length) {
    //存在3d场景
    if (pen_3d.length === 1) {
      let params = queryURLParams(pen_3d[0].iframe.split('?')[1]);
      meta2d.store.pens[
        pen_3d[0].id
      ].calculative.singleton.div.children[0].contentWindow.postMessage(
        JSON.stringify({
          name: name_3d,
          type: 1, //用于区分是系统消息
          path: `3d`,
        }),
        '*'
      );
      pen_3d[0].iframe = 'view/index.html?data=3d'; //'/3d?id=3d';
    } else {
      pen_3d.forEach((pen) => {
        //发送消息
        let params = queryURLParams(pen.iframe.split('?')[1]);
        (
          meta2d.store.pens[pen.id].calculative.singleton.div
            .children[0] as HTMLIFrameElement
        ).contentWindow.postMessage(
          JSON.stringify({
            name:name_3d,
            // id: params.id,
            type: 1,
            path: `3d-${params.id}`,
          }),
          '*'
        );
        pen.iframe = `view/index.html?data=-${params.id}`; //`/3d?id=3d-${params.id}`;
      });
    }
    iframeNum += pen_3d.length;
    flag_3d = true;
  }

  const pen_2d = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`2d${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/2d`) !== -1)
  );
  let name_2d = (downloadType===Frame.vue3?'downloadVue3':downloadType===Frame.vue2?'downloadVue2':'downloadReact');

  if (pen_2d && pen_2d.length) {
    //存在3d场景
    if (pen_2d.length === 1) {
      let params = queryURLParams(pen_2d[0].iframe.split('?')[1]);
      meta2d.store.pens[
        pen_2d[0].id
      ].calculative.singleton.div.children[0].contentWindow.postMessage(
        JSON.stringify({
          name: name_2d,
          id: params.id,
          type: 1,
          path: `2d`,
        }),
        '*'
      );
      pen_2d[0].iframe = '/2d?id=2d';
    } else {
      pen_2d.forEach((pen) => {
        //发送消息
        let params = queryURLParams(pen.iframe.split('?')[1]);
        (
          meta2d.store.pens[pen.id].calculative.singleton.div
            .children[0] as HTMLIFrameElement
        ).contentWindow.postMessage(
          JSON.stringify({
            name:name_2d,
            // id: params.id,
            type: 1,
            path: `2d-${params.id}`,
          }),
          '*'
        );
        pen.iframe = `/2d?id=2d-${params.id}`;
      });
    }
    iframeNum += pen_2d.length;
  }

  const pen_v = meta2dData.pens.filter(
    (pen) =>
      pen.name === 'iframe' &&
      (pen.iframe.indexOf(`v${rootDomain}`) !== -1 ||
        pen.iframe.indexOf(`view${rootDomain}/v`) !== -1||pen.iframe.indexOf('data=v') !== -1||pen.iframe.indexOf('/preview') !== -1)
  );
  if (pen_v && pen_v.length) {
    //存在大屏场景
    pen_v.forEach((pen) => {
      //发送消息
      let params = queryURLParams(pen.iframe.split('?')[1]);
      (
        meta2d.store.pens[pen.id].calculative.singleton.div
          .children[0] as HTMLIFrameElement
      ).contentWindow.postMessage(
        JSON.stringify({
          name: name_2d,
          // id: params.id,
          type: 1,
          path: `v-${params.id}`,
        }),
        '*'
      );
      pen.iframe = `/2d?id=v-${params.id}`;
    });
    iframeNum += pen_v.length;
  }

  downloadList =  getFrameDownloadList(meta2dData,undefined,downloadType,flag_3d);
  if (iframeNum === 0) {
    //如果没有嵌入场景
    saveDownload();
  } else {
    setTimeout(() => {
      if (compareNum < iframeNum) {
        //message阻塞/报错的情况
        saveDownload();
      }
    }, 10000);
  }
}

const saveDownload = async () => {
  const list = [...downloadList];
  //控件
  let jsPath= '';
  // let jsPensPath = '';
  switch (downloadType) {
    case Frame.html:
      jsPath = '/view/js/2d-components.js';
      // jsPensPath = `/view/js/1.js`;
      break;
    case Frame.vue2:
      jsPath = '/meta2d-vue2/public/js/2d-components.js';
      // jsPensPath = `/meta2d-vue2/public/js/1.js`;
      break;
    case Frame.vue3:
      jsPath = '/meta2d-vue3/public/js/2d-components.js';
      // jsPensPath = `/meta2d-vue3/public/js/1.js`;
      break;
    case Frame.react:
      jsPath = '/meta2d-react/public/js/2d-components.js';
      // jsPensPath = `/meta2d-react/public/js/1.js`;
      break;
  }
  // list.push({
  //   url: '/view/js/2d-components.js', //需要购买
  //   path: jsPath,
  // });
  // const js = await get2dComponentJs([...prePayList.iotPens]);
  // list.push({
  //   data: js,
  //   path:jsPath,
  // });

  ///png图形库
  // const pngs = await getTemPngs([...prePayList.pngs]);
  // list.forEach((item) => {
  //   if(item.url){
  //     let url =item.url.replace(img_cdn, '').replace(img_upCdn, '')
  //     if (pngs[url]) {
  //       item.url = pngs[url];
  //     }
  //   }
  // });
  //js线性图元 
  // const res: any = await axios.post('/api/paid/2d/component?pageSize=1000', {
  //     type: 'JS线性图元',
  // });
  // let purchased = res.list.map((item) => item.name);
  // let arr = [];
  // [...prePayList.jsPens].forEach((item) => {
  //   if(purchased.includes(item)){
  //     arr.push(item);
  //   }
  // });
  // const res_list: Blob = await axios.post(
  //   '/api/2d/tools',
  //   {
  //     list: arr.map((item) => {
  //       return {
  //         type: 'JS线性图元',
  //         name: item,
  //       };
  //     }),
  //   },
  //   {
  //     responseType: 'blob',
  //   }
  // );

  // list.push({
  //   data: res_list,
  //   path: jsPensPath,
  // });

  //SVG线性图元
  // if ([...prePayList.svgPens].length) {
  //   // let purchased = data.purchasedList?.filter(
  //   //   (_item) => _item.type === 'SVG线性图元'
  //   // );
  //   const res: any = await axios.post('/api/paid/2d/component?pageSize=1000', {
  //       type: 'SVG线性图元',
  //   });
  //   let purchased = res.list;
  //   let count = data.goods.find((item) => item.type === 'SVG线性图元').count;
  //   if(purchased.length === count){
  //   // if (purchased.length === 1 && !purchased[0].name) {
  //     //已经购买全部
  //     list.forEach((item) => {
  //       if (item.data &&
  //         (item.path.indexOf('/projects/2d') !== -1 || item.path.indexOf('/projects/v') !== -1 || item.path.indexOf('/public/json')!==-1) &&
  //         item.path.indexOf('/projects/v/png/') === -1 && item.path.indexOf('/projects/2d/png/') === -1) {
  //         //清空所有svgpath
  //         let meta2dData = JSON.parse(item.data);
  //         for (let key of Object.keys(meta2dData.paths)) {
  //           let path = meta2dData.paths[key];
  //           if (
  //             path.indexOf('-1.18Zm4-1') !== -1 ||
  //             path.indexOf('-1.19Zm4-1') !== -1 ||
  //             path.indexOf('2.85ZM') !== -1 ||
  //             path.indexOf('-1-2.39.3') !== -1
  //           ) {
  //             meta2dData.paths[key] = '';
  //           }
  //         }
  //         item.data = JSON.stringify(meta2dData);
  //       }
  //     });
  //   } else {
  //     let svgnames =  purchased.map(i=>i.name);
  //     list.forEach((item) => {
  //       if (
  //         item.data &&
  //         (item.path.indexOf('/projects/2d') !== -1 || item.path.indexOf('/projects/v') !== -1 || item.path.indexOf('/public/json')!==-1) &&
  //         item.path.indexOf('/projects/v/png/') === -1 && item.path.indexOf('/projects/2d/png/') === -1
  //       ) {
  //         //2d 图纸数据
  //         let meta2dData = JSON.parse(item.data);
  //         meta2dData.pens.forEach((pen) => {
  //           if (pen.name === 'svgPath' && pen.svgUrl) {
  //             if (svgnames.includes(pen.svgUrl.replace(img_cdn, ''))) {
  //               pen.pathId = null;
  //             }
  //           }
  //         });
  //         item.data = JSON.stringify(meta2dData);
  //       }
  //     });
  //   }
  // }

  //开始下载list
  const [{ default: JSZip }, { saveAs }] = await Promise.all([
    import('jszip'),
    import('file-saver'),
  ]);
  const zip = new JSZip();

  await Promise.all(
    list.map(async (item: any) => {
      if (item.url) {
        //接口请求
        try{
          const res: Blob = await axios.get(item.url.startsWith('/')?(cdn+item.url):item.url, {
            responseType: 'blob',
          });
          zip.file(item.path.split('?')[0], res, { createFolders: true });
        }catch(e){
          console.log(e);
        }
      } else if (item.data) {
        //直接写数据
        zip.file(item.path, item.data, { createFolders: true });
      }
    })
  );
  let _fileName =
    (meta2d.store.data.name &&
      meta2d.store.data.name.replace(/\//g, '_').replace(/:/g, '_')) ||
    'le5le.meta2d';
  const blob = await zip.generateAsync({ type: 'blob' });
  saveAs(blob, `${_fileName}.zip`);
  MessagePlugin.closeAll();
  MessagePlugin.success('下载成功，请在浏览器下载列表中查看');
};

// const _downloadHtml = async () => {
//   if (!(user && user.id)) {
//     MessagePlugin.warning(noLoginTip);
//     return;
//   }

//   // if (!user.isVip) {
//   //   gotoAccount();
//   //   return;
//   // }

//   if (user.vipDesc !== '超级会员' && user.vipDesc !== '旗舰会员') {
//     MessagePlugin.info('需要开通超级会员~');
//     gotoAccount();
//     return;
//   }
//   frameFlag = -1;
//   MessagePlugin.info('正在下载打包中，可能需要几分钟，请耐心等待...');
//   const data: Meta2dBackData = meta2d.data();
//   if (data._id) delete data._id;
//   if (data.id) delete data.id;
//   if (data.image) delete data.image;
//   checkData(data);
//   const [{ default: JSZip }, { saveAs }] = await Promise.all([
//     import('jszip'),
//     import('file-saver'),
//   ]);
//   const zip = new JSZip();
//   let _fileName =
//     (data.name && data.name.replace(/\//g, '_').replace(/:/g, '_')) ||
//     'le5le.meta2d';

//   //处理cdn图片地址
//   const _zip: any = zip.folder(`${_fileName}`);
//   _zip.file(
//     'data.json',
//     JSON.stringify(data).replaceAll(cdn, '').replaceAll(upCdn, '')
//   );
//   await Promise.all([
//     zipBkImg(_zip),
//     zipImages(_zip, meta2d.store.data.pens),
//     zipFiles(_zip),
//   ]);
//   const blob = await zip.generateAsync({ type: 'blob' });
//   saveAs(blob, `${_fileName}.zip`);
// };

// async function zipBkImg(zip: JSZip) {
//   let img = meta2d.store.data.bkImage;
//   if (img) {
//     if (img.startsWith('/') || img.startsWith(cdn) || img.startsWith(upCdn)) {
//       const pngs = await getTemPngs([img.replace(cdn, '').replace(upCdn, '')]);
//       await zipImage(zip, img, pngs[img.replace(cdn, '').replace(upCdn, '')]);
//     }
//   }
// }

// enum Frame {
//   vue2,
//   vue3,
//   react,
//   html
// }

const downloadVue3 = async () => {
  downloadAsFrame(Frame.vue3);
};

const downloadVue2 = async () => {
  downloadAsFrame(Frame.vue2);
};

const downloadReact = async () => {
  downloadAsFrame(Frame.react);
};

async function downloadAsFrame(type: Frame) {
  if (!(user && user.id)) {
    MessagePlugin.warning(noLoginTip);
    return;
  }
  // if (user.vipDesc !== '旗舰会员') {
  //   MessagePlugin.info('需要开通旗舰会员~');
  //   gotoAccount();
  //   return;
  // }
  downloadType = type;
  // await preGetPayList();
  preFrameDownload();
}

// const preFrameDownload = async (type: Frame) => {
//   frameFlag = type;
//   MessagePlugin.info('正在下载打包中，可能需要几分钟，请耐心等待...');
//   zip3D(
//     type === Frame.vue3 ? 'toVue3' : type === Frame.vue2 ? 'toVue2' : 'toReact'
//   );
//   zip2D(
//     type === Frame.vue3 ? 'downloadVue3' : type === Frame.vue2 ? 'downloadVue2' : 'downloadReact'
//   );
//   const data: any = meta2d.data();
//   if (data._id) delete data._id;
//   if (data.id) delete data.id;
//   if (data.image) delete data.image;
//   data.userId = user.id;
//   checkData(data);
//   const [{ default: JSZip }, { saveAs }] = await Promise.all([
//     import('jszip'),
//     import('file-saver'),
//   ]);
//   const zip = new JSZip();
//   let _fileName =
//     (data.name && data.name.replace(/\//g, '_').replace(/:/g, '_')) ||
//     'le5le.meta2d';
//   //处理付费svg
//   if (Object.keys(data.paths).length >= 3) {
//     //简单判断有无svg图元
//     const res: any = await axios.post('/api/paid/2d/component', {
//       type: 'SVG线性图元',
//     });
//     if (res.list.length === 1 && !res.list[0].name) {
//       //已经购买全部
//       for (let key of Object.keys(data.paths)) {
//         let path = data.paths[key];
//         if (
//           path.indexOf('-1.18Zm4-1') !== -1 ||
//           path.indexOf('-1.19Zm4-1') !== -1 ||
//           path.indexOf('2.85ZM') !== -1 ||
//           path.indexOf('-1-2.39.3') !== -1
//         ) {
//           data.paths[key] = '';
//         }
//       }
//     } else {
//       //购买部分
//       let purchasedList = res.list.map((i) => i.name);
//       data.pens.forEach((pen) => {
//         if (pen.name === 'svgPath' && pen.svgUrl) {
//           if (purchasedList.includes(pen.svgUrl)) {
//             pen.pathId = null;
//           }
//         }
//       });

//     }
//   }

//   const _zip: any = zip.folder(`${_fileName}`);
//   _zip.file(
//     `${type === Frame.vue3
//       ? 'meta2d-vue3'
//       : type === Frame.vue2
//         ? 'meta2d-vue2'
//         : 'meta2d-react'
//     }/public/json/data.json`,
//     JSON.stringify(data).replaceAll(cdn, '').replaceAll(upCdn, '')
//   );
//   await Promise.all([
//     zipJs(_zip),
//     zipBkImg(_zip),
//     zipImages(_zip, meta2d.store.data.pens),
//     type === Frame.vue3
//       ? zipVue3Files(_zip)
//       : type === Frame.vue2
//         ? zipVue2Files(_zip)
//         : zipReactFiles(_zip),
//     zipIotPens(_zip),
//   ]);
//   const blob = await zip.generateAsync({ type: 'blob' });
//   saveAs(blob, `${_fileName}.zip`);
//   frameFlag = -1;
// }

// async function zipIotPens(zip: JSZip) {
//   //处理控件
//   const js = await get2dComponentJs();
//   zip.file(`${frameFlag === Frame.vue3
//       ? 'meta2d-vue3'
//       : frameFlag === Frame.vue2
//         ? 'meta2d-vue2'
//         : 'meta2d-react'
//     }/public/js/2d-components.js`, js, { createFolders: true });
//   const res: Blob = await axios.get('/view/js/r.js', {
//     responseType: 'blob',
//   });
//   zip.file(`${frameFlag === Frame.vue3
//       ? 'meta2d-vue3'
//       : frameFlag === Frame.vue2
//         ? 'meta2d-vue2'
//         : 'meta2d-react'
//     }/public/js/r.js`, res, { createFolders: true });
// }

// async function zipJs(zip: JSZip) {
//   const files = ['/view/js/marked.min.js', '/view/js/lcjs.iife.js'];
//   await Promise.all(
//     files.map(async (filePath) => {
//       const res: Blob = await axios.get(filePath, {
//         responseType: 'blob',
//       });
//       zip.file(
//         `${frameFlag === Frame.vue3
//           ? 'meta2d-vue3'
//           : frameFlag === Frame.vue2
//             ? 'meta2d-vue2'
//             : 'meta2d-react'
//         }/public` + filePath.replace('/view', ''),
//         res,
//         { createFolders: true }
//       );
//     })
//   );
// }

// async function _zipVue3Files(zip: JSZip) {
//   const files = [
//     '/view/js/marked.min.js',
//     '/view/js/lcjs.iife.js',
//     '/view/vue3/Meta2d.vue',
//     '/view/index.html',
//     '/view/js/meta2d.js',
//     '/view/使用说明.md',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

//新
// async function zipVue3Files(zip: JSZip) {
//   const files = [
//     '/view/meta2d-vue3/src/components/Meta2d.vue',
//     '/view/meta2d-vue3/src/App.vue',
//     '/view/meta2d-vue3/src/main.js',
//     '/view/meta2d-vue3/src/style.css',
//     '/view/meta2d-vue3/index.html',
//     '/view/meta2d-vue3/package.json',
//     '/view/meta2d-vue3/README.md',
//     '/view/meta2d-vue3/vite.config.js',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

// async function _zipVue2Files(zip: JSZip) {
//   const files = [
//     '/view/js/marked.min.js',
//     '/view/js/lcjs.iife.js',
//     '/view/vue2/Meta2d.vue',
//     '/view/index.html',
//     '/view/js/meta2d.js',
//     '/view/使用说明.md',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

// async function zipVue2Files(zip: JSZip) {
//   const files = [
//     '/view/meta2d-vue2/src/components/Meta2d.vue',
//     '/view/meta2d-vue2/src/App.vue',
//     '/view/meta2d-vue2/src/main.js',
//     // '/view/meta2d-vue2/src/style.css',
//     '/view/meta2d-vue2/public/index.html',
//     '/view/meta2d-vue2/package.json',
//     '/view/meta2d-vue2/README.md',
//     // '/view/meta2d-vue3/vite.config.js',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

// async function _zipReactFiles(zip: JSZip) {
//   const files = [
//     '/view/js/marked.min.js',
//     '/view/js/lcjs.iife.js',
//     '/view/react/Meta2d.jsx',
//     '/view/react/Meta2d.css',
//     '/view/index.html',
//     '/view/js/meta2d.js',
//     '/view/使用说明.md',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

// async function zipReactFiles(zip: JSZip) {
//   const files = [
//     '/view/meta2d-react/src/index.css',
//     '/view/meta2d-react/src/index.js',
//     '/view/meta2d-react/src/Meta2d.css',
//     '/view/meta2d-react/src/Meta2d.jsx',
//     '/view/meta2d-react/package.json',
//     '/view/meta2d-react/README.md',
//     '/view/meta2d-react/public/index.html',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

// async function zipFiles(zip: JSZip) {
//   const files = [
//     '/view/js/marked.min.js',
//     '/view/js/lcjs.iife.js',
//     '/view/js/index.js',
//     '/view/js/meta2d.js',
//     '/view/index.html',
//     '/view/index.css',
//     '/view/favicon.ico',
//     '/view/使用说明.pdf',
//   ] as const;
//   // 文件同时加载
//   await Promise.all(files.map((filePath) => zipFile(zip, filePath)));
// }

// async function zipFile(zip: JSZip, filePath: string) {
//   const res: Blob = await axios.get(
//     (cdn ? cdn + '/v' : import.meta.env.BASE_URL.slice(0, -1)) + filePath,
//     {
//       responseType: 'blob',
//     }
//   );
//   zip.file(filePath.replace('/view', ''), res, { createFolders: true });
// }

// /**
//  * 图片放到 zip 里
//  * @param pens 可以是非具有 calculative 的 pen
//  */
// async function zipImages(zip: JSZip, pens: Pen[]) {
//   if (!pens) {
//     return;
//   }

//   // 不止 image 上有图片， strokeImage ，backgroundImage 也有图片
//   const imageKeys = [
//     {
//       string: 'image',
//     },
//     { string: 'strokeImage' },
//     { string: 'backgroundImage' },
//   ] as const;
//   const images: string[] = [];
//   for (const pen of pens) {
//     for (const i of imageKeys) {
//       const image = pen[i.string];
//       if (image) {
//         // HTMLImageElement 无法精确控制图片格式
//         if (
//           image.startsWith('/') ||
//           image.startsWith(cdn) ||
//           image.startsWith(upCdn)
//         ) {
//           // 只考虑相对路径下的 image ，绝对路径图片无需下载
//           if (!images.includes(image)) {
//             images.push(image);
//           }
//         }
//       }
//     }
//     // 无需递归遍历子节点，现在所有的节点都在外层
//   }
//   //付费pngs
//   const pngs = await getTemPngs(images.map(i => i.replace(cdn, '').replace(upCdn, '')));
//   await Promise.all(images.map((image) => zipImage(zip, image, pngs[image.replace(cdn, '').replace(upCdn, '')])));
// }

// async function zipImage(zip: JSZip, image: string, temImage?: string) {
//   const res: Blob = await axios.get(temImage || image, {
//     responseType: 'blob',
//     // params: {
//     //   isZip: true,
//     // },
//   });
//   zip.file(
//     (frameFlag === -1
//       ? ''
//       : `${frameFlag === Frame.vue3
//         ? 'meta2d-vue3'
//         : frameFlag === Frame.vue2
//           ? 'meta2d-vue2'
//           : 'meta2d-react'
//       }/public`) + (cdn ? image.replace(cdn, '').replace(upCdn, '') : image),
//     res,
//     {
//       createFolders: true,
//     }
//   );
// }

const downloadImageTips =
  '无法下载，宽度不合法，画布可能没有画笔/画布大小超出浏览器最大限制';

const downloadPng = () => {
  if (!meta2d.store.data.pens.length) {
    MessagePlugin.warning(downloadImageTips);
    return;
  }
  try {
    meta2d.downloadPng();
  } catch (e) {
    MessagePlugin.warning(downloadImageTips);
  }
};

async function getIconDefs(url: string) {
  let res: any = await axios.get(url);
  let str = res.match(/@font-face([\s\S]*?)\}/)[1];
  str = `@font-face ${str} }`;
  return str;
}

const downloadSvg = async () => {
  // await import('@/assets/canvas2svg');
  for (const pen of meta2d.store.data.pens) {
    if (pen.calculative.img) {
      //重新生成绘制图片
      pen.onRenderPenRaw?.(pen);
    }
  }
  if (!C2S) {
    MessagePlugin.error('请先加载乐吾乐官网下的canvas2svg.js');
    return;
  }

  const rect: any = meta2d.getRect();
  if (!isFinite(rect.width)) {
    MessagePlugin.error(downloadImageTips);
    return;
  }
  rect.x -= 10;
  rect.y -= 10;
  const ctx = new C2S(rect.width + 20, rect.height + 20);
  ctx.textBaseline = 'middle';
  ctx.strokeStyle = getGlobalColor(meta2d.store);
  for (const pen of meta2d.store.data.pens) {
    // 不使用 calculative.inView 的原因是，如果 pen 在 view 之外，那么它的 calculative.inView 为 false，但是它的绘制还是需要的
    if (!isShowChild(pen, meta2d.store) || pen.visible == false) {
      continue;
    }
    meta2d.renderPenRaw(ctx, pen, rect);
  }

  let mySerializedSVG = ctx.getSerializedSvg();
  let icon_pens = meta2d.store.data.pens.filter(
    (item) => item.iconFamily && item.icon
  );
  if (icon_pens && icon_pens.length > 0) {
    let iconList = [
      '/icon/国家电网/iconfont.css',
      '/icon/电气工程/iconfont.css',
      '/icon/通用图标/iconfont.css',
    ];
    let defsList: any = await Promise.all(
      iconList.map((item) => getIconDefs(item))
    );
    mySerializedSVG = mySerializedSVG.replace(
      '<defs/>',
      `<defs>
    <style type="text/css">
${defsList.join('\n')}
</style>
{{bk}}
  </defs>
{{bkRect}}`
    );
  }
  /*  mySerializedSVG = mySerializedSVG.replace(
        '<defs/>',
        `<defs>
    <style type="text/css">
  @font-face {
    font-family: 'ticon';
    src: url('icon/通用图标/iconfont.ttf') format('truetype');
  }
</style>
{{bk}}
  </defs>
{{bkRect}}`
      );
*/
  if (meta2d.store.data.background) {
    mySerializedSVG = mySerializedSVG.replace('{{bk}}', '');
    mySerializedSVG = mySerializedSVG.replace(
      '{{bkRect}}',
      `<rect x="0" y="0" width="100%" height="100%" fill="${meta2d.store.data.background}"></rect>`
    );
  } else {
    mySerializedSVG = mySerializedSVG.replace('{{bk}}', '');
    mySerializedSVG = mySerializedSVG.replace('{{bkRect}}', '');
  }

  mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, '&#x');

  const urlObject: any = (window as any).URL || window;
  const export_blob = new Blob([mySerializedSVG]);
  const url = urlObject.createObjectURL(export_blob);

  const a = document.createElement('a');
  a.setAttribute(
    'download',
    `${(meta2d.store.data as Meta2dBackData).name || 'le5le.meta2d'}.svg`
  );
  a.setAttribute('href', url);
  const evt = document.createEvent('MouseEvents');
  evt.initEvent('click', true, true);
  a.dispatchEvent(evt);
};

const onUndo = () => {
  meta2d.undo();
};

const onRedo = () => {
  meta2d.redo();
};

const onCut = () => {
  meta2d.cut();
};

const onCopy = () => {
  meta2d.copy();
};

const onPaste = () => {
  meta2d.paste();
};

const onAll = () => {
  meta2d.activeAll();
};

const onDelete = () => {
  meta2d.delete();
};

const onToggleAnchor = () => {
  //取消连线状态
  // meta2d.store.options.disableAnchor = false;
  if (!meta2d.store.options.disableAnchor) {
    meta2d.canvas.drawingLineName && drawPen();
    meta2d.toggleAnchorMode();
  }
};

const onAddAnchorHand = () => {
  meta2d.addAnchorHand();
};

const onRemoveAnchorHand = () => {
  meta2d.removeAnchorHand();
};

const onToggleAnchorHand = () => {
  meta2d.toggleAnchorHand();
};

const onScaleUp = () => {
  const _scale = meta2d.store.data.scale + 0.1;
  meta2d.scale(_scale);
};

const onScaleDown = () => {
  const _scale = meta2d.store.data.scale - 0.1;
  meta2d.scale(_scale);
};

const autoAnchor = ref(true);
const onAutoAnchor = () => {
  meta2d.store.options.autoAnchor = !meta2d.store.options.autoAnchor;
  autoAnchor.value = meta2d.store.options.autoAnchor;
};

const showAnchor = ref(false);
const onDisableAnchor = () => {
  meta2d.store.options.disableAnchor = !meta2d.store.options.disableAnchor;
  changeDisableAnchor();
};

const changeDisableAnchor = () => {
  const { disableAnchor, autoAnchor } = meta2d.store.options;
  showAnchor.value = !disableAnchor || false;
  if (disableAnchor && autoAnchor) {
    // 禁用瞄点开了，需要关闭自动瞄点
    onAutoAnchor();
  }
};

const payListDialog = reactive({
  show: false,
  title:'',
  href:'',
  downloadUrl:''
});

const downloadZipDialog = reactive({
  show: false,
  checked:true,
  expend:false,
  price:0,
  list:[],
  hasJs:false,
});

const prePay = async () => {
  let list = [];
  let names = data.purchasedList.map((item) => item.name);
  if(data.payDiagram.checked){
      prePayList.pngs.forEach((item) => {
        if(!names.includes(item)){
          list.push({
            type: '图片图元',
            name: item,
          });
        }
      });
      prePayList.jsPens.forEach((item) => {
        if(!names.includes(item)){
          list.push({
            type: 'JS线性图元',
            name: item,
          });
        }
      });

      prePayList.iotPens.forEach((item) => {
        if(!names.includes(item)){
          list.push({
            type: '控件',
            name: item,
          });
        }
      });
      if ([...prePayList.svgPens].includes('*')) {
        list.push({
          type: 'SVG线性图元',
        });
      } else {
        prePayList.svgPens.forEach((item) => {
          if(!names.includes(item)){
            list.push({
              type: 'SVG线性图元',
              name: item,
            });
          }
        });
      }
  }
  const res: any = await axios.post('/api/order/deployment/submit', {
     goods:data.payGoods,
    '2ds':list,
  });
  wechatPayDialog.show = true;
  data.order = res;
};

const downloadTrial = () => {
  MessagePlugin.info('正在下载中，可能需要几分钟，请耐心等待...');
  //下载试用版
  window.open(payListDialog.downloadUrl, '_blank');
}
const skipPay = () => {
  //跳过支付，直接下载
  MessagePlugin.info('正在下载打包中，可能需要几分钟，请耐心等待...');
  if (downloadType === Frame.html) {
    preDownload();
  } else {
    preFrameDownload();
  }
};

const finishPay = async () => {
  // let id = data.order.id;
  // const result: { state: number } = await axios.post('/api/order/pay/state', {
  //   id,
  // });
  // if (result && result.state) {
    MessagePlugin.success('支付成功');
    wechatPayDialog.show = false;
    if(wechatPayDialog.isZip){
      // downloadZipDialog.show = false;
      wechatPayDialog.isZip = false;
      doDownloadZip();
    }else{
    payListDialog.show = false;
    MessagePlugin.loading('正在下载打包中，可能需要几分钟，请耐心等待...',0);
    if (downloadType === Frame.html) {
      preDownload();
    } else {
      preFrameDownload();
    }
  }
  // } else {
  //   MessagePlugin.error('支付失败');
  //   // wechatPayDialog.show = false;
  // }
};

const finalPrice = computed(() => {
  let total = 0;
  let price = 0;
  data.goods.forEach((item, index) => {
    if (item.checked) {
      total += item.unPurchased;
      price += item.unPurchased * item.unitPrice;
    }
  });
  return {
    total,
    price,
  };
});

const wechatPayDialog = reactive({
  show: false,
  isZip:false
});

const emit = defineEmits(['success']);

const onSuccess = (success: boolean) => {
  finishPay();
  emit('success', success);
};
</script>
<style lang="postcss" scoped>
.app-header {
  display: flex;
  height: 40px;
  background-color: var(--color-background);
  position: relative;
  z-index: 2;

  .logo {
    display: flex;
    padding: 0 16px;
    align-items: center;
    font-size: 14px;
    font-weight: 500;

    img {
      height: 20px;
      margin-right: 6px;
    }
  }

  a {
    display: flex;
    padding: 0 8px;
    margin: 0 8px;
    align-items: center;
    color: var(--color);
    text-decoration: none;
    white-space: nowrap;

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

    svg {
      font-size: 15px;
      margin: 2px 4px 0 0;
    }

    &.active {
      background-color: var(--color-primary);
      color: #ffffff;
    }
  }

  input {
    font-size: var(--font-size);
    flex-grow: 1;
    min-width: 100px;
    background: none;
    outline: none;
    border: none;
    text-align: center;
    color: var(--color-title);
  }
}

.pay-box{
  background: rgba(175,202,255,0.04);
  border-radius: 4px;
  margin-bottom:24px;
  padding:20px 24px;
  position:relative;
  display:flex;
  .pay-up{
    display:flex;
  }
 :deep(.t-checkbox__label){
  font-size: 16px;
    color: #6e7b91;
    margin-left:16px;
 }

  .pay-title{
    font-size: 16px;
    color: #6e7b91;
    .t-icon{
      margin-top:-5px;
      margin-left:12px;
    }
    :deep(.t-checkbox__input){
      background:#fff0;
    }
    :deep(.t-is-checked){
      .t-checkbox__input{
        background:var(--color-primary);
      }
    }
  }
  .pay-price{
    position:absolute;
    right:24px;
    color:#4480F9;
    display:flex;
    p:nth-child(2){
      font-size: 20px;
    }
  }

  .pay-down{
    margin-top:16px;
    display:flex;
    flex-wrap:wrap;
    /* justify-content:space-between; */
    /* padding-top:24px; */
    max-height: 200px;
    overflow-y: scroll;
    &>div{
      width: 48px;
      height: 48px;
      background: #1c283b;
      border-radius: 4px;
      margin-right:2.5px;
      margin-bottom:2.5px;
      &:nth-child(12n){
        margin-right: 0px;
      }
      img{
        margin:4px;
        width:40px;
        height:40px;
      }
      .l-icon{
        /* width: 80px; */
        /* height: 80px; */
        /* margin:8px; */
        font-size:24px;
        margin:12px;
      }
      &>div{
        margin: 8px 12px;
      }
    }
    &>p{
      display: block;
      margin-top:8px;
      width:100%;
    }
  }
}
.pay-footer{
  display:flex;
  margin-bottom: -48px;
  margin-left:24px;
  font-size: 14px;
  &>div{
    color:#4480F9;
    display:flex;
    p:nth-child(2){
      font-size: 24px;
      font-weight: 800;
      margin-top:-3px;
    }
    p:nth-child(1){
      margin:0px 4px;
    }
  }
}
.pay-diagram{
    flex-direction:column;
}

/* .pay-dialog {
  background-color: red;
} */

/* .pay-body {
  height: 300px;
  overflow-y: scroll;
  margin-bottom: 30px;

  .t-collapse {
    border: 0px;

    :deep(.t-collapse-panel__wrapper .t-collapse-panel__header) {
      border-bottom: 0px;
    }

    :deep(.t-collapse-panel__wrapper .t-collapse-panel__body) {
      background: #fff0;
      border-bottom: 0px;

      .t-collapse-panel__content {
        padding: 0;
        color: #c1c8d7;
      }
    }
  }
} */

/* .pay-line {
  display: flex;
  height: 54px;
  background-color: #afcaff0a;
  margin-top: 1px;

  div {
    width: 30%;
    text-align: center;
    line-height: 54px;

    :deep(.t-image) {
      width: 40px;
      height: 40px;
      margin-top: 7px;
    }

    :deep(.pay-svg) {
      .t-image {
        background: #fff;
      }
    }

    .l-icon {
      width: 40px;
      height: 40px;
      margin-top: 7px;
      width: 30%;
    }
  }

  .pay-p{
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }

  & > div:first-child {
    width: 40%;
    display: flex;
  }
} */

/* .pay-tip {
  height: 54px;
  width: 100%;
  position: relative;

  p {
    position: absolute;
    right: 16px;
    color: var(--color-desc);
  }
}

.pay-footer {
  margin-bottom: -42px;
  position: relative;

  .pay-price {
    position: absolute;
    right: 215px;
   margin-left: 50px; 
    align-items: flex-end;
    line-height: 10px;

     p{
    vertical-align: bottom;
    line-height: normal;
  } 
    p:nth-child(2) {
      font-size: 32px;
      font-weight: Semibold;
      color: #4480f9;
      line-height: 20px;
    }

    p:nth-child(1) {
      font-size: 14px;
      color: #4480f9;
    }
  }
} */

/* .pay-title {
  margin: 18px 0px 12px 18px;
} */
</style>
