<template>
  <div  class="app-container">
    <div v-show="visible.thirdLayer">
      <div  class="app-container">
          <div class="block">
              <!-- <span class="demonstration">時間篩選</span> -->
              <el-date-picker
              v-model="date"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="開始日期"
              end-placeholder="结束日期"
              align="right">
              </el-date-picker>
              <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜尋</el-button>
          </div>
      </div>
      <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column :label="data.thirdLayer.name" align="center">
          <el-table-column label="時間" align="center">
            <template slot-scope="scope" prop="createdAt">
              <span>{{moment(scope.row.createdAt)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="事件" align="center">
            <template slot-scope="scope">
              {{scope.row.type}}
            </template>
          </el-table-column>
          <el-table-column label="金額" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.amount)">{{scope.row.amount}}</span>
            </template>
          </el-table-column>
          <el-table-column label="錢包" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.wallet}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="250">
            <template slot-scope="scope">
                <el-button v-show="scope.row.type==='遊戲'" type="primary" size="mini" icon="el-icon-tickets" @click="handlePersonDetail(scope.row)">個人明細</el-button>  
                <router-link to="/room/index/gambleMember/index/gameHistory/index/detail/index">
                  <el-button v-show="scope.row.type==='遊戲'" type="primary" size="mini" icon="el-icon-tickets" @click="handleGameDetail(scope.row)">此場明細</el-button>                
                </router-link>
            </template>
          </el-table-column>
        </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="個人詳細資料" :visible.sync="dialogFormVisible" width="75%" center>
        <el-table :data="dialogList" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
          style="width: 100%" :summary-method="getSummaries" show-summary>
          <el-table-column label="關" align="center">
            <template slot-scope="scope">
              {{scope.row.round}}
            </template>
          </el-table-column>
          <el-table-column label="門" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.door}}</span>
            </template>
          </el-table-column>
          <el-table-column label="押注" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.wager}}</span>
            </template>
          </el-table-column>
          <el-table-column label="輸贏" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.earned)">{{scope.row.earned}}</span>
            </template>
          </el-table-column>
          <el-table-column label="抽水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.serviceFees}}</span>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" type="danger">關 閉</el-button>
        </div>
      </el-dialog>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>

import { mapActions, mapGetters } from 'vuex'
import { fetchGameHistory, fetchChipsHistory, fetchPersonGameDetail, fetchPunishment } from '@/api/gambleMember'
import { fetchCurrentChips } from '@/api/gambleGameBucket'
import waves from '@/directive/waves' // 水波纹指令
import moment from 'moment-timezone'
import config from '../../../../config' 
import _ from 'lodash'

