import axios from "axios"
import { useSlidesStore } from "@/store"
import { slides as slidesData } from "@/mocks/slides"
/**
 * http 请求json
 */

export function getHttpJson(url: string): Promise<{ code: number; data: Record<string, any> }> {
  return new Promise((res, rej) => {
    axios
      .get(url)
      .then(resData => {
        if (resData.status === 200 && typeof resData.data === "object") {
          res({
            code: 200,
            data: resData.data
          })
        } else {
          res({
            code: 500,
            data: {}
          })
        }
      })
      .catch(() => {
        res({
          code: 500,
          data: {}
        })
      })
  })
}

export function jsonToPpt(jsonData: Record<string, any>) {
  const slidesStore = useSlidesStore()
  const { width, theme, slides } = jsonData
  slidesStore.updateSlideIndex(0)
  slidesStore.setViewportSize(width || 1920)
  slidesStore.setViewportRatio(theme.viewportRatio || 0.5625)
  // 兼容妙极客 这里过滤一下这个数据
  const newSlides = formatSlides(slides)
  slidesStore.setTheme(theme)
  slidesStore.setSlides(newSlides.length ? newSlides : slidesData)
}

export function getJsonToBlob() {
  const slidesStore = useSlidesStore()
  const { slides, theme, viewportRatio, viewportSize, title } = slidesStore
  const json = {
    width: viewportSize,
    height: viewportSize * viewportRatio,
    slides: slides,
    theme: Object.assign(theme, { viewportRatio })
  }
  return {
    blob: new Blob([JSON.stringify(json)]),
    title
  }
}

function formatSlides(slides: any[]): any[] {
  return (slides || []).map(item => {
    // 背景兼容  当为渐变并且没有渐变数据的时候，判定为妙极客数据兼容
    if (item.background?.type === "gradient") {
      if (item.background.gradientType === "linear" && !item.background?.gradient) {
        item.background.gradient = {
          colors: [
            { pos: 0, color: (item.background.gradientColor && item.background.gradientColor[0]) || "rgba(255,255,255,1)" },
            { pos: 100, color: (item.background.gradientColor && item.background.gradientColor[1]) || "rgba(255,255,255,1)" }
          ],
          rotate: item.background.gradientRotate || 0,
          type: item.background.gradientType
        }
      }
    }
    ;(item.elements || []).map((el: any) => {
      // 兼容块
      if (el.type === "shape") {
        if (el.gradient?.type == "linear" && !el.gradient?.colors) {
          el.gradient.colors = [
            { pos: 0, color: (el.gradient.color && el.gradient.color[0]) || "rgba(255,255,255,1)" },
            { pos: 100, color: (el.gradient.color && el.gradient.color[1]) || "rgba(255,255,255,1)" }
          ]
        }
      }
    })
    return item
  })
}
