<template>
  <div class="menu-content">
    <div class="gradient-text title">实时标绘</div>
    <div v-show="collaboration" style="display: flex; align-items: center; justify-content: flex-end; height: 90px">
      <div class="btn2" style="margin-left: 10px" @click="handleCloseCollaboration">关闭协同</div>
      <div class="btn2" style="margin-left: 10px" @click="handleSaveCollaboration">保存</div>
    </div>
    <div class="line">
      <div class="tabs1">
        <div v-for="(item, index) in menu" :key="index" :class="menuActive1 === index ? 'tab tab_active' : 'tab'" @click="clickTab(index)">
          {{ item.name }}
        </div>
      </div>
      <div class="btn-box">
        <div class="btn1" @click="handleScreenshot">
          <div class="icon1"></div>
          当前地图截图导出
        </div>
        <div v-show="!collaboration" class="btn2" @click="handleShare('1')">协同标绘</div>
        <div v-show="collaboration" class="btn2" @click="handleShowLayer">查看图层</div>
      </div>
    </div>
    <div v-if="menuActive1 === 0" class="content">
      <div class="box1">
        <div class="box-item">
          <div class="btn" @click="handleUndo">
            <div class="revoke-icon"></div>
            撤回
          </div>
          <div class="line2"></div>
          <div class="btn">
            <div class="delete-icon"></div>
            删除
          </div>
          <div class="line2"></div>
          <div class="btn" @click="handleShowDialog">
            <div class="save-icon"></div>
            保存
          </div>
        </div>
        <div class="btn">
          <div class="setting-icon"></div>
          设置
        </div>
      </div>
      <div class="tab-content">
        <div class="tabs2">
          <div
            v-for="(item, index) in menu[menuActive1].children"
            :key="index"
            :class="menuActive2 === index ? 'tab tab_active' : 'tab'"
            @click="clickTab2(index)"
          >
            {{ item.name }}
          </div>
        </div>
        <div class="tab-content2">
          <div v-show="menuActive2 === 0" class="line3">
            <LineWidthSelect v-model="mouseToolState.lineWidth" :options="lineWidthOptions" />
            <div class="color-container">
              <el-color-picker v-model="mouseToolState.color" popper-class="custom-color-picker" show-alpha />
            </div>
          </div>
          <div class="tab-list">
            <div
              v-for="(item, index) in menu[menuActive1].children[menuActive2].children"
              :key="index"
              :class="menuActive3 === index ? 'tab tab_active' : 'tab'"
              @click="clickTab3(item, index)"
            >
              <div :class="menuActive3 === index ? 'checked2' : 'checked1'"></div>
              <img :src="item.image" class="icon" />
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else-if="menuActive1 === 1" class="tab-content3">
      <!--      <div class="box1">-->
      <!--        <div class="box-item">-->
      <!--          <div class="btn">-->
      <!--            <div class="merge-icon"></div>-->
      <!--            合并-->
      <!--          </div>-->
      <!--        </div>-->
      <!--      </div>-->
      <div class="params-box">
        <el-input v-model="queryParams.pattern_name" class="custom-input" placeholder="请输入" @input="handleQuery">
          <template #prefix>
            <el-icon class="el-input__icon"><search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="custom-table">
        <div class="table-header">
          <div class="th">预案名称</div>
          <div class="th">操作</div>
        </div>
        <div v-for="(item, index) in patternList" :key="index" class="tr">
          <div class="td">
            <div>{{ item.pattern_name }}</div>
          </div>
          <div class="td td2">
            <div class="btn" @click="handleDelete(item.id)">
              <div class="delete-icon"></div>
              删除
            </div>
            <div class="line2"></div>
            <div class="btn" @click="handleEdit(item.id)">
              <div class="edit-icon"></div>
              编辑
            </div>
            <div class="line2"></div>
            <div class="btn" @click="handleShare('2', item.id)">
              <div class="share-icon"></div>
              分享
            </div>
          </div>
        </div>
        <div class="footer">
          <el-pagination
            background
            :hide-on-single-page="true"
            layout="total, prev, pager, next"
            :total="total"
            :page-size="queryParams.pageSize"
            :current-page="queryParams.page"
            @current-change="getList"
          />
        </div>
      </div>
    </div>
  </div>
  <!--添加文字-->
  <TextEdit v-model="showTextEdit" @add-text="addText" />
  <!--绘制提示信息-->
  <div v-show="tipTitle !== ''" class="tipTitle">{{ tipTitle }}</div>
  <!--保存修改弹窗-->
  <EditDialog v-if="showEdit" v-model="showEdit" :edit-data="editData" @submit="handleSubmit" />
  <Contact v-if="shareState.showShare" v-model="shareState.showShare" @close="handleCloseShare" @confirm="handleShareConfirm" />
  <Dialog v-model="showForm" title="协同标绘" type="xs" @confirm="handleSendForm">
    <div style="display: flex; align-items: center">
      <div style="font-size: 36px">预案名称</div>
      <el-input v-model="form.pattern_name" class="custom-input" placeholder="请输入" style="flex: 1" />
    </div>
  </Dialog>
  <LayerDetail v-if="showLayer" v-model="showLayer" :pattern-id="patternId" />
