<template>
  <div class="app-container">
    <sticky
        :z-index="10"
        class-name="sub-navbar"
    >
      <el-button-group >
        <el-button
            icon="el-icon-close"
            @click="onCancel"
        >取消</el-button>
        <el-button
            type="success"
            icon="el-icon-check"
            @click="saveVal"
            v-permission="['shop:game_setting']"
        >保存</el-button>
      </el-button-group>
    </sticky>
    <el-row>
      <el-select
          v-model="shop"
          :placeholder="'选择'+$t('main.shop')"
          name="shop"
          required
          class="w100"
          v-if="userLevel === 1"
      >
        <el-option
            v-for="item in allDepts"
            :key="item._id"
            :label="item.name"
            :value="item._id"
        />
      </el-select>
    </el-row>
    <div class="one-block" v-for="(game) in list" :key="game._id">
      <el-row>
        <el-switch
            v-model="game.selected"
            :active-text="game.name"
            @change="gameSelectedChange(game._id)"
            :disabled = "noShop"
            inactive-text="">
        </el-switch>
      </el-row>
      <el-divider content-position="left"></el-divider>
      <el-row style="display: flex; flex-wrap: wrap;">
        <el-col :span="4" v-for="(vdata, index) in game.versions" :key="vdata._id" :offset="index %4 === 0 ? 0 : 2" style="margin-bottom: 20px;">
          <el-card :body-style="{padding: '0px'}">
            <img :src="vdata.image" class="image" :alt="vdata.name">
            <div style="padding: 14px;">
              <div class="sub-bottom">
                <span>{{vdata.name}}</span>
                <span>
                  <router-link
                      :to="`/shop/theme_edit/${shop}/${game._id}/${vdata._id}`"
                      class="link-type"
                      v-if="!noShop"
                      >
                      自定义
                  </router-link>
                </span>
              </div>
              <div class="bottom">
                <el-image
                    v-if="!noShop"
                    style="width: 40px; height: 40px"
                    :src="vdata.type === 1 ? 'img/icons/wqr.png' : 'img/icons/preview.png'"
                    @click="showPreview(vdata)"
                    >
                </el-image>
                <span
                    v-if="vdata.type === 1 && !noShop"
                    @click="showPreview(vdata)"
                >
                 查看小程序码
                </span>
                <span
                    v-if="vdata.type === 0  && !noShop"
                >
                  <a :href="vdata.url" target="_blank">预览游戏 </a>
                </span>
                <el-switch
                    v-model="vdata.selected"
                    active-text=""
                    @change="versionSelectedChange(game._id, vdata._id)"
                    :disabled = "noShop"
                    inactive-text="">
                </el-switch>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-image-viewer
        v-if="showViewer"
        :on-close="closeViewer"
        :url-list="[qrUrl]" />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { getGames, IGameData, IGameVersion } from '@/api/game'
import Sticky from '@/components/Sticky/index.vue'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer.vue'

import {
  getShopGameInfo,
  getShopGameQr,
  getShops,
  saveShopGameInfo
} from '@/api/shop'
import { UserModule } from '@/store/modules/user'
import { EVENT_GAME_UPDATE, EVENT_SHOP_UPDATE, EventBus } from '@/utils/event-bus'

@Component({
  name: 'GameSetting',
  components: {
    Sticky,
    ElImageViewer
  },
  filters: {
    parseGameType: (type: number) => {
      return type === 1 ? '微信小游戏' : '网页版'
    }
  }
})
export default class extends Vue {
  private total = 0
  private list: IGameData[] = []
  private listLoading = true
  private shop = ''
  private allDepts = []
  private gameid = ''
  private versionid = ''
  private qrUrl = ''
  private showViewer = false
  private listQuery = {
    page: 1,
    limit: 20,
    key: '',
    hasVersion: 1
  }

  get userLevel() {
    return UserModule.level
  }

  get noShop() {
    return !this.shop
  }

