<template>
<div class="app-container calendar-list-container">
  <div class="app-container">
     <div class="block">
      <el-row :gutter="20">
        <el-col :span="6">
          <span class="demonstration">關數</span>
          <el-select @change='handleFilter' style="width: 120px" class="filter-item" v-model="query.secondLayer.round" placeholder="關">
          <el-option v-for="item in roundOptions" :key="item.label" :label="item.label" :value="item.key">
          </el-option>
        </el-select>
        </el-col >
        <el-col :offset="10" :span="8">
            <span class="demonstration">時間 : {{moment(this.data.secondLayer.createdAt)}}</span>
        </el-col>
      </el-row>
    </div>
  </div>
    <el-table header-row-class-name="init" :data="bookie" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
      style="width: 100%">      
      <el-table-column label="本期開獎" lable-className="title" align="center">   
        <el-table-column label="莊家結果" align="center">            
                  
          <el-table-column label="莊家" prop="MemberRecord.GambleMember.name"></el-table-column>
          <el-table-column label="點數">
            <template slot-scope="scope">
              <span>{{`${scope.row.DealingRecord.point1} | ${scope.row.DealingRecord.point2} / ${point(scope.row.DealingRecord)}`}}</span>
            </template>
          </el-table-column>
          <el-table-column label="上莊分數" prop="bidChips"></el-table-column>      
          <el-table-column label="莊輸贏">
            <template slot-scope="scope">
              <div :style="moneyColor(scope.row.MemberRecord.earned)">{{scope.row.MemberRecord.earned}}</div>
            </template>
          </el-table-column>      
          <el-table-column label="抽水" prop="MemberRecord.serviceFees"></el-table-column>
          <el-table-column prop="ass" label="服務費">
          </el-table-column>     
        </el-table-column>             
      </el-table-column>                   
    </el-table>
    <el-table :header-cell-style="initDoor" :data="dealing" v-loading.body="listLoading" :summary-method="getSummaries" show-summary  element-loading-text="Loading" border fit highlight-current-row
      style="width: 100%">
      <el-table-column label="各門結果" align="center"> 
        <el-table-column label="名稱">
          <template slot-scope="scope">
            <span>{{scope.$index === 0 ?"點數":"門主"}}</span>
          </template>
        </el-table-column>   
        <el-table-column label="第一門">
          <template slot-scope="scope">
            <span>{{doorTableSwitch(scope.$index, 0)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="第二門">
          <template slot-scope="scope">
            <span>{{doorTableSwitch(scope.$index, 1)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="第三門">
          <template slot-scope="scope">
            <span>{{doorTableSwitch(scope.$index, 2)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="第四門">
          <template slot-scope="scope">
            <span>{{doorTableSwitch(scope.$index, 3)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="第五門">
          <template slot-scope="scope">
            <span>{{doorTableSwitch(scope.$index, 4)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="第六門">
          <template slot-scope="scope">
            <span>{{doorTableSwitch(scope.$index, 5)}}</span>
          </template>
        </el-table-column>
      </el-table-column>      
    </el-table>
    <el-table :data="bookie" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
      style="width: 100%">      
      <el-table-column label="莊家紀錄" align="center">            
        <el-table-column label="莊家" prop="MemberRecord.GambleMember.name"></el-table-column>
        <el-table-column label="點數">
          <template slot-scope="scope">
            <span>{{`${scope.row.DealingRecord.point1} | ${scope.row.DealingRecord.point2} / ${point(scope.row.DealingRecord)}`}}</span>
          </template>
        </el-table-column>
        <el-table-column label="上莊分數" prop="bidChips"></el-table-column>      
        <el-table-column label="莊輸贏">
          <template slot-scope="scope">
            <div :style="moneyColor(scope.row.MemberRecord.earned)">{{scope.row.MemberRecord.earned}}</div>
          </template>
        </el-table-column>      
        <el-table-column label="抽水" prop="MemberRecord.serviceFees"></el-table-column>
        <el-table-column prop="ass" label="服務費">
        </el-table-column>     
      </el-table-column>                   
    </el-table>
    <el-table :data="detail" :span-method="objectSpanMethod"  v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
      style="width: 100%">
      <el-table-column label="此關結果" align="center">
        <el-table-column prop="MemberRecord.GambleMember.name" label="玩家">
        </el-table-column>
        <!-- <el-table-column prop="MemberRecord.GambleMember.name" label="門主">
        </el-table-column> -->
        <el-table-column  label="押">
          <template slot-scope="scope">
            <span>{{`${scope.row.MemberRecord.door} / ${scope.row.MemberRecord.wager}`}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="DealingRecord.totalPoints" label="點數">
          <template slot-scope="scope">
            <span>{{`${scope.row.DealingRecord.point1} | ${scope.row.DealingRecord.point2} / ${point(scope.row.DealingRecord)}`}}</span>
          </template>
        </el-table-column>
        <el-table-column label="輸贏">
          <template slot-scope="scope">
            <div :style="moneyColor(scope.row.MemberRecord.earned)">{{scope.row.MemberRecord.earned - scope.row.MemberRecord.serviceFees}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="MemberRecord.serviceFees" label="抽水">
        </el-table-column>
        <el-table-column label="輸贏合計">
          <template slot-scope="scope">
            <div :style="moneyColor(scope.row.totalChips)">{{scope.row.totalChips}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="MemberRecord.GambleMember.chips" label="最終積分">
        </el-table-column>
      </el-table-column>      
    </el-table>


    <el-table :data="members" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
      style="width: 100%">
      <el-table-column label="當前玩家餘額" align="center">
        <el-table-column prop="name_0" label="成員">
        </el-table-column>
        <el-table-column prop="chips_0" label="當前積分">
        </el-table-column>
        <el-table-column prop="name_1" label="成員">
        </el-table-column>
        <el-table-column prop="chips_1" label="當前積分">
        </el-table-column>
        <el-table-column prop="name_2" label="成員">
        </el-table-column>
        <el-table-column prop="chips_2" label="當前積分">
        </el-table-column>
        <el-table-column prop="name_3" label="成員">
        </el-table-column>
        <el-table-column prop="chips_3" label="當前積分">
        </el-table-column>
        </el-table-column>      
    </el-table>
</div>
</template>

<script>

import { mapGetters, mapActions } from 'vuex'
import { fetchDetails, fetchRoundCount, fetchDealingRecords, fetchMemberRecords, fetchRoundRecord, fetchGameBid } from '@/api/gambleGameBucket'
import { fetchGambleMemberList } from '@/api/gambleMember'
import { ponitTransform } from '@/utils/point'
import _ from 'lodash'
import moment from 'moment-timezone'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      detail: [],
      group: [],
      statement: '',
      rowspan: 0,
      colspan: 0,
      func: '',
      rowIndex: 0,
      colIndex: 0,
      roundOptions: [],
      members: [],
      dealing: [],
      bookie: [],
      memberRecord: [],
      door: 0,
      bidChips: 0,
    }
  },
  created() {
    fetchRoundRecord(this.data.secondLayer, this.query.secondLayer).then(response => {
      this.door = response.data.initialDoor
    })
    fetchGameBid(this.data.secondLayer).then(response => {
      this.bidChips = response.data
    })
    fetchRoundCount(this.data.secondLayer).then((response) => {
      for (let i = 1; i <= response.data; i++) {
        this.roundOptions.push({ label: `第 ${i} 關`, key: i })
      }
    })
    this.SetVisible(2)
    this.getList()
    fetchGambleMemberList({ page: 1, limit: 9999999999, chipsSort: 'DESC' }).then(response => {
      const { rows } = response.data
      let members = {}
      // TODO refactor
      rows.map((person, index) => {
        if (index % 4 === 0) {
          members.name_0 = person.name
          members.chips_0 = person.chips
          index === response.data.count - 1 ? this.members.push(members) : false
        } else if (index % 4 === 1) {
          members.name_1 = person.name
          members.chips_1 = person.chips
          index === response.data.count - 1 ? this.members.push(members) : false
        } else if (index % 4 === 2) {
          members.name_2 = person.name
          members.chips_2 = person.chips
          index === response.data.count - 1 ? this.members.push(members) : false
        } else if (index % 4 === 3) {
          members.name_3 = person.name
          members.chips_3 = person.chips
          this.members.push(members)
          members = {}
        }
      })
    })
  },
  computed: {
    ...mapGetters([
      'visible',
      'data',
      'query'
    ])
  },
  methods: {
    ...mapActions([
      'SetVisible',
      'SetData',
      'SetQuery'
    ]),
    getList() {
      this.listLoading = true
      let detailTemp, dealingTemp, memberRecordTemp
      this.detail = []
      fetchDealingRecords(this.data.secondLayer, this.query.secondLayer).then(response => {
        dealingTemp = response.data.rows.filter(record => {
          return record.door !== -1
        })

        const deal = {}
        const member = {}
        dealingTemp.map((record, index) => {
          deal[`door_${index % 6}`] = record.door
          deal[`point1_${index % 6}`] = record.point1
          deal[`point2_${index % 6}`] = record.point2
          deal[`totalPoints_${index % 6}`] = record.totalPoints
          record.GambleMember ? member[`member_${index % 6}`] = record.GambleMember.name : false
          if (index % 6 === 5) {
            this.dealing.push(deal)
            this.dealing.push(member)
          }
        })
      })
      fetchMemberRecords(this.data.secondLayer, this.query.secondLayer).then(response => {
        memberRecordTemp = _.groupBy(response.data.rows, record => {
          return record.door
        })
        this.memberRecord = Object.values(memberRecordTemp)
      })
      fetchDetails(this.data.secondLayer, this.query.secondLayer).then(response => {
        detailTemp = response.data.rows.filter(record => {
          return record.DealingRecord.door !== -1 &&
            record.MemberRecord.door !== -1 &&
            record.MemberRecord.door === record.DealingRecord.door
        })

        this.bookie = response.data.rows.filter(record => {
          return record.DealingRecord.door === -1 &&
            record.MemberRecord.door === -1 &&
            record.MemberRecord.door === record.DealingRecord.door
        })
        this.bidChips ? this.bookie[0].bidChips = this.bidChips : false        
        this.group = _.groupBy(detailTemp, record => {
          return record.MemberRecord.GambleMember.name
        })
        this.group = Object.values(this.group)

        this.detail = this.group.reduce((arr, element) => {
          return arr.concat(element)
        }, [])

        this.group.map((item, itemIndex) => {
          let totalChips = 0
          item.map((person, personIndex) => {
            totalChips = totalChips + person.MemberRecord.earned - person.MemberRecord.serviceFees
            item.length - 1 === personIndex ? this.detail[this._sum(itemIndex)].totalChips = totalChips : false
          })
        })

        for (let i = 0; i < this.group.length; i++) {
          if (i === 0) {
            this.statement =
            `if(this.rowIndex === ${i}){
              this.rowspan = ${this.group[i].length},
              this.colspan = 1
            }`
          } else {
            this.statement +=
            `else if(this.rowIndex === ${this._sum(i)}){
              this.rowspan = ${this.group[i].length},
              this.colspan = 1 
            }`
          }
          if (i === this.group.length - 1) {
            this.statement +=
            `else {
              this.rowspan = 0,
              this.colspan = 0
            }`
          }
        }

        this.func = eval(`(function() {${this.statement}})`)
      })

      this.listLoading = false
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 5 || columnIndex === 6 || columnIndex === 7 || columnIndex === 8) {
        this.rowIndex = rowIndex
        this.columnIndex = columnIndex
        const that = this

        this.func()
        return {
          rowspan: this.rowspan,
          colspan: this.colspan
        }
      }
    },
    getSummaries() {
      const sums = []
      this.memberRecord.map((group, index) => {
        if (index === 0) sums[index] = '總押注'
        let doorTotal = 0
        group.map((door) => {
          doorTotal += door.wager
        })
        sums[index + 1] = doorTotal
      })
      return sums
    },
    handleFilter() {
      fetchRoundRecord(this.data.secondLayer, this.query.secondLayer).then(response => {
        this.door = response.data.initialDoor
      })
      this.SetQuery({layer:2, query: {round: this.query.secondLayer.round}})      
      this.dealing = []
      this.getList()
    },
    moment(time) {
      return moment(time).tz('Asia/Taipei').format('YYYY-MM-DD HH:mm:ss')
    },
    moneyColor(money) {
      return money >= 0 ? { color: '#67C23A' } : { color: '#FA5555' }
    },
    // TODO refactor
    doorTableSwitch(rowIndex, colIndex) {
      if (rowIndex === 0) {
        return `${this.dealing[0][`point1_${colIndex}`]} | ${this.dealing[0][`point2_${colIndex}`]} / ${this.point({point1: this.dealing[0][`point1_${colIndex}`] ,point2: this.dealing[0][`point2_${colIndex}`] ,totalPoints: this.dealing[0][`totalPoints_${colIndex}`]})}`
      }
      if (rowIndex === 1) {
        return this.dealing[1][`member_${colIndex+1}`] ? `${this.dealing[1][`member_${colIndex+1}`]}` : '從缺'
      }
    },
    _sum(i) {
      let count = 0
      for (let j = 0; j < i; j++) {
        count += this.group[j].length
      }
      return count
    },
    point(dealingRecord) {
      return ponitTransform(dealingRecord)
    },
    initDoor({row, column, rowIndex, columnIndex}) {
      return  columnIndex === this.door ? { color: '#F56C6C' } : ``
    }
  },
  destroyed() {
    this.SetVisible(1)
  }
}
</script>
<style>
div{
  font-weight: bold;
  font-size: 25px
}
</style>