</template>

<script lang="ts" setup name="OnlinePlotting">
import { nanoid } from 'nanoid';
import { deepClone } from '@/utils';
import { useHistory } from '@/hooks/useHistory';
import { closeCollaboration, createCollaboration, deletePatternById, getPatternInfo, getPatternList } from '@/api/globalMap/onlinePlotting';
import TextEdit from '@/views/globalMap/RightMenu/OnlinePlotting/TextEdit.vue';
import EditDialog from '@/views/globalMap/RightMenu/OnlinePlotting/EditDialog.vue';
import { Search } from '@element-plus/icons-vue';
import html2canvas from 'html2canvas';
import LayerDetail from './LayerDetail.vue';
import { createWebSocket } from '@/utils/websocket';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const getDrawTool = inject('getDrawTool');
const getMap = inject('getMap');
const getMapUtils = inject('getMapUtils');
const containerScale = inject('containerScale');
const { currentState, commit, undo, history, future } = useHistory();
const emits = defineEmits(['getCollaborationData']);
const getImageUrl = (name) => {
  return new URL(`../../../../assets/images/map/rightMenu/onlinePlotting/icon/${name}.png`, import.meta.url).href;
};
let drawing = ref(false);
const mouseToolState = ref<MouseTool>({
  color: 'rgba(248, 1, 2, 1)',
  lineWidth: '1',
  graphicsType: ''
});
const menuActive1 = ref<string | number>(0);
const menuActive2 = ref<string | number>(0);
const menuActive3 = ref<string | number>('');
const menu = ref([
  {
    name: '标绘工具',
    children: [
      {
        name: '基本工具',
        value: 'basicTools',
        children: [
          // {
          //   name: '直箭头',
          //   value: 'straightArrow',
          //   image: getImageUrl('straightArrow')
          // },
          {
            name: '矩形',
            value: 'rectangle',
            image: getImageUrl('rectangle')
          },
          {
            name: '任意面',
            value: 'polygon',
            image: getImageUrl('polygon')
          },
          // {
          //   name: '任意线',
          //   value: 'anyLine',
          //   image: getImageUrl('anyLine')
          // },
          {
            name: '圆',
            value: 'circle',
            image: getImageUrl('circle')
          },
          {
            name: '直线',
            value: 'straightLine',
            image: getImageUrl('straightLine')
          },
          {
            name: '文字',
            value: 'text',
            image: getImageUrl('text')
          },
          {
            name: '面积',
            value: 'measureArea',
            image: getImageUrl('measureArea')
          }
        ]
      },
      {
        name: '火点',
        value: 'firePoint',
        children: [
          { name: '起火点', value: 'marker', image: getImageUrl('firePoint'), icon: getImageUrl('firePoint'), size: [48, 32] },
          { name: '烟点', value: 'marker', image: getImageUrl('smokePoint'), icon: getImageUrl('smokePoint'), size: [48, 32] },
          { name: '已灭火点', value: 'marker', image: getImageUrl('extinguishedPoint'), icon: getImageUrl('extinguishedPoint'), size: [48, 32] }
        ]
      },
      {
        name: '火线',
        value: 'firewire',
        children: [
          { name: '火线', value: 'marker', image: getImageUrl('firewire'), icon: getImageUrl('firewire'), size: [48, 32] },
          { name: '受控火线', value: 'marker', image: getImageUrl('controlledfireline'), icon: getImageUrl('controlledfireline'), size: [48, 32] },
          { name: '已灭火线', value: 'marker', image: getImageUrl('extinguishedline'), icon: getImageUrl('extinguishedline'), size: [48, 32] },
          { name: '强火线', value: 'marker', image: getImageUrl('StrongFrontline'), icon: getImageUrl('StrongFrontline'), size: [48, 32] },
          { name: '中火线', value: 'marker', image: getImageUrl('ZhongxianLine'), icon: getImageUrl('ZhongxianLine'), size: [48, 32] },
          { name: '弱火线', value: 'marker', image: getImageUrl('WeakFrontline'), icon: getImageUrl('WeakFrontline'), size: [48, 32] }
        ]
      },
      {
        name: '火场',
        value: 'fireGround',
        children: [
          { name: '火场', value: 'marker', image: getImageUrl('fireground'), icon: getImageUrl('fireground'), size: [48, 32] },
          {
            name: '受控火场',
            value: 'marker',
            image: getImageUrl('controlledfireground'),
            icon: getImageUrl('controlledfireground'),
            size: [48, 32]
          },
          {
            name: '已灭火场',
            value: 'marker',
            image: getImageUrl('extinguishedfireground'),
            icon: getImageUrl('extinguishedfireground'),
            size: [48, 32]
          }
        ]
      },
      {
        name: '箭头',
        value: 'arrow',
        children: [
          { name: '曲箭头', value: 'marker', image: getImageUrl('curvedarrow'), icon: getImageUrl('curvedarrow'), size: [48, 32] },
          { name: '直箭头', value: 'marker', image: getImageUrl('straightarrow1'), icon: getImageUrl('straightarrow1'), size: [48, 32] },
          { name: '细箭头', value: 'marker', image: getImageUrl('thinarrow'), icon: getImageUrl('thinarrow'), size: [48, 32] }
        ]
      },
      // {
      //   name: '导航',
      //   value: 'navigation',
      //   children: [
      //     { name: '导航', value: 'marker', image: getImageUrl('navigation'), icon: getImageUrl('navigation'), size: [166, 88] }
      //   ]
      // },
      {
        name: '扑救队伍',
        value: 'firefightingTeam',
        children: [
          { name: '指挥中心', value: 'marker', image: getImageUrl('commandcentre'), icon: getImageUrl('commandcentre'), size: [48, 32] },
          { name: '分指中心', value: 'marker', image: getImageUrl('dividingcenter'), icon: getImageUrl('dividingcenter'), size: [48, 32] },
          { name: '集结地', value: 'marker', image: getImageUrl('rendezvous'), icon: getImageUrl('rendezvous'), size: [48, 32] },
          { name: '军队', value: 'marker', image: getImageUrl('army'), icon: getImageUrl('army'), size: [48, 32] },
          { name: '武警', value: 'marker', image: getImageUrl('armedpolice'), icon: getImageUrl('armedpolice'), size: [48, 32] },
          { name: '森林警察', value: 'marker', image: getImageUrl('forestpoliceman'), icon: getImageUrl('forestpoliceman'), size: [48, 32] },
          { name: '扑火队伍', value: 'marker', image: getImageUrl('firefightingteam'), icon: getImageUrl('firefightingteam'), size: [48, 32] }
          // { name: '扑火队伍路线', value: 'marker', image: getImageUrl('Firefightingteamroute'), icon: getImageUrl('Firefightingteamroute'), size: [48, 32] }
        ]
      },
      {
        name: '飞机车辆',
        value: 'aircraftVehicles',
        children: [
          { name: '固定翼', value: 'marker', image: getImageUrl('fixedwing'), icon: getImageUrl('fixedwing'), size: [48, 32] },
          { name: '直升机', value: 'marker', image: getImageUrl('helicopter'), icon: getImageUrl('helicopter'), size: [48, 32] },
          { name: '无人机', value: 'marker', image: getImageUrl('UAV'), icon: getImageUrl('UAV'), size: [48, 32] },
          { name: '指挥车', value: 'marker', image: getImageUrl('commandvehicle'), icon: getImageUrl('commandvehicle'), size: [48, 32] },
          {
            name: '飞机航线设置',
            value: 'marker',
            image: getImageUrl('aircraftroutesetting'),
            icon: getImageUrl('aircraftroutesetting'),
            size: [48, 32]
          },
          {
            name: '直升机航线设置',
            value: 'marker',
            image: getImageUrl('helicopterroutesetting'),
            icon: getImageUrl('helicopterroutesetting'),
            size: [48, 32]
          }
        ]
      },
      {
        name: '基础设置',
        value: 'basicSetting',
        children: [
          { name: '航站', value: 'marker', image: getImageUrl('terminal'), icon: getImageUrl('terminal'), size: [48, 32] },
          {
            name: '起降点',
            value: 'marker',
            image: getImageUrl('takeoffandlandingpoint'),
            icon: getImageUrl('takeoffandlandingpoint'),
            size: [48, 32]
          },
          { name: '取水点', value: 'marker', image: getImageUrl('waterpoint'), icon: getImageUrl('waterpoint'), size: [48, 32] },
          { name: '瞭望塔', value: 'marker', image: getImageUrl('watchtower'), icon: getImageUrl('watchtower'), size: [48, 32] },
          { name: '物资库', value: 'marker', image: getImageUrl('materialwarehouse'), icon: getImageUrl('materialwarehouse'), size: [48, 32] }
        ]
      }
      // {
      //   name: '其他',
      //   value: 'other',
      //   children: [
      //     { name: '危险区域', value: 'marker', image: getImageUrl('dangerousarea'), icon: getImageUrl('dangerousarea'), size: [166, 88] },
      //     { name: '隔离带开采', value: 'marker', image: getImageUrl('Isolationzonemining'), icon: getImageUrl('Isolationzonemining'), size: [166, 88] },
      //     { name: '应急庇护场所', value: 'marker', image: getImageUrl('emergencyshelter'), icon: getImageUrl('emergencyshelter'), size: [166, 88] },
      //     { name: '风力风向', value: 'marker', image: getImageUrl('windspeedanddirection'), icon: getImageUrl('windspeedanddirection'), size: [166, 88] },
      //     { name: '测距', value: 'marker', image: getImageUrl('ranging'), icon: getImageUrl('ranging'), size: [166, 88] },
      //     { name: '大风', value: 'marker', image: getImageUrl('strongwind'), icon: getImageUrl('strongwind'), size: [166, 88] },
      //     { name: '人工降雨', value: 'marker', image: getImageUrl('artificialrainfall'), icon: getImageUrl('artificialrainfall'), size: [166, 88] },
      //     { name: '台风', value: 'marker', image: getImageUrl('typhoon'), icon: getImageUrl('typhoon'), size: [166, 88] }
      //   ]
      // }
    ]
  },
  {
    name: '历史预案',
    children: []
  }
]);
const lineWidthOptions = reactive([
  { name: '1像素', value: '1' },
  { name: '2像素', value: '2' },
  { name: '3像素', value: '3' }
]);
let showTextEdit = ref();
let lnglat = ref([]);
// 协同
let collaboration = ref(false);
// 分享
let shareState = reactive({
  type: '',
  showShare: false,
  id: ''
});
let patternId = ref('');
let shareId = ref('');
const overlays = [];
const overlaysData = [];
watch(
  () => drawing,
  () => {
    if (!drawing.value) {
      menuActive3.value = '';
    }
  }
);
const tipTitle = computed(() => {
  let res = '';
  if (
    menu.value[menuActive1.value] &&
    menu.value[menuActive1.value].children &&
    menu.value[menuActive1.value].children[menuActive2.value] &&
    menu.value[menuActive1.value].children[menuActive2.value].children &&
    menu.value[menuActive1.value].children[menuActive2.value].children[menuActive3.value]
  ) {
    const data = menu.value[menuActive1.value].children[menuActive2.value].children[menuActive3.value];
    if (data.value === 'straightArrow') {
      res = '单击开始、单击结束';
    } else if (['rectangle', 'polygon', 'anyLine', 'circle'].includes(data.value)) {
      res = '鼠标按住拖曳，松开鼠标结束标绘';
    } else if (['straightLine', 'measureArea'].includes(data.value)) {
      res = '单击开始，移动，单击改变方向，双击结束';
    }
  }
  return res;
});

