<template>
  <div class="graphics">
    <div class="input-search">
      <div class="btn">
        <t-icon name="search" />
      </div>
      <t-input placeholder="搜索" />
    </div>
    <div class="groups">
      <div class="sub-groups">
        <div
          v-for="group in groups"
          :class="group.name === activeGroup ? 'active' : ''"
          @click="groupChange(group.name)"
        >
          <t-icon :name="group.icon" />
          {{ group.name }}
        </div>
      </div>
      <div class="list" :class="showType === 1 ? 'two-list' : ''">
        <t-collapse v-model:value="panelValue" @change="handlePanelChange">
          <t-collapse-panel :header="item.name" v-for="item in showList">
            <div
              class="show-item"
              v-for="iItem in item.list"
              :draggable="true"
              @dragstart="dragStart($event, iItem)"
              @drag="drag($event, iItem)"
              @dragend="dragEnd()"
            >
              <t-image v-if="iItem.image" :src="iItem.image" fit="cover" />
              <div class="svg-box" v-else-if="iItem.svg" v-html="iItem.svg" />
              <svg v-else class="l-icon" aria-hidden="true">
                <use :xlink:href="'#' + iItem.icon"></use>
              </svg>
              <p :title="iItem.name">{{ iItem.name }}</p>
            </div>
          </t-collapse-panel>
        </t-collapse>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { shapeLib, chartLib, formLib } from '@/services/defaults';
import { getPngFolders, getPngs } from '@/services/png';
import { getIconFolders, getIcons } from '@/services/icons';
import { getComponents, getComponentsList } from '@/services/api';
import { convertPen } from '@/services/upgrade';
import { deepClone } from '@meta2d/core';
import { isGif } from '@/services/utils';

const activeGroup = ref('图形');
const groups = reactive([
  {
    icon: 'desktop',
    name: '场景',
    key: '',
  },
  {
    icon: 'root-list',
    name: '模板',
    key: '',
  },
  {
    icon: 'chart',
    name: '图表',
    key: 'chart',
  },
  {
    icon: 'control-platform',
    name: '控件',
    key: '',
  },
  {
    icon: 'image',
    name: '素材',
    key: '',
  },
  {
    icon: 'file-icon',
    name: '图标',
    key: '',
  },
  {
    icon: 'chart-bubble',
    name: '图形',
    key: 'shape',
  },
  {
    icon: 'app',
    name: '我的',
    key: '',
  },
]);

const getSceneLib = () => {};

const getCommponentsLib = async () => {
  const data = {
    projection: {
      image: 1,
      _id: 1,
      name: 1,
      folder: 1,
      component: 1,
    },
  };
  const config = {
    params: {
      current: 1,
      pageSize: 100,
    },
  };
  const res: any = await getComponentsList(data, config);
  const folderMap: any = {};
  res.list?.map((item: any) => {
    if (!folderMap[item.folder]) {
      folderMap[item.folder] = [];
    }

    folderMap[item.folder].push(item);
  });
  let list = [];
  for (let key in folderMap) {
    list.push({
      name: key === 'undefined' ? '未分类' : key,
      show: true,
      list: folderMap[key],
    });
  }

  return list;
};

const getMaterialLib = async () => {
  const pngs = await getPngFolders();
  console.log('png', pngs);
  return pngs;
};
let materialLib: any[] = [];

const getIconsLib = async () => {
  const icons = await getIconFolders();
  console.log(icons);
  return icons;
};

let iconsLib: any[] = [];

const groupChange = async (name: string) => {
  panelValue.value = [];
  activeGroup.value = name;
  showType.value = 0;
  switch (name) {
    case '场景':
      showList.value = [];
      break;
    case '模版':
      showList.value = [];
      break;
    case '图表':
      showList.value = chartLib;
      break;
    case '控件':
      showList.value = formLib;
      break;
    case '素材':
      if (materialLib.length === 0) {
        materialLib = await getMaterialLib();
      }
      console.log(materialLib);
      showList.value = materialLib;
      break;
    case '图标':
      if (iconsLib.length === 0) {
        iconsLib = await getIconsLib();
      }
      showList.value = iconsLib;
      break;
    case '图形':
      showList.value = shapeLib;
      break;
    case '我的':
      showList.value = await getCommponentsLib();
      showType.value = 1;
      break;
  }
};

const showList = ref<any[]>([]);
const showType = ref(0);
const panelValue = ref([]);
const handlePanelChange = (e: any) => {
  console.log('e', e);
  // console.log("change", e,panelValue.value);
  // if (activeGroup.value === '素材') {
  //   const data:any = materialLib[e[0]];
  //   console.log("data", data.name);
  //   if (!data.list || data.list.length === 0) {
  //     data.list = getPngs(globalThis.folderJson?data.pinyin:data.name)
  //   }
  // }
};

