<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="选择店铺"
          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)"
            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;">
              <span>{{vdata.name}}</span>
              <div class="bottom">
                <span>{{ vdata.type | parseGameType}}</span>
                <el-switch
                    v-model="vdata.selected"
                    active-text=""
                    @change="versionSelectedChange(game._id, vdata._id)"
                    inactive-text="">
                </el-switch>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { getGames, IGameData } from '@/api/game'
import Sticky from '@/components/Sticky/index.vue'
import { getShopGameInfo, getShops, saveShopGameInfo } from '@/api/shop'
import { UserModule } from '@/store/modules/user'

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

  get userLevel() {
    return UserModule.level
  }

  async created() {
    await this.getList()
    if (UserModule.level === 1) {
      await this.getRemoteDeptList('')
    } else {
      this.shop = UserModule.department
    }
  }

  @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()
  }

  private 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')
    }
  }
}
</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;
}

.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>