// 点击一级菜单
const clickTab = (value: number) => {
  menuActive1.value = value;
};
// 点击二级菜单
const clickTab2 = (value: number) => {
  menuActive2.value = value;
};
// 点击三级菜单
const clickTab3 = (item, index) => {
  const type = item.value;
  if (mouseToolState.value.graphicsType !== type || (mouseToolState.value.graphicsType === 'marker' && mouseToolState.value.title !== item.name)) {
    if (type === 'text') {
      mouseToolState.value.graphicsType = type;
      handleTextEdit();
    } else if (type === 'marker') {
      const data = {
        graphicsType: type,
        lineWidth: mouseToolState.value.lineWidth,
        color: mouseToolState.value.color,
        icon: item.icon,
        size: item.size,
        title: item.name
      };
      drawing.value = true;
      mouseToolState.value = data;
    } else {
      showTextEdit.value = false;
      drawing.value = true;
      mouseToolState.value.graphicsType = type;
    }
    const drawTool = getDrawTool();
    const newOptions = drawTool.drawGraphics(mouseToolState.value);
    if (newOptions.graphicsType !== 'text') {
      // 绘制完成事件
      initDrawMethod(newOptions);
    }
    menuActive3.value = index;
  } else {
    showTextEdit.value = false;
    drawing.value = false;
    mouseToolState.value.graphicsType = '';
    menuActive3.value = '';
  }
};
const handleTextEdit = () => {
  const drawTool = getDrawTool();
  const map = drawTool.getMap();
  drawTool.closeDraw();
  // 监听地图点击事件
  map.on('click', handleClickMap);
};
const handleClickMap = (e) => {
  // 获取点击位置的经纬度
  lnglat.value = [e.lnglat.lng, e.lnglat.lat];
  showTextEdit.value = true;
};
const addText = (textEditState) => {
  const data = {
    graphicsType: 'text',
    lineWidth: mouseToolState.value.lineWidth,
    color: mouseToolState.value.color,
    text: textEditState.text,
    fontColor: textEditState.fontColor,
    fontSize: textEditState.fontSize,
    lnglat: lnglat.value
  };
  showTextEdit.value = false;
  drawing.value = true;
  mouseToolState.value = data;
  // 绘制完成事件
  const drawTool = getDrawTool();
  const res = drawTool.drawGraphics(mouseToolState.value);
  overlays.push(res.text);
  overlaysData.push(res.data);
  commit(deepClone(overlaysData));
  res.text.on('rightclick', handleRightClick);
  const map = drawTool.getMap();
  // 监听地图点击事件
  map.off('click', handleClickMap);
  close();
};
// watch(
//   () => mouseToolState.value.graphicsType,
//   (value) => {
//     if (value) {
//       const map = getMap();
//       map.off('click', handleClickMap);
//     }
//   }
// );
const changeDrawing = () => {
  drawing.value = !drawing.value;
};
const close = () => {
  const drawTool = getDrawTool();
  drawTool.closeDraw();
  drawing.value = false;
  menuActive3.value = '';
  mouseToolState.value.graphicsType = '';
};
// 初始化绘制完成回调
const initDrawMethod = (options) => {
  const drawTool = getDrawTool();
  const mouseTool = drawTool.getMouseTool();
  const onDraw = (event) => {
    mouseTool.off('draw', onDraw);
    close();
    const obj = event.obj;
    const id = nanoid();
    obj._opts.extData = {
      id: id
    };
    const data: any = deepClone(options);
    data.id = id;
    if (options.type == 'marker') {
      const position = obj.getPosition();
      data.lnglat = [position.lng, position.lat];
      data.latitude = position.lat;
      data.longitude = position.lng;
      data.image = data.icon;
      data.image = data.icon;
      data.imageHover = data.icon;
    } else {
      const path = obj.getPath();
      // 将AMap.LngLat对象数组转换为经纬度数组
      const pathArr = path.map((lngLat) => {
        // 返回经度和纬度的数组
        return [lngLat.lng, lngLat.lat];
      });
      if (options.type !== 'straightLine') {
        pathArr.push(pathArr[0]);
      }
      data.path = pathArr;
      if (options.type == 'circle') {
        data.center = [obj.getCenter().lng, obj.getCenter().lat];
        data.radius = obj.getRadius();
      }
    }
    if (options.type == 'measureArea') {
      const AMap = getDrawTool().getAMap();
      const map = getMap();
      // 计算区域面积
      const area = Math.round(AMap.GeometryUtil.ringArea(data.path));
      const text = new AMap.Text({
        position: data.path[data.path.length - 1],
        text: '区域面积' + area + '平方米',
        offset: new AMap.Pixel(-20, -20)
      });
      data.area = area;
      map.add(text);
      overlays.push([obj, text]);
      overlaysData.push(data);
      commit(deepClone(overlaysData));
    } else {
      overlays.push(obj);
      overlaysData.push(data);
      commit(deepClone(overlaysData));
      console.log(overlaysData);
    }
    // 右击进入编辑
    obj.on('rightclick', handleRightClick);
  };
  mouseTool.on('draw', onDraw);
};
// 图形右击事件
let rightClickObj;
let initContextMenu = false;
const handleRightClick = (event) => {
  rightClickObj = event.target;
  const contextMenu = getDrawTool().getContextMenu();
  if (!initContextMenu) {
    // 右键删除按钮
    contextMenu.addItem(
      '删除',
      function () {
        contextMenu.close();
        deleteGraphics();
      },
      0
    );
    initContextMenu = true;
  }
  contextMenu.open(getMap(), event.lnglat);
};
// 删除图形
const deleteGraphics = () => {
  const id = rightClickObj.getExtData()?.id;
  if (id) {
    for (let i = 0; i < overlays.length; i++) {
      const overlay = Array.isArray(overlays[i]) ? overlays[i][0] : overlays[i];
      if (overlay?.getExtData().id === id) {
        removeOverlayByIndex(i);
        commit(deepClone(overlaysData));
        rightClickObj = null;
      }
    }
  }
};
// 撤销绘制
const handleUndo = () => {
  // drawing.value = false;
  const previous = history.value[history.value.length - 2];
  if (history.value.length > 1) {
    if (currentState.value.length > previous.length) {
      // 撤销新增
      removeOverlayByIndex(currentState.value.length - 1);
    } else {
      let restoreData;
      for (let i = 0; i < previous.length; i++) {
        let index = 0;
        for (let k = 0; k < currentState.value.length; k++) {
          if (previous[i].id !== currentState.value[k].id) {
            index++;
          } else {
            break;
          }
        }
        if (index === previous.length - 1) {
          restoreData = previous[i];
          break;
        }
      }
      if (restoreData) {
        const obj = getDrawTool().createGraphics(restoreData);
        overlays.push(obj);
      }
    }
    undo();

    console.log(history.value, future.value, currentState.value);
  }
};
// 根据索引移除覆盖物
const removeOverlayByIndex = (index: number) => {
  const map = getMap();
  if (Array.isArray(overlays[index])) {
    overlays[index].forEach((overlay) => {
      // 移除地图上覆盖物
      map.remove(overlay);
    });
  } else {
    // 移除地图上覆盖物
    map.remove(overlays[index]);
  }
  overlays.splice(index, 1);
  overlaysData.splice(index, 1);
};

