<template>
  <div  class="app-container">
    <div v-show="visible.secondLayer">
      <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="allCombine" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
          <el-table-column label="代理商名稱" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總上分額" align="center">
            <template slot-scope="scope">
               <span>{{scope.row.allUp}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總下分額" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.allDown}}</span>
            </template>
          </el-table-column>
          <el-table-column label="所有會員點數" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.allChips}}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效投注量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.allEarned}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總水量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.allServiceFees}}</span>
            </template>
          </el-table-column>
          <el-table-column label="上繳工作室金額" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(all(scope))">{{all(scope)}}</span>
            </template>
          </el-table-column>
      </el-table>
      <el-table :data="combine" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column :label="`${this.data.secondLayer.GambleMember.name}的會員`" align="center">
          <el-table-column label="名稱" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </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 label="總上分額" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.totalUp}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總下分額" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.totalDown}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總獎勵" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.totalReward}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總懲罰" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.totalPunishment}}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效投注量" align="center">
            <template slot-scope="scope">
              <span>{{0}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="莊家贏錢" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.bookieEarned)">{{scope.row.bookieEarned}}</span>
            </template>
          </el-table-column>
          <el-table-column label="閒家贏錢" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.memberEarned)">{{scope.row.memberEarned}}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="莊家總投注量抽水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.bookieWagerFee}}</span>
            </template>
          </el-table-column>
          <el-table-column label="莊家總投注量退水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.feeRatio.times(scope.row.bookieWagerFee).valueOf()}}</span>
            </template>
          </el-table-column>
          <el-table-column label="莊家總抽水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.bookieServiceFees}}</span>
            </template>
          </el-table-column>
          <el-table-column label="莊家退水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.feeRatio.times(scope.row.bookieServiceFees).valueOf()}}</span>
            </template>
          </el-table-column>
          <el-table-column label="閒家總抽水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.memberServiceFees}}</span>
            </template>
          </el-table-column>
          <el-table-column label="閒家退水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.feeRatio.times(scope.row.memberServiceFees).valueOf()}}</span>
            </template>
          </el-table-column>
          <el-table-column label="總退水" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.totalServiceFees}}</span>
            </template>
          </el-table-column>
          <el-table-column label="會員結帳" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor((scope.row.memberCheckOut)*(-1))">{{(scope.row.memberCheckOut)*(-1)}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
                <router-link to="/agent/index/gambleMemberManagement/index/gameHistory">
                    <el-button type="primary" size="mini" icon="el-icon-tickets" @click="handlePersonDetail(scope.row)">紀錄</el-button>  
                </router-link>
            </template>
          </el-table-column>
        </el-table-column>      
      </el-table>

    </div>
    <router-view></router-view>
  </div>
</template>

<script>

import { mapActions, mapGetters } from 'vuex'
import { fetchMemberList } from '@/api/agnetManagement'
import waves from '@/directive/waves' // 水波纹指令
import moment from 'moment-timezone'
import config from '../../../../config' 
import _ from 'lodash'
import { Decimal } from 'decimal.js';

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

    }
  },
  created() {
    this.SetVisible(2)
    this.getList()
  },
  computed: {
    ...mapGetters([
      'visible',
      'data',
    ])
  },
  // props: ['agent'],
  methods: {
    ...mapActions([
      'SetVisible',
      'SetData',
    ]),
    getList() {
      this.listLoading = true
      this.allCombine = []
      this.combine = []
      fetchMemberList(this.data.secondLayer, this.listQuery).then(response => {
        response.data.rows.map(member => {
          let row = {
            id: member.id,
            name: member.name,
            chips: member.chips,
            totalUp: 0,
            totalDown: 0,
            totalReward: 0,
            totalPunishment: 0,
            bookieEarned: 0,
            memberEarned: 0,
            bookieWagerFee: 0,
            bookieServiceFees: 0,
            memberServiceFees: 0,
            totalServiceFees: 0,
            memberCheckOut: 0,
            feeRatio: new Decimal(this.data.secondLayer.feeRatio/100),
          }
        
          let bookie = _.groupBy(member['GambleGame-Bucket-MemberRecords'], 'isBookie')
          if (bookie.false) {
            row.memberEarned = _.sumBy(bookie.false, item => {
              return Math.abs(item.earned)
            });
            console.log('membeEarned', row.memberEarned)
            row.memberServiceFees = _.sumBy(bookie.false, 'serviceFees');
          }
          if (bookie.true) {
            row.bookieWagerFee = _.sumBy(bookie.true, (item) => {
              return item.wagerServiceFees
            });
            console.log('eeee', bookie.true)
            row.bookieEarned = _.sumBy(bookie.true, item => {
              return Math.abs(item.earned)
            });
            console.log('bookieEarned' , row.bookieEarned)
            row.bookieServiceFees = _.sumBy(bookie.true, (item) => { return item.serviceFees});
          }
          row.totalServiceFees = Number(new Decimal(row.bookieServiceFees).plus(row.memberServiceFees).plus(row.bookieWagerFee).valueOf())
          let chipsLog = _.groupBy(member.GambleMemberChipsLogs, 'type')
          // console.log('type', chipsLog)
          if (chipsLog['0'] || chipsLog['2']) {
            row.totalUp = _.sumBy(chipsLog['0'], (item) => { 
              return item.chips > 0 ? item.chips : 0
            })
            row.totalDown = _.sumBy(chipsLog['0'], (item) => { 
              return item.chips < 0 ? item.chips : 0
            }) + _.sumBy(chipsLog['2'], (item) => { 
              return item.chips < 0 ? item.chips : 0
            })

          }
          row.memberCheckOut = row.totalUp + row.totalDown - row.chips
          // TODO CHECK 是否需要
          if(chipsLog['1']) {
            row.totalReward = _.sumBy(chipsLog['1'], (item) => { 
              return item.chips > 0 ? item.chips : 0
            })
            row.totalPunishment = _.sumBy(chipsLog['1'], (item) => { 
              return item.chips < 0 ? item.chips : 0
            })
          }
          // console.log('www',row)

          this.combine.push(row)
        })
        console.log('cimbine' , this.combine)
        this.allCombine.push({
          name: this.data.secondLayer.GambleMember.name,
          allUp: _.sumBy(this.combine, 'totalUp'),
          allDown: _.sumBy(this.combine, 'totalDown'),
          allChips: _.sumBy(this.combine, 'chips'),
          allEarned: _.sumBy(this.combine, (item) => {return item.bookieEarned + item.memberEarned}),
          allServiceFees: _.sumBy(this.combine, (item) => {return item.totalServiceFees }),
        })
        this.listLoading = false
      })
      
    },
    handlePersonDetail(row) {
      const temp = Object.assign({}, row) // copy obj
      this.SetVisible(3)
      this.SetData({layer:3, 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' }
    },
    all(scope) {
      return (scope.row.allUp+scope.row.allDown-scope.row.allChips-scope.row.allServiceFees)*(-1)
    }
  },
  destroyed() {
    this.SetVisible(1)
  }
}
</script>