  async created() {
    await this.getList()
    if (UserModule.level === 1) {
      await this.getRemoteDeptList('')
      EventBus.$on(EVENT_SHOP_UPDATE, () => {
        this.getRemoteDeptList()
      })
    } else {
      this.shop = UserModule.department
    }
    EventBus.$on(EVENT_GAME_UPDATE, () => {
      this.getList()
    })
  }

  beforeDestory() {
    if (UserModule.level === 1) {
      EventBus.$off(EVENT_SHOP_UPDATE)
    }
    EventBus.$off(EVENT_GAME_UPDATE)
  }

  @Watch('shop')
  private onShopChange() {
    if (this.shop) {
      this.getShopGameSetting(this.shop)
    }
  }

  private async getList() {
    this.listLoading = true
    const { data } = await getGames(this.listQuery)
    this.listLoading = false
    this.list = data.records
    this.total = data.total
  }

  private async getShopGameSetting(shopid: string) {
    const { data } = await getShopGameInfo({ shopid })
    console.log(data)
    this.gameid = data.gameid
    this.versionid = data.versionid
    this.updateGameSelected()
    for (let i = 0; i < this.list.length; i++) {
      const game = this.list[i]
      for (const v of game.versions) {
        if (v.type === 1) {
          v.qr = await this.getGameQr(this.shop, game._id!, v._id!)
        }
      }
      Vue.set(this.list, i, game)
    }
  }

  private async getGameQr(shop: string, gameId: string, version: string) {
    const params = { shop, gameId, version }
    const { data } = await getShopGameQr(params)
    return data.url
  }

  private async updateGameSelected() {
    if (this.list.length === 0) {
      return
    }
    if (!this.gameid) {
      this.gameid = this.list[0]._id!
    }
    for (const game of this.list) {
      if (game._id === this.gameid) {
        if (!game.versions.find(o => o._id === this.versionid)) {
          this.versionid = game.versions[0]._id!
        }
        break
      }
    }
    for (let i = 0; i < this.list.length; i++) {
      const game = this.list[i]
      game.selected = game._id === this.gameid
      for (const v of game.versions) {
        v.selected = v._id === this.versionid
      }
      Vue.set(this.list, i, game)
    }
  }

  private async getRemoteDeptList(name?: string) {
    if (UserModule.level > 1) {
      return
    }
    const { data } = await getShops({ key: name })
    if (!data.records) return
    this.allDepts = data.records
  }

  private gameSelectedChange(gameid: string) {
    console.log(gameid)
    this.gameid = gameid
    this.updateGameSelected()
  }

  private versionSelectedChange(gameid: string, versionid: string) {
    console.log(gameid, versionid)
    this.gameid = gameid
    this.versionid = versionid
    this.updateGameSelected()
  }

  private async onCancel() {
    try {
      await this.$confirm('确认不保存当前信息?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      this.$store.dispatch('delView', this.$route)
      this.$router.go(-1)
    } catch (err) {

    }
  }

  private async saveVal() {
    if (!this.shop || !this.gameid || !this.versionid) {
      this.$message({
        message: '请先选择一个游戏',
        type: 'warning'
      })
      return
    }
    try {
      const data = {
        shopid: this.shop,
        gameid: this.gameid,
        versionid: this.versionid
      }
      await saveShopGameInfo(data)
      this.$notify({
        title: 'Success',
        message: '更新游戏配置成功',
        type: 'success',
        duration: 2000
      })
    } catch (err) {
      console.log('save shop gamesetting error')
    }
  }

  private showPreview(data: IGameVersion) {
    if (data.type === 1 && data.qr) {
      this.qrUrl = data.qr!
      this.showViewer = true
    } else if (data.url) {
      window.open(data.url, '_blank')
    }
  }

  private closeViewer() {
    this.qrUrl = ''
    this.showViewer = false
  }
}
</script>

<style lang="scss" scoped>
.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bottom span{
  font-size: 13px;
  color: #999;
}
.sub-bottom {
  display: flex;
  justify-content: space-between;
}

.button {
  padding: 0;
  min-height: auto;
  float: right;
}

.image {
  width: 100%;
  display: block;
}
.one-block{
  border: 1px solid #ebebeb;
  border-radius: 3px;
  transition: .2s;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

</style>
