import {dicts} from "@/utils/dicts";
import axios from 'axios'
import Vue from 'vue'

window.axios = axios
const KENGEE_CDN_BASE = "http://10.0.97.209/presource/datascreen"
const libs = [
  `${KENGEE_CDN_BASE}/js/pinyin.min.js`,
  `${KENGEE_CDN_BASE}/js/dayjs.min.js`,
  `${KENGEE_CDN_BASE}/js/Tween.js`,
  `${KENGEE_CDN_BASE}/js/three/three.min.js`,
  `${KENGEE_CDN_BASE}/js/d3-array.min.js`,
  `${KENGEE_CDN_BASE}/js/d3-geo.min.js`,
  '/presource/datascreen/js/ezuikit-flv/ezuikit.js',
  '/presource/datascreen/js/clappr.min.js',
  '/presource/datascreen/js/simplebar/simplebar.min.js',
]
const css = [
  "/presource/datascreen/js/simplebar/simplebar.css"
]
window.$loadScript = (type = 'js', url, dom = "body") => {
  let flag = false;
  return new Promise((resolve) => {
    const head = dom == 'head' ? document.getElementsByTagName('head')[0] : document.body;
    for (let i = 0; i < head.children.length; i++) {
      let ele = head.children[i]
      if ((ele.src || '').indexOf(url) !== -1) {
        flag = true;
        resolve();
      }
    }
    if (flag) return;
    let script;
    if (type === 'js') {
      script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
    } else if (type === 'css') {
      script = document.createElement('link');
      script.rel = 'stylesheet';
      script.type = 'text/css';
      script.href = url;
    }
    head.appendChild(script);
    script.onload = function () {
      resolve();
    };
  });
};
window.$glob = {token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoLXVzZXItaWQiOiIxODA4MDM2NzI3NzQzNDU1MjMyIiwiaC1yb2xlLWlkIjoiMTgwODAzNjg5NDQxMjUxMzI4MCIsImV4cCI6MTc1MTQ0NDg0MywibmJmIjoxNzE5OTA4ODQzfQ.Wi6wzArP79mFj3XEzSendOfWHJc1mNuSAlAC1W4zMzI"}
window.$dicts = dicts
window.$waitFor = (target, t = 500) => new Promise(resolve => {
  const interval = setInterval(() => {
    if (target) {
      clearInterval(interval)
      resolve(target)
    }
  }, t)
  if (target) {
    clearInterval(interval)
    resolve(target)
  }
})
window.evenRowBGC = (color = "#09265B") => `transparent;background-image: linear-gradient(-45deg, ${color} 0, ${color} 10%, transparent 10%, transparent 50%,${color} 50%, ${color} 60%, transparent 60%, transparent);background-size: 10px 10px;`

Vue.prototype.$marketBoard = Vue.observable({
  screenId: '5b1849ac-4fc3-451a-844c-3362b47341ef',
  thirdGoods: {},
  search: {"groupCodeList": [], "currentDate": "20240701", "compareDate": "20240630", "hourNum": "18"}
})
Vue.prototype.$multipleStoreBoard = Vue.observable({
  carouselIndex: 0,
  search: {"groupCodeList": [], "hourNum": "", type: "1"}
})
Vue.prototype.$storeBoard = Vue.observable({
  currentDate: "20240705",
  dialog: false,
  aroundStock: [],
  query: {},
  search: {}
})
Vue.component("HlsPlayer", {
  render: (h) => h('div', {style: {width: '100%', height: '100%'}}),
  props: {
    id: {default: ""},
    url: {default: "https://open.ys7.com/v3/openlive/155715496_1_1.m3u8?expire=1747359002&id=712960386311127040&t=c9c6ad362940b1fb4ea7a736cec78980aa9ad1d27d6e3eddf75788c0564e9d7b&ev=100"}
  },
  data() {
    return {
      player: null
    }
  },
  methods: {
    play(url) {
      const {EzuikitFlv} = window
      if (EzuikitFlv && url && this.$el) {
        const {id} = this.$props
        this.$el.id = id
        this.player = new EzuikitFlv({container: id, url, decoder: "/presource/datascreen/js/ezuikit-flv/decoder.js"})
        this.player.play()
        this.$el.onclick = () => this.player.fullScreen()
      }
    }
  },
  watch: {
    url: {
      handler(url, old) {
        if (old) this.player?.destroy()
        this.play(url)
      }
    }
  },
  mounted() {
    this.play(this.url)
  },
  beforeDestroy() {
    this.player?.destroy()
  }
})
Vue.component("scrollTable", {
  props: {
    tableData: {default: () => []},
    columns: {default: () => []},
    config: {default: () => ({})}
  },
  data() {
    return {
      timer: null,
      scroll: null
    }
  },
  render(h) {
    const {config, tableData, columns} = this.$props
    return h('el-table', {
        props: {
          headerCellClassName: 'tableHeader', cellClassName: 'tableCell', stripe: !0, height: '100%',
          ...config, data: tableData,
        }, class: 'scrollTable',
        on: {
          'cell-click': (row, column, cell, event) => {
            this.$emit("click", row, column, cell, event)
          }
        }
      },
      columns.map(col => h("tableColumn", {props: {column: col}}))
    )
  },
  methods: {
    initScroll() {
      const {SimpleBar, $waitFor} = window
      $waitFor(this.$el.querySelector('.el-table__body-wrapper')).then(dom => {
        this.scroll = new SimpleBar(dom)
        dom.addEventListener('mouseover', this.stopAutoScroll)
        // dom.addEventListener('mouseout', this.autoScroll)
        // this.scroll.refresh();
      })
    },
    autoScroll() {
      if (this.timer) clearInterval(this.timer)
      this.$el.querySelector('.simplebar-vertical').style.display = 'none'
      // this.$el.querySelectorAll('.simplebar-scrollbar').map(e => e.display = 'none')
      this.timer = setInterval(() => {
        const dom = this.$el.querySelector('.simplebar-content-wrapper')
        const max = dom.scrollHeight - dom.clientHeight
        if (dom.scrollTop + 1 >= max) dom.scrollTop = 0
        else dom.scrollTop += 1
      }, 60)
    },
    stopAutoScroll() {
      const {$waitFor} = window
      $waitFor(this.$el.querySelector('.simplebar-vertical')).then(dom => dom.style.display = 'block')
      if (this.timer) clearInterval(this.timer)
    }
  },
  mounted() {
    this.initScroll()
    // this.autoScroll()
  },
  beforeDestroy() {
    this.stopAutoScroll()
    const dom = this.$el.querySelector('.el-table__body-wrapper')
    dom.removeEventListener("mouseover", this.stopAutoScroll)
    // dom.removeEventListener("mouseout", this.autoScroll)
  }
})
Vue.component("tableColumn", {
  props: {
    column: {default: () => ({})}
  },
  render(h) {
    const config = this.$props.column
    let column = h('el-table-column', {
      props: {...config, label: `${config.label}` || "-"}, scopedSlots: {
        default: ({row}) => {
          return config.custom ? h('div', {
              style: {color: row.preSaleNum > row.stockNum ? 'red' : '#fff'}, class: 'pointer'
            }, '周边库存情况') :
            h('span', config.format?.(row) ?? row[config.prop] ?? '')
        }
      }
    })
    if (config.children?.length > 0) {
      column = h('el-table-column', {props: {...config, label: `${config.label}` || "-"}},
        config.children.map(col => h("tableColumn", {props: {column: col}}))
      )
    }
    return column
  },
})
Vue.component("AppSubTitle", {
  props: {
    text: {default: "副标题"}
  },
  data() {
    return {
      pinyinText: ""
    }
  },
  methods: {
    async getPinyin(text) {
      const wait = (t = 500) => new Promise(resolve => setTimeout(resolve, t))
      while (!window.pinyinPro) await wait()
      const {pinyin} = window.pinyinPro
      this.pinyinText = pinyin(text, {toneType: 'none'}).toUpperCase()

    }
  },
  watch: {
    text: {
      immediate: true,
      handler(v) {
        v && this.getPinyin(v)
      }
    }
  },
  render(h) {
    return h('div', {class: 'AppSubTitle'}, [
      this.text,
      h('span', this.pinyinText),
      h('div', {class: 'right'}, this.$slots.right)
    ])
  }
})


export default Promise.all([
  import("./fetch"),
  ...libs.map(url => $loadScript('js', url)),
  ...css.map(url => $loadScript('css', url))
])