export default {
  directives: {
    waves
  },
  data() {
    return {
      chipLogList: [],
      gameRecordList: [],   
      list: [],   
      dialogList: null,
      total: null,
      listLoading: true,
      listQuery: { 
        page: 1, 
        limit: 9999999999, 
        startAt: null, 
        endAt: null 
      }, 
      tempCurrentChips: [],
      pickerOptions: {
        shortcuts: [{
          text: '本週',
          onClick(picker) {
            const end = moment().day('sunday').hour(12).minute(0).second(0).day(7).hour(11).minute(59).second(59)
            const start = moment().day('sunday').hour(12).minute(0).second(0).subtract(1, 'weeks').day(7).hour(16).minute(0).second(0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '上週',
          onClick(picker) {
            const end = moment().day('sunday').hour(12).minute(0).second(0).subtract(1, 'weeks').day(7).hour(11).minute(59).second(59)
            const startAt = moment().day('sunday').hour(12).minute(0).second(0).subtract(2, 'weeks').day(7).hour(16).minute(0).second(0)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      date: null,
      dialogFormVisible: false

    }
  },
  created() {
    this.date = this.p_date
    this.SetVisible(3)
    this.getList()
  },
  computed: {
    ...mapGetters([
      'visible',
      'data',
      // 'query',
      // 'p_date'
    ])
  },
  methods: {
    ...mapActions([
      'SetVisible',
      'SetData',
      // 'SetQuery',
      // 'SetDate'
    ]),
    async getList() {
      this.listLoading = true
      //this.list = []
      await fetchGameHistory(this.data.thirdLayer, this.listQuery).then(response => {
        this.list = []
        this.chipLogList = response.data
        this.tempCurrentChips = []
        this.chipLogList.map((item) => {
          fetchCurrentChips(item['GambleGame-Bucket'], this.data.thirdLayer).then(response => {
            item.earned = _.sumBy(response.data, item => {
              return item.earned - item.serviceFees - item.wagerServiceFees - item.FixedServiceFees
            })
            let round = _.groupBy(response.data, 'round')
            round = Object.values(round)
            item.currentChips = _.sumBy(round[round.length-1], 'chips') + round[round.length-1][0].currentChips
            this.list.unshift({
              id: item.game,
              createdAt: item['GambleGame-Bucket'].createdAt,
              type: '遊戲',
              amount: item.earned,
              wallet: item.currentChips
            })
             
          })
        })
      })
      await fetchChipsHistory(this.data.thirdLayer, this.listQuery).then(response => {
        this.gameRecordList = response.data
        this.gameRecordList.map((item) => {
          if(item.type === config.const.GambleMemberChipsLog.type.deposit) item.type =  '上 / 下 分';
          if(item.type === config.const.GambleMemberChipsLog.type.reward) item.type =  '獎勵 / 懲罰';
          if(item.type === config.const.GambleMemberChipsLog.type.reset) item.type =  '歸零';
          this.list.unshift({
            id: item.id,
            createdAt: item.createdAt,
            type: item.type,
            amount: item.chips,
            wallet: item.totalChips
          })
        })
      })
      await fetchPunishment(this.data.thirdLayer).then(response => {
          response.data.map(item => {
            this.list.unshift({
              id: item.id,
              createdAt: item.createdAt,
              type: item.rule,
              amount: (item.chips)*(-1),
              wallet: ` `
            })
          })
      })
      this.list.sort(function compare(a, b) {
        const dateA = new Date(a.createdAt);
        const dateB = new Date(b.createdAt);
        return  dateB - dateA;
      });
      this.total = this.list.length
      this.listLoading = false
    },
    handlePersonDetail(row) {
      this.listLoading = true
      this.dialogFormVisible = true
      fetchPersonGameDetail(this.data.thirdLayer.id, row.id).then(response => {
        console.log('params', this.data.thirdLayer.id, row.id)
        console.log('rows', response.data.rows)
        this.dialogList = response.data.rows.map(row => {
          row.serviceFees = row.serviceFees + row.wagerServiceFees + row.FixedServiceFees
        })
        this.listLoading = false
      })
    },
    handleGameDetail(row) {
      console.log('Game detail', row)
      const temp = Object.assign({}, row) // copy obj
      this.SetVisible(4)
      this.SetData({layer:4, data: temp})
    },
    handleFilter() {
      // this.listQuery.page = 1 
      if (this.date) { 
        this.listQuery.startAt = moment.utc(this.date[0]).format() 
        this.listQuery.endAt = moment.utc(this.date[1]).format()  
      } else {
        this.listQuery.startAt = null 
        this.listQuery.endAt = null 
      }
      this.getList()
    },
    // handleSizeChange(val) {
    //   this.listQuery.limit = val
    //   this.getList()
    // },
    // handleCurrentChange(val) {
    //   this.listQuery.page = val
    //   this.getList()
    // },
    moment(time) {
      return moment(time).tz('Asia/Taipei').format('YYYY-MM-DD HH:mm:ss')
    },
    getSummaries() {
      const sums = []
      let totalWager = 0
      let totalEarned = 0
      let totalServiceFees = 0
      if (this.dialogList) {
        this.dialogList.map((memberRecord) => {
          totalWager += memberRecord.wager
          totalEarned += memberRecord.earned
          totalServiceFees += memberRecord.serviceFees
        })
      }
      sums[0] = '合計'
      sums[1] = 'N/A'
      sums[2] = totalWager
      sums[3] = totalEarned
      sums[4] = totalServiceFees
      return sums
    },
    moneyColor(money) {
      return money >= 0 ? { color: '#67C23A' } : { color: '#FA5555' }
    }
  },
  destroyed() {
    this.SetVisible(2)
  },
  // time 持久化
  // watch: {
  //   'date': function(val) {
  //    this.SetDate(val)
  //   }
  // }
}
</script>
