<!-- TODO select -->
<template>
<div class="app-container calendar-list-container">
  <div  v-show="visible">
    <div class="app-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名稱" v-model="listQuery.name">
      </el-input>
      <el-select clearable @change='handleFilter' style="width: 120px" class="filter-item" v-model="listQuery.chipsSort" placeholder="點數">
        <el-option v-for="item in chipsSortOptions" :key="item.label" :label="item.label" :value="item.key">
        </el-option>
      </el-select>
      <el-select clearable @change='handleFilter' style="width: 120px" class="filter-item" v-model="listQuery.updatedSort" placeholder="更新時間">
        <el-option v-for="item in updatedSortOptions" :key="item.label" :label="item.label" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜尋</el-button>
      <el-button class="filter-item" @click="handleCreate" type="primary" icon="el-icon-edit">創建</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" label='ID' >
        <template slot-scope="scope">
          {{scope.row.id}}
        </template>
      </el-table-column>
      <el-table-column label="名稱" align="center">
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column label="點數" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.chips}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="350">
        <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleDeposit(scope.row)">上下分</el-button>
            <router-link to="/gambleMember/index/chipsHistory">
              <el-button type="primary" size="mini" icon="el-icon-tickets" @click="handleLog(scope.row)">上下分紀錄</el-button>            
            </router-link>
            <router-link to="/gambleMember/index/gameHistory">
              <el-button type="primary" size="mini" icon="el-icon-tickets" @click="handlePage(scope.row)">歷史查詢</el-button>
            </router-link>       
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item v-if="dialogStatus=='deposit'" label="ID" prop="id">
          <el-input v-model="temp.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="名稱" prop="name">
          <el-input v-if="dialogStatus=='deposit'" v-model="temp.name" :disabled="true"></el-input>
          <el-input v-if="dialogStatus=='create'" v-model="temp.name"></el-input>          
        </el-form-item>
        <el-form-item label="點數" prop="chips">
          <el-input v-if="dialogStatus=='deposit'" v-model="temp.chips" :disabled="true"></el-input>
          <el-input v-if="dialogStatus=='create'" v-model="temp.chips"></el-input>          
        </el-form-item>
        <el-form-item v-if="dialogStatus=='deposit'" label="上下分" prop="depositChips">
          <el-input placeholder="請輸入上下分" v-model="temp.depositChips">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">確 定</el-button>
        <el-button v-if="dialogStatus=='deposit'" type="primary" @click="depositChips">確 定</el-button>
      </div>
    </el-dialog>
  </div>
    <router-view :member="member"></router-view>
  </div>
</template>

<script>

import { mapGetters, mapActions } from 'vuex'
import { fetchList, updateChips, createGambleMember } from '@/api/gambleMember'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'gambleMemberTable',
  directives: {
    waves
  },
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        chipsSort: '',
        updatedSort: ''
      },
      temp: {
        id: '',
        name: '',
        chips: '',
        depositChips: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        deposit: '儲值',
        create: '新增'
      },
      member: {},
      chipsSortOptions: [{ label: '多 -> 少', key: 'DESC' }, { label: '少 -> 多', key: 'ASC' }],
      updatedSortOptions: [{ label: '新 -> 舊', key: 'DESC' }, { label: '舊 -> 新', key: 'ASC' }],
      rules: {
        depositChips: [{ pattern: /^-?\d+$/, required: true, message: '請輸入整數', trigger: 'change' }],
        chips: [{ pattern: /^(0|[1-9][0-9]*)$/, required: true, message: '請輸入整數', trigger: 'change' }],
        name: [{ type: 'string', required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  created() {
    this.SetVisible(true)
    this.getList()
  },
  computed: {
    ...mapGetters([
      'visible'
    ])
  },
  methods: {
    ...mapActions([
      'SetVisible'
    ]),
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.count
        this.listLoading = false
      })
    },
    handleDeposit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'deposit'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    depositChips() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateChips(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                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
            })
            this.getList()
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        chips: '',
        depositChips: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createGambleMember(this.temp).then((response) => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '創建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handlePage(row) {
      const temp = Object.assign({}, row) // copy obj
      this.SetVisible(false)
      this.member = temp
    },
    handleLog(row) {
      const temp = Object.assign({}, row) // copy obj
      this.SetVisible(false)
      this.member = temp
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    }
  }
}
</script>