// 历史预案
const queryParams = reactive({
  page: 1,
  pageSize: 9,
  pattern_name: ''
});

const patternList = ref([]);
let total = ref(0);
let editData = ref({
  id: '',
  pattern_name: '',
  content: {}
});
let showEdit = ref(false);
const handleSubmit = () => {
  showEdit.value = false;
  editData.value = {
    id: '',
    pattern_name: '',
    content: {}
  };
  getList();
};
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};
const getList = () => {
  // if (menuActive1.value === 1 && menu.value[menuActive1.value].name == '历史预案') {
  getPatternList(queryParams).then((res) => {
    patternList.value = res.data;
    total.value = res.total;
  });
  // }
};
const handleDelete = (id: number) => {
  proxy?.$modal.confirm('是否确认删除选择的数据项？').then(() => {
    deletePatternById(id).then(() => {
      getList();
    });
  });
};
const handleEdit = (id) => {
  getPatternInfo(id).then((res) => {
    editData.value = res.data;
    editData.value.id = id;
  });
  showEdit.value = true;
};
const handleShare = (type, id?: string) => {
  shareState.type = type;
  shareState.id = id;
  shareState.showShare = true;
};
const handleCloseShare = () => {
  shareState.type = '';
  shareState.id = '';
};
const handleCloseCollaboration = () => {
  closeCollaboration({ pattern_id: patternId.value }).then(() => {
    collaboration.value = false;
  });
};
const handleSaveCollaboration = () => {

};
let showForm = ref(false);
let form = ref({
  pattern_id: '',
  user_id_list: [],
  name: '',
  pattern_name: '',
  visible: 'false',
  content: ''
});
const handleShareConfirm = (data) => {
  if (shareState.type === '1') {
    // 协同标绘
    const userIdList = [];
    data.forEach((item) => {
      userIdList.push(item.userId);
    });
    let content = currentState.value.length > 0 ? JSON.stringify(currentState.value[currentState.value.length - 1]) : '';
    form.value = {
      pattern_id: nanoid(),
      user_id_list: userIdList,
      name: '',
      pattern_name: '',
      visible: 'false',
      content: content
    };
    showForm.value = true;
  } else {
    // 分享
  }
  shareState.type = '';
  shareState.id = '';
};
const getWebSocketData = (data) => {
  console.log('接收数据', data);
};
const handleSendForm = () => {
  // createWebSocket('v7fUAuygwZUs24Nx3RDnL', getWebSocketData);
  // patternId.value = 'v7fUAuygwZUs24Nx3RDnL';
  createCollaboration(form.value).then(() => {
    patternId.value = form.value.pattern_id;
    createWebSocket(form.value.pattern_id, getWebSocketData);
  });
  collaboration.value = true;
};
const handleShowDialog = () => {
  editData.value = {
    id: '',
    pattern_name: '',
    content: currentState.value
  };
  showEdit.value = true;
};
let dataURL = ref('');
// 页面元素转图片
const handleScreenshot = () => {
  const canvasBox = getMap().Iv;
  // 手动创建一个 canvas 标签
  const canvas = document.createElement('canvas');
  if (canvasBox) {
    // 获取父级的宽高
    const width = parseInt(window.getComputedStyle(canvasBox).width) / containerScale().scaleX;
    const height = parseInt(window.getComputedStyle(canvasBox).height) / containerScale().scaleX;
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
    const options = {
      backgroundColor: null, // 设置背景色为透明
      useCORS: true, //是否尝试使用CORS从服务器加载图像，解决跨域问题
      tainttest: true, // 是否在渲染前测试图片
      logging: false // 不启动日志调试
    };
    // canvasBox是要截图的元素，options是一些相关配置
    html2canvas(canvasBox, options).then((canvas) => {
      // toDataURL 图片格式转成 base64
      dataURL.value = canvas.toDataURL('image/png');
      // 新建一个a标签
      var oA = document.createElement('a');
      oA.download = '截图'; // 设置下载的文件名
      oA.href = dataURL.value;
      document.body.appendChild(oA);
      oA.click(); // 模拟点击a标签
      oA.remove(); // 下载之后把创建的元素删除
    });
  }
};

