<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="游戏名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        增加游戏
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="游戏名称" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.gameName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="游戏描述" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.gameDes }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="创建时间" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTimestamp | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.lastTimestamp | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.state | StateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录回调地址" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.loginback }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付回调地址" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.payback }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            Edit
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row)">
            Delete
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 400px; margin-left:20px;">
        <el-form-item label="游戏名称" prop="name">
          <el-input v-model="temp.gameName" />
        </el-form-item>
        <el-form-item label="游戏描述">
          <el-input v-model="temp.gameDes" />
        </el-form-item>
        <el-form-item label="登录地址" prop="loginAdd">
          <el-input v-model="temp.loginAdd" />
        </el-form-item>
        <el-form-item label="回调地址" prop="callbackAdd">
          <el-input v-model="temp.callbackAdd" />
        </el-form-item>
        <el-form-item label="状态" prop="cpMember">
          <el-select v-model="temp.cpMember" class="filter-item" placeholder="Please select">
            <el-option v-for="item in cpMemberList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="CP合作商" prop="cpMember">
          <el-select v-model="temp.cpMember" class="filter-item" placeholder="Please select">
            <el-option v-for="item in cpMemberList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchList, createGame, updateGame, deleteGame } from '@/http/games'

import Pagination from '@/components/Pagination'

const gameState=[
  { key:'1', state_name:'正常'},
  { key:'2', state_name:'失效'}
]

const gameStateKeyValue = gameState.reduce((acc, cur) =>{
  acc[cur.key] = cur.state_name
  return acc
},{})

export default {
  name:'games',
  components: { Pagination },
  
  filters:{
    stateFilter(state){
      return gameStateKeyValue[state];
    }
  },
  data() {
    return {
      listLoading: false,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      gameState:{

      },
      cpMemberList:["AAA", "BBB", "CCC"],
      rules: {
        name: [{ required: true, message: '游戏名称是必需的！', trigger: 'blur' }],
        loginAdd:[{ required: true,message: '登录地址是必需的！', trigger: 'blur' }],
        callbackAdd:[{required:true,message:'回调地址是必需的！', trigger:'blur'}],
        gameState:[{required:true, message:'游戏状态是必需的!', trigger:'blur'}],
        cpMember:[{required:true, message:'合作商是必须的！',trigger:'blur'}],
      },
      downloadLoading: false,
      dialogStatus: '',
      dialogFormVisible: false,
      temp: {
        // id: undefined,
        // importance: 1,
        // remark: '',
        // timestamp: new Date(),
        // title: '',
        // type: '',
        // status: 'published',
        gameName:'',
        gameDes:'',
        loginAdd:'',
        callbackAdd:'',
        cpMember:'',
        gameState:'',
      },
    }
  },
  created(){
    // this.getList()
  },
  methods: {
    getList(){
      this.listLoading = true;
      this.$api.games.fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        setTimeout(()=>{
          this.listLoading = false;
        },1.5 * 1000)
      })
    },
    handleFilter(){
      this.listQuery.page = 1
      this.getList()
    },
    handleDelete(row){
      this.temp = Object.assign({}, row)
      this.$api.games.deleteGame(this.temp).then(()=>{
        for(const v of this.list){
          if(v.name === this.temp.name){
            const index = this.list.indexOf(v);
            this.list.splice(index, 1);
            break;
          }
        }
      })
    },
    handleModifyStatus(row,status){

    },
    resetTemp(){
      this.temp = {
        // id: undefined,
        // importance: 1,
        // remark: '',
        // timestamp: new Date(),
        // title: '',
        // status: 'published',
        // type: '',
        gameName:'',
        gameDes:'',
        loginAdd:'',
        callbackAdd:'',
        cpMember:'',
      }
    },
    handleCreate(){
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(()=>{
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(){
      this.$refs['dataForm'].vallidate((valid) =>{
        if(valid){
         this.$api.games.createGame(this.temp).then(()=>{
            this.list.unshift(this.temp)
            this.dialogFormVisible = false;
            this.$notify({
              title:'成功',
              message:'创建成功',
              type:'success',
              duration:2000
            })
          })
        }
      })
    },
    handleUpdate(row){
      this.temp = Object.assign({}, row);
      this.dialogFormVisible = true;
      this.dialogStatus = 'update';
      this.$nextTick(()=>{
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData(){
      this.$refs['dataForm'].vallidate((valid)=>{
        if(valid){
          const tempData = Object.assign({}, this.temp);
          this.$api.games.updateGame(tempData).then(()=>{
            for(const v of this.list){
              //更新本地的数据
              if(v.name === this.temp.name){
                const index = this.list.indexOf(v)
                this.list.splice(index,1,this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            // this.$notify({
            //   title:'成功',
            //   message:'',
            //   type:'success',
            //   duration:2000
            // })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.filter-container {
  padding-bottom: 10px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }
}
</style>>

