<template>
  <div class="market">
    <a-menu mode="vertical" v-model="selectedMenu" @click="getPlugins">
      <a-menu-item v-for="item in menu" :key="item.id" :value="item.path">
        <a-icon :type="formatMenu(item.name).icon" />
        {{ formatMenu(item.name).name }}
      </a-menu-item>
    </a-menu>
    <div class="market-content">
      <a-carousel v-if="bannerList && !!bannerList.length" arrows>
        <div
          slot="prevArrow"
          slot-scope="props"
          class="custom-slick-arrow"
          style="left: 10px; zindex: 1"
        >
          <a-icon type="left-circle" />
        </div>
        <div
          slot="nextArrow"
          slot-scope="props"
          class="custom-slick-arrow"
          style="right: 10px"
        >
          <a-icon type="right-circle" />
        </div>
        <div v-for="banner in bannerList">
          <img @click="jumpTo(banner.link)" width="100%" :src="banner.src" />
        </div>
      </a-carousel>
      <a-divider v-if="bannerList && !!bannerList.length"></a-divider>
      <h2>插件</h2>
      <a-list
        item-layout="horizontal"
        style="width: 100%"
        :grid="{ gutter: 16, column: 2 }"
        :data-source="pluginList"
      >
        <a-list-item slot="renderItem" slot-scope="item, index">
          <a-button
            v-if="showButton(item) === 'download'"
            :loading="loading[index]"
            type="link"
            slot="actions"
            @click="download(index, item)"
          >
            <a-icon
              v-show="!loading[index]"
              style="font-size: 20px"
              type="cloud-download"
            />
          </a-button>
          <a-button
            v-if="showButton(item) === 'update'"
            :loading="loading[index]"
            type="link"
            slot="actions"
            @click="update(index, item)"
          >
            <a-icon
              v-show="!loading[index]"
              style="font-size: 20px; color: #409eff"
              type="sync"
            />
          </a-button>

          <a-list-item-meta
            @click="showPannel(item, index)"
            :description="item.description"
          >
            <div slot="title">{{ item.pluginName }}</div>
            <a-avatar slot="avatar" :src="item.logo" />
          </a-list-item-meta>
        </a-list-item>
      </a-list>
    </div>
    <a-drawer
      placement="right"
      :visible="show"
      @close="show = false"
      width="100%"
    >
      <div class="plugin-market-desc" slot="title">
        <img width="80" :src="currentSelect.logo" />
        <div class="desc">
          <h4>{{ currentSelect.pluginName }}</h4>
          <div class="info">
            <div class="actor">
              开发者：{{ currentSelect.author }}
              <a-button
                v-if="showButton(currentSelect) === 'download'"
                :loading="loading[currentSelect.index]"
                @click="download(currentSelect.index, currentSelect)"
                icon="cloud-download"
                type="primary"
              >
                获取
              </a-button>
              <a-button
                v-if="showButton(currentSelect) === 'update'"
                :loading="loading[currentSelect.index]"
                @click="update(currentSelect.index, currentSelect)"
                icon="sync"
                type="primary"
              >
                更新
              </a-button>
            </div>
            <div>{{ currentSelect.description }}</div>
          </div>
        </div>
      </div>
      <div class="market-plugin-detail" v-html="readme"></div>
    </a-drawer>
  </div>
</template>

<script>
import api from "../../../assets/api";
import { mapActions, mapMutations, mapState } from "vuex";
import marked from "marked";
import { shell } from "electron";
import axios from "axios";
import { isMdFile } from "../../../assets/common/utils";
const rendererMD = new marked.Renderer();