let showLayer = ref(false);
let handleShowLayer = () => {
  showLayer.value = true;
};
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.menu-content {
  width: 1584px;
  height: 1772px;
  background: url('@/assets/images/map/rightMenu/onlinePlotting/dialog.png') no-repeat;
  padding: 130px 45px 20px 50px;
  font-size: 36px;
  position: relative;
  color: #ffffff;
}
.title {
  font-size: 60px;
  position: absolute;
  top: 30px;
  left: 140px;
}

:deep(.el-color-dropdown__link-btn) {
  display: none;
}
.line {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tabs1 {
  margin-top: 45px;
  display: flex;
  .tab {
    width: 316px;
    height: 77px;
    line-height: 77px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/tab.png') no-repeat;
    cursor: pointer;
    font-size: 44px;
    color: #b7c1d5;
    font-family: YouSheBiaoTiHei;
    padding-left: 60px;
    &:hover {
      width: 317px;
      height: 83px;
      color: #ffffff;
      background: url('@/assets/images/map/rightMenu/onlinePlotting/tabActive.png') no-repeat;
    }
  }
  .tab_active {
    width: 317px;
    height: 83px;
    color: #ffffff;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/tabActive.png') no-repeat;
  }
}
.btn1 {
  width: 440px;
  height: 150px;
  background: url('@/assets/images/map/rightMenu/onlinePlotting/btn1.png') no-repeat;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 32px;
  color: #edfaff;
  margin-bottom: -55px;
  .icon1 {
    width: 42px;
    height: 42px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/screenshot.png') no-repeat;
    margin-right: 12px;
  }
}
.btn2 {
  width: 278px;
  height: 78px;
  background: url('@/assets/images/map/rightMenu/btn.png') no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 32px;
  color: #edfaff;
  margin-bottom: -57px;
  .icon1 {
    width: 42px;
    height: 42px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/screenshot.png') no-repeat;
    margin-right: 12px;
  }
}
.box1 {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 1490px;
  height: 96px;
  background: url('@/assets/images/map/rightMenu/onlinePlotting/box1.png') no-repeat;
  padding: 25px 30px;
  .box-item {
    display: flex;
    align-items: center;
  }
}
.btn {
  display: flex;
  align-items: center;
  cursor: pointer;
  .revoke-icon {
    width: 48px;
    height: 50px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/revoke.png') no-repeat;
  }
  .delete-icon {
    width: 50px;
    height: 50px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/delete.png') no-repeat;
  }
  .edit-icon {
    width: 46px;
    height: 46px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/edit.png') no-repeat;
  }
  .cancel-icon {
    width: 50px;
    height: 50px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/cancel.png') no-repeat;
  }
  .save-icon {
    width: 46px;
    height: 46px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/save.png') no-repeat;
  }
  .share-icon {
    width: 46px;
    height: 48px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/share.png') no-repeat;
  }
  .setting-icon {
    width: 48px;
    height: 50px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/setting.png') no-repeat;
  }
  .merge-icon {
    width: 52px;
    height: 52px;
    margin-right: 10px;
    background: url('@/assets/images/map/rightMenu/onlinePlotting/merge.png') no-repeat;
  }
}
.line2 {
  width: 3px;
  height: 24px;
  background-color: #a7ccdf;
  margin: 0 38px;
}
.tabs2 {
  width: 300px;
  min-width: 300px;
  height: 1240px;
  background: url('@/assets/images/map/rightMenu/onlinePlotting/tabBg.png') no-repeat;
  background-size: 300px 1188px;
  overflow-y: auto;
  padding: 30px 0;
  .tab {
    width: 100%;
    height: 99px;
    cursor: pointer;
    color: #eaf3fc;
    font-size: 38px;
    padding: 0 60px;
    display: flex;
    align-items: center;
    &:hover {
      background: url('@/assets/images/map/rightMenu/onlinePlotting/tabActive2.png') no-repeat;
    }
  }
  .tab_active {
    background: url('@/assets/images/map/rightMenu/onlinePlotting/tabActive2.png') no-repeat;
  }
}
.tab-content {
  display: flex;
  margin-top: 20px;
  .tab-content2 {
    padding: 20px 45px;
    display: flex;
    flex-direction: column;
    .line {
      height: 100px;
    }
    .line3 {
      display: flex;
    }
    .tab-list {
      width: 100%;
      flex: 1;
      overflow-y: auto;
      display: flex;
      flex-wrap: wrap;
      align-content: baseline;
      .icon {
        width: 160px;
        height: 88px;
        margin-bottom: 20px;
      }
      .tab {
        &:nth-child(3n-1) {
          margin: 40px 50px 0;
        }
      }
    }
    .tab {
      width: 333px;
      height: 235px;
      background: url('@/assets/images/map/rightMenu/onlinePlotting/box2.png') no-repeat;
      padding: 27px;
      cursor: pointer;
      position: relative;
      font-size: 38px;
      color: #eaf3fc;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 40px;
      &:hover {
        background: url('@/assets/images/map/rightMenu/onlinePlotting/boxHover2.png') no-repeat;
      }
      .checked1 {
        position: absolute;
        top: 30px;
        right: 30px;
        width: 32px;
        height: 32px;
        background: url('@/assets/images/map/rightMenu/onlinePlotting/checked1.png') no-repeat;
      }
      .checked2 {
        position: absolute;
        top: 30px;
        right: 30px;
        width: 36px;
        height: 36px;
        background: url('@/assets/images/map/rightMenu/onlinePlotting/checked2.png') no-repeat;
      }
    }
    .tab_active {
      background: url('@/assets/images/map/rightMenu/onlinePlotting/boxActive2.png') no-repeat;
    }
  }
}

.tipTitle {
  position: absolute;
  top: 0;
  left: -2745px;
  z-index: 2;
  padding: 10px 30px;
  font-size: 38px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 10px;
}
.tab-content3 {
  .custom-table {
    width: 100%;
    color: #000;
    .table-header {
      display: flex;
      font-size: 38px;
      width: 100%;
      background-color: #194ba0;
      .th {
        padding: 25px 30px;
        flex: 1;
        color: #edfaff;
        &:last-child {
          flex: unset;
          width: 620px;
        }
      }
    }
    .tr {
      display: flex;
      font-size: 38px;
      width: 1487px;
      background: url('@/assets/images/map/rightMenu/onlinePlotting/tr.png') no-repeat;
      background-size: 100% 100%;
      margin-top: 10px;
      &:hover {
        background: url('@/assets/images/map/rightMenu/onlinePlotting/trActive.png') no-repeat;
      }
      .td {
        padding: 25px 30px;
        color: #edfaff;
        flex: 1;
        .icon {
          margin: 0 10px;
          cursor: pointer;
        }
      }
      .td2 {
        flex: unset;
        width: 620px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}

.color-container {
  width: 80px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  background-color: #0d3980;
  border: 4px solid #0b5fbb;
  margin-left: 20px;
  :deep(.el-color-picker) {
    height: 60px !important;
  }
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 12px;
    height: 12px;
    background: url('@/assets/images/inputIcon1.png') no-repeat;
  }
  &::after {
    content: '';
    position: absolute;
    right: 0;
    bottom: 0;
    width: 12px;
    height: 12px;
    background: url('@/assets/images/inputIcon2.png') no-repeat;
  }
}
.params-box {
  margin: 30px 0;
}
.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-right: 40px;
  :deep(.el-pagination__total) {
    color: #a7ccdf;
    font-size: 32px;
  }

  :deep(.el-pagination) {
    .btn-next,
    .btn-prev {
      background-color: transparent;
      border: none;
      .el-icon {
        font-size: 22px;
        color: #a7ccdf;
      }
    }
    .el-pager li {
      width: 64px;
      height: 64px;
      line-height: 64px;
      text-align: center;
      font-size: 32px;
      color: #a7ccdf;
      background-color: #0e3064;
      border: 1px solid #0c57a7;
      margin: 0 6px;
      &:hover {
        background-color: #038dff;
        border: 1px solid #038dff;
      }
    }
    .el-pager li.is-active {
      background-color: #038dff;
      border: 1px solid #038dff;
    }
  }
}
.btn-box {
  display: flex;
  align-items: center;
}
</style>