watch(
  () => panelValue.value,
  async (newV: any[], oldV: any[]) => {
    console.log(newV, oldV);
    const newOpen: any = [];
    for (let v of newV) {
      !oldV.includes(v) && newOpen.push(v);
    }
    if (newOpen.length === 0) {
      return;
    }
    console.log(newOpen);
    if (activeGroup.value === '素材') {
      const data: any = materialLib[newOpen[0]];
      console.log('data', data, newOpen[0]);
      if (!data.list || data.list.length === 0) {
        data.list = await getPngs(
          globalThis.folderJson ? data.pinyin : data.name
        );
        console.log(materialLib);
        showList.value = deepClone(materialLib);
      }
    } else if (activeGroup.value === '图标') {
      const data: any = iconsLib[newOpen[0]];
      if (!data.list || data.list.length === 0) {
        data.list = await getIcons(
          globalThis.folderJson ? data.pinyin : data.name
        );
        showList.value = deepClone(iconsLib);
      }
    }
  }
);

const dragStart = async (event: DragEvent, item: any) => {
  // console.log('drag', item);
  console.log(event, item);

  if (!item || !event.dataTransfer) {
    return;
  }
  if (item._id && !item.componentDatas) {
    let res: any = await getComponents(item._id);
    item.component = true;
    item.componentDatas = res.componentDatas;
    item.componentData = res.componentData;
  }
  if (!item.data && !item.component && item.image) {
    let target: any = event.target;
    target.children[0] && (target = target.children[0].children[0]);
    // firefox naturalWidth svg 图片 可能是 0
    const normalWidth = target.naturalWidth || target.width;
    const normalHeight = target.naturalHeight || target.height;
    const [name, lockedOnCombine] = isGif(item.image)
      ? ['gif', 0]
      : ['image', undefined];
    event.dataTransfer.setData(
      'Meta2d',
      JSON.stringify({
        name,
        width: 100,
        height: 100 * (normalHeight / normalWidth),
        image: item.image,
        imageRatio: true,
        lockedOnCombine,
      })
    );
  } else if (item.component) {
    console.log('comp', item.componentDatas, item.componentData);
    if (item.componentData) {
      const pens = convertPen([item.componentData]);
      meta2d.canvas.addCaches = deepClone(pens);
    } else if (item.componentDatas) {
      console.log('进入');
      meta2d.canvas.addCaches = deepClone(item.componentDatas);
    }
  } else {
    event.dataTransfer.setData(
      'Meta2d',
      JSON.stringify(item.componentDatas || item.data)
    );
  }
  event.stopPropagation();
};

const drag = (event: DragEvent, item: any) => {};

const dragEnd = () => {};

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

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

//获取所有图形库
const getGraphics = async () => {
  // if (!materialLib.length) {
  //   materialLib = await getPngFolders();
  // }
};

onMounted(() => {
  groupChange('图形');
  document.removeEventListener('dragstart', dragstart);
  document.removeEventListener('dragend', dragend);
});

onUnmounted(() => {
  document.addEventListener('dragstart', dragstart, false);
  document.addEventListener('dragend', dragend, false);
});
</script>
<style lang="postcss" scoped>
.graphics {
  display: flex;
  flex-direction: column;

  .input-search {
    flex-shrink: 0;
    height: 40px;
  }

  .groups {
    display: grid;
    grid-template-columns: 50px 1fr;
    border-top: 1px solid var(--color-background-input);
    flex-grow: 1;
    overflow-y: auto;
    font-size: 12px;

    .sub-groups {
      & > div {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 16px 4px;
        line-height: 1;
        cursor: pointer;

        .t-icon {
          font-size: 20px;
          margin-bottom: 8px;
        }

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

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

    .list {
      overflow-y: auto;
      max-height: calc(100vh - 100px);
      background-color: var(--color-background-active);
      padding-top: 8px;

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

      :deep(.t-collapse) {
        border: none;
      }
      :deep(.t-collapse-panel__header) {
        border: none;
        font-size: 12px;
        font-weight: 400;
        padding: 8px 16px;
        &:hover {
          color: var(--color-primary);
        }
      }

      :deep(.t-collapse-panel__body) {
        border: none;
      }
      :deep(.t-collapse-panel__content) {
        background-color: var(--color-background-active);
        padding: 4px 4px 20px 4px;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        grid-row-gap: 20px;
      }
      .show-item {
        &:hover {
          cursor: pointer;
          color: var(--color-primary-hover);
          svg {
            color: var(--color-primary-hover);
          }
        }
        p {
          text-align: center;
          font-size: 12px;
          height: 14px;
          line-height: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          word-break: break-all;
          -webkit-box-orient: vertical;
        }
        .t-image__wrapper {
          height: 32px;
          width: 32px;
          background: #fff0;
          margin-left: calc(50% - 16px);
          margin-top: 10px;
          margin-bottom: 10px;
          :deep(.t-image) {
            border-radius: 2px;
          }
        }

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

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

    .two-list {
      :deep(.t-collapse-panel__content) {
        padding: 8px;
        grid-template-columns: 116px 116px;
        grid-template-rows: 136px;
      }
      .show-item {
        p {
          margin-top: 10px;
          margin-bottom: 12px;
        }
        .t-image__wrapper {
          width: 88px;
          height: 88px;
          margin-left: 14px;
        }
      }
    }
  }
}
</style>
