<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.type"
        placeholder="类型"
        style="width: 120px"
        class="filter-item"
        @change="changeTypes"
      >
        <el-option
          v-for="item in gameDataTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon
              :icon="item.value"
              :desc="item.value"
            /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <div class="filter-item">
        <search-room-input
          @success="searchRoomSuccess"
          @fail="searchRoomFail"
          @load="loadSearchRoom"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" label="系统" align="center" width="100">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.history.sysOrigin"
            :desc="scope.row.history.sysOrigin"
          />
        </template>
      </el-table-column>
      <el-table-column label="房间信息" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.roomProfile">
            <avatar :url="scope.row.roomProfile.roomCover" />
            <div
              style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
            >
              <el-link
                v-if="scope.row.roomProfile.roomName"
                @click="queryRoomDetails(scope.row.roomProfile.id)"
              >
                {{ scope.row.roomProfile.roomName }}
              </el-link>
            </div>
          </div>
          <div v-else>{{ scope.row.history.roomId }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" min-width="200">
        <template slot-scope="scope">
          {{ gameStatusName[scope.row.history.gameStatus] || "-" }}、
          {{ gameEventName[scope.row.history.gameStatusEvent] || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="金额(加入/奖金)" align="center" min-width="150">
        <template slot-scope="scope">
          {{ scope.row.history.joinAmount || "-" }}/{{
            scope.row.history.bonus || "-"
          }}
        </template>
      </el-table-column>
      <el-table-column label="情况" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            style="cursor: pointer;"
            @click="clickGamePlayer(scope.row)"
          >玩家:{{ scope.row.history.playerSize || "-" }}</el-button>
          、锁定座位:{{ scope.row.history.lockSeat || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="history.victoryColor"
        label="胜利方"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <div
            :style="{
              background: scope.row.history.victoryColor || 'black',
              width: '50px',
              height: '20px',
              padding: '5px',
              'border-radius': '5px',
              margin: 'auto'
            }"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="history.createTime"
        label="创建时间"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.history.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="listQuery.type === 'HISTORY'"
        prop="history.updateTime"
        label="修改时间"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.history.updateTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column
        prop="history.victoryColor"
        label="操作"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            :disabled="scope.row.history.gameStatus === 'END'"
            @click="clickDismiss(scope.row)"
          >解散</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;line-height: 60px;">
      <el-button
        v-if="!listNoteData && list.length > 0"
        type="text"
        :loading="listLoading"
        @click="clickLoadMore"
      >点击加载更多</el-button>
      <div v-else-if="list.length > 0">已经加载全部</div>
    </div>

    <el-dialog
      title="游戏玩家"
      :visible="visibleGamePlayers"
      :before-close="() => (visibleGamePlayers = false)"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="80%"
    >
      <el-table
        :data="selectedRow.players"
        element-loading-text="Loading"
        fit
        highlight-current-row
        max-height="350px"
      >
        <el-table-column label="头像" align="center" width="150">
          <template slot-scope="scope">
            <avatar
              :url="scope.row.userProfile.userAvatar"
              :gender="scope.row.userProfile.userSex"
            />
            <div
              style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
            >
              <gender
                :gender="scope.row.userProfile.userSex"
                :gender-name="scope.row.userProfile.userSexName"
                :desc="scope.row.userProfile.account"
              />
              ({{ scope.row.userProfile.accountStatusName }})
            </div>
          </template>
        </el-table-column>
        <el-table-column label="昵称" align="center">
          <template slot-scope="scope">
            <div
              style="width:100%;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
            >
              <el-link
                @click="queryUserDetails(scope.row.userProfile.id)"
              ><a :title="scope.row.userProfile.userNickname">
                {{ scope.row.userProfile.userNickname }}
              </a></el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="棋盘" align="center">
          <template slot-scope="scope">
            <div
              :style="{
                background: scope.row.players.checkerboardColor || 'black',
                width: '50px',
                height: '20px',
                padding: '5px',
                'border-radius': '5px',
                margin: 'auto'
              }"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="players.rankingIndex"
          label="名次"
          align="center"
        />
        <el-table-column prop="players.initiator" label="房主" align="center">
          <template slot-scope="scope">
            {{ scope.row.players.initiator ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="players.consumeJoinAmount"
          label="消费"
          align="center"
        />
        <el-table-column
          prop="players.createTime"
          label="创建时间"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.players.createTime | dateFormat }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <user-deatils-drawer
      v-if="userDeatilsDrawerVisible"
      :user-id="thatSelectedUserId"
      @close="userDeatilsDrawerVisible = false"
    />

    <room-deatils-drawer
      v-if="roomDeatilsDrawerVisible"
      :room-id="queryRoomId"
      @close="roomDeatilsDrawerVisible = false"
    />
  </div>
</template>
<script>
import { flowLudoGame, dismissLudoGame } from '@/api/game'
import { mapGetters } from 'vuex'
import RoomDeatilsDrawer from '@/components/data/RoomDeatilsDrawer'

export default {
  name: 'GameLudo',
  components: { RoomDeatilsDrawer },
  data() {
    return {
      userDeatilsDrawerVisible: false,
      gameDataTypes: [
        { label: '运行', value: 'RUN' },
        { label: '历史', value: 'HISTORY' }
      ],
      searchDisabled: false,
      list: [],
      listQuery: {
        limit: 20,
        roomId: '',
        sysOrigin: '',
        lastId: '',
        type: 'RUN'
      },
      listLoading: true,
      gameStatusName: {
        WAIT: '等待开始',
        PROGRESS: '进行中',
        END: '已结束'
      },
      gameEventName: {
        NONE: '无',
        TIMEOUT_DISBAND: '游戏未开始超时,解散',
        DISCONNECTED_DISBAND: '游戏已开始,全部掉线后,解散',
        OTHER__DISBAND: '其他,不在预计状态内',
        NORMAL_SETTLEMENT: '正常结算',
        BACK_DISBAND: '后台解散'
      },
      roomDeatilsDrawerVisible: false,
      queryRoomId: '',
      listNoteData: false,
      selectedRow: {},
      thatSelectedUserId: '',
      visibleGamePlayers: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
        that.listQuery.lastId = ''
        that.listNoteData = false
      }
      that.listLoading = true
      flowLudoGame(that.listQuery).then(res => {
        that.listLoading = false
        const { body } = res
        const list = body || []
        if (list.length > 0) {
          that.list = that.list.concat(list)
          that.listQuery.lastId = that.list[that.list.length - 1].history.id
          return
        }
        that.listNoteData = true
      })
    },
    handleSearch() {
      this.renderData(true)
    },
    queryUserDetails(id) {
      this.userDeatilsDrawerVisible = true
      this.thatSelectedUserId = id
    },
    loadSearchRoom() {
      this.searchDisabled = true
    },
    searchRoomSuccess(res) {
      this.searchDisabled = false
      if (!res) {
        return
      }
      this.listQuery.roomId = res.id
    },
    searchRoomFail() {
      this.listQuery.roomId = ''
      this.searchDisabled = false
    },
    queryRoomDetails(roomId) {
      this.roomDeatilsDrawerVisible = true
      this.queryRoomId = roomId
    },
    clickDismiss(row) {
      const that = this
      if (row.history.gameStatus === 'END') {
        return
      }
      that
        .$confirm('后台解散游戏将没有胜利者, 是否确定解散?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          dismissLudoGame(row.history.roomId)
            .then(res => {
              that.$opsMessage.success()
              row.history.gameStatus = 'END'
              row.history.gameStatusEvent = 'BACK_DISBAND'
              that.list = that.list.filter(
                item => item.history.id !== row.history.id
              )
            })
            .catch(er => {
              that.$opsMessage.fail()
            })
        })
        .catch(() => {})
    },
    changeTypes() {
      this.renderData(true)
    },
    clickLoadMore() {
      if (this.listNoteData || this.listLoading) {
        return
      }
      this.renderData()
    },
    clickGamePlayer(row) {
      this.visibleGamePlayers = true
      this.selectedRow = row
    }
  }
}
</script>
<style scoped lang="scss">
.store-table-expand {
  font-size: 0;
  label {
    width: 90px;
    color: #99a9bf;
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 50%;
    }
  }
}
</style>