export default {
  data() {
    return {
      menu: [],
      pluginList: [],
      loading: {},
      bannerList: [],
      show: false,
      selectedMenu: [],
      currentSelect: {}
    };
  },
  async created() {
    this.getMenu();
    // this.bannerList = bannerRes.result;
  },
  methods: {
    getMenu() {
      api.getMenu().then(async ({ data: res }) => {
        if (!res.length) return;
        this.menu = res;
        // console.log(res);

        const firstItem = res[0];
        this.selectedMenu = [firstItem.id];
        this.getPlugins({ item: { value: firstItem.path } });
      });
    },
    formatMenu(name) {
      if (!name) return "";
      switch (name) {
        case "entertainment":
          return {
            name: "游戏娱乐",
            icon: "build"
          };
        case "software":
          return {
            name: "应用软件",
            icon: "calculator"
          };
        case "tools":
          return {
            name: "开发工具",
            icon: "tool"
          };
      }
    },
    getPlugins({ item }) {
      console.log(item);
      const path = encodeURIComponent(item.value);
      api.getPlugins(path).then(async ({ data: res }) => {
        this.pluginList = [];
        res.forEach(async plugin => {
          const pluginItem = await this.getPluginDetail(
            encodeURIComponent(plugin.path)
          );
          this.pluginList.push(pluginItem);
        });
      });
    },
    async getPluginDetail(path) {
      const { data: plugin } = await api.getPluginDetail(path);
      plugin.path = path;
      if (plugin.detail && isMdFile(plugin.detail)) {
        const { readme } = await api.getReadme(plugin);
        plugin.readme = readme;
      } else {
        plugin.readme = plugin.detail;
      }
      plugin.logo = api.getLogo(plugin);
      plugin.downloadUrl = api.getDownloadUrl(plugin.path);
      console.log(plugin.downloadUrl);

      return plugin;
    },
    async download(index, item) {
      if (this.loading[index]) return;
      this.$set(this.loading, index, true);
      try {
        await this.downloadPlugin(item);
      } catch (e) {
        this.$message.error(e);
      }
      this.$set(this.loading, index, false);
    },
    async update(index, item) {
      if (this.loading[index]) return;
      this.$set(this.loading, index, true);
      try {
        await this.updatePlugin(item);
        this.checkUpdatePlugins();
      } catch (e) {
        this.$message.error(e);
      }
      this.$set(this.loading, index, false);
    },
    showButton(item) {
      const plugin = this.devPlugins.find(
        plugin => plugin.name === item.name && plugin.type === "prod"
      );
      if (!plugin) return "download";
      if (plugin && plugin.version !== item.version) {
        this.changeUpdateBadge(true);
        return "update";
      }
      return null;
    },
    checkUpdatePlugins() {
      const list = this.pluginList;
      const update = this.devPlugins.some(plugin => {
        return (
          plugin.type === "prod" &&
          list.find(item => {
            item.name === plugin.name && item.version !== plugin.version;
          })
        );
      });
      this.changeUpdateBadge(update);
    },
    showPannel(item, index) {
      this.show = true;
      this.currentSelect = item;
      this.currentSelect.index = index;
    },
    jumpTo(link) {
      if (link) {
        shell.openExternal(link);
      }
    },
    ...mapActions("main", ["downloadPlugin", "updatePlugin"]),
    ...mapMutations("main", ["changeUpdateBadge"])
  },
  computed: {
    ...mapState("main", ["devPlugins"]),
    readme() {
      marked.setOptions({
        renderer: rendererMD,
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false
      });
      try {
        console.log(123, this.currentSelect);

        return marked(this.currentSelect.readme);
      } catch (e) {
        return "暂无描述信息";
      }
    }
  }
};
</script>

<style lang="less">
.market-plugin-detail {
  img {
    width: 100%;
  }
  height: 430px;
  overflow: auto;
  &::-webkit-scrollbar {
    width: 0;
  }
}
.plugin-market-desc {
  display: flex;
  img {
    margin-right: 20px;
  }
  .desc {
    flex: 1;
  }
  .info {
    font-size: 12px;
    color: #999;
    font-weight: normal;
    padding-right: 40px;
  }
  .actor {
    flex: 1;
    display: flex;
    justify-content: space-between;
  }
}
.market {
  height: calc(~"100vh - 110px");
  background: #fff;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  .ant-menu {
    width: 220px;
  }
  .market-content {
    flex: 1;
    padding: 20px;
    box-sizing: border-box;
  }
  .ant-carousel .slick-slide {
    text-align: center;
    height: 235px;
    line-height: 160px;
    background: #364d79;
    overflow: hidden;
  }

  .ant-carousel .custom-slick-arrow {
    width: 25px;
    height: 25px;
    font-size: 25px;
    color: #fff;
    background-color: rgba(31, 45, 61, 0.11);
    opacity: 0.3;
  }
  .ant-carousel .custom-slick-arrow:before {
    display: none;
  }
  .ant-carousel .custom-slick-arrow:hover {
    opacity: 0.5;
  }

  .ant-carousel .slick-slide h3 {
    color: #fff;
  }
  .ant-list-item {
    display: flex !important;
    align-items: center;
    justify-content: space-between;
  }
  .ant-list-item-meta {
    align-items: center;
  }
  .ant-list-item-meta-description {
    width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .ant-list-item-action {
    margin-left: 0;
  }
}
</style>
