<template>
  <div class="app-container calendar-list-container">
    <div  v-show="visible.firstLayer">
      <div class="app-container">
        <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名稱" v-model="listQuery.name">
        </el-input>
        <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.GambleMember.id}}
          </template>
        </el-table-column> -->
        <el-table-column label="名稱" align="center">
          <template slot-scope="scope">
            {{scope.row.GambleMember.name}}
          </template>
        </el-table-column>
        <el-table-column label="抽水％" align="center">
          <template slot-scope="scope">
            {{scope.row.feeRatio}}
          </template>
        </el-table-column>
          <el-table-column label="上繳工作室金額" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.all)">{{scope.row.all}}</span>
            </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="450">
          <template slot-scope="scope">          
            <router-link to="/agent/index/gambleMemberManagement">
              <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="創建代理商" :visible.sync="dialogCreateFormVisible" :before-close="handleDialogClose" center>
        <el-form :rules="rules" ref="createForm" :model="createFormData" label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
          <el-form-item label="名稱" prop="name">
            <el-input v-model="createFormData.name"></el-input>
          </el-form-item>
          <el-form-item label="抽水 ％" prop="feeRatio">
            <el-input v-model="createFormData.feeRatio"></el-input>
          </el-form-item>
        </el-form>          
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleDialogClose">取 消</el-button>
          <el-button type="primary" @click="createData">確 定</el-button>
        </div>
      </el-dialog>
    </div>
    <router-view></router-view>
  </div>
</template>

<script>

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

export default {
  directives: {
    waves
  },
  data() {
    return {
      list: [],
      total: null,
      listLoading: true,
      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()
      },
      dialogCreateFormVisible: false,
      dialogStatus: '',
      // agent: {},
      rules: {
        // rewardChips: [{ pattern: /^-?\d+$/, required: true, message: '請輸入整數', trigger: 'change' }],        
        // 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' }]
      },
      createFormData: {
        name: '',
        feeRatio: '',
      }
    }
  },
  created() {
    this.SetVisible(1)
    this.getList()
  },
  computed: {
    ...mapGetters([
      'visible',
      'data',
    ])
  },
  methods: {
    ...mapActions([
      'SetVisible',
      'SetData',
    ]),
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {

        response.data.rows.map(agent => {
          let combine = []
          this.list = []          
          fetchMemberList(agent, 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,
                bookieServiceFees: 0,
                memberServiceFees: 0,
                totalServiceFees: 0,
                memberCheckOut: 0,
              }
            
              let bookie = _.groupBy(member['GambleGame-Bucket-MemberRecords'], 'isBookie')
              if (bookie.false) {
                row.memberEarned = _.sumBy(bookie.false, 'earned');
                row.memberServiceFees = _.sumBy(bookie.false, 'serviceFees')*agent.feeRatio/100;
              }
              if (bookie.true) {
                row.bookieEarned = _.sumBy(bookie.true, 'earned');
                row.bookieServiceFees = _.sumBy(bookie.true, (item) => { return item.serviceFees-500; })*agent.feeRatio/100;
              }
              row.totalServiceFees = new Decimal(row.bookieServiceFees).plus(row.memberServiceFees).valueOf()

              let chipsLog = _.groupBy(member.GambleMemberChipsLogs, 'type')
              if (chipsLog['0']) {
                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
                })
              }
              row.memberCheckOut = row.totalUp + row.totalDown - row.chips
              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
                })
              }
              combine.push(row)
            })
            let allUp = _.sumBy(combine, 'totalUp')
            let allDown = _.sumBy(combine, 'totalDown')
            let allChips = _.sumBy(combine, 'chips')
            let allEarned = _.sumBy(combine, (item) => {return item.bookieEarned + item.memberEarned})
            let allServiceFees = _.sumBy(combine, (item) => {return item.bookieServiceFees + item.
            memberServiceFees})
            agent.all = (allUp+allDown-allChips-allServiceFees)*(-1)
            this.list.push(agent)
            
            this.listLoading = false
          })
        })
        this.total = response.data.count
        this.listLoading = false
      })
    },
    resetCreateData() {
      this.temp = {
        id: undefined,
        name: '',
        chips: '',
        depositChips: ''
      }
    },
    handleCreate() {
      this.resetCreateData()
      this.dialogCreateFormVisible = true
      this.$nextTick(() => {
        this.$refs['createForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['createForm'].validate((valid) => {
        if (valid) {
          createAgent(this.createFormData).then((response) => {
            const agent = response.data.gambleAgentSetting;
            agent.GambleMember = response.data.agent
            this.list.unshift(agent)
            this.dialogCreateFormVisible = false         
            this.$notify({
              title: '成功',
              message: '創建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDialogClose() {
      this.dialogCreateFormVisible = false;
    },
    handlePage(row) {
      const temp = Object.assign({}, row) // copy obj
      this.SetVisible(2)
      this.SetData({layer:2, data: temp})
      // this.agent = temp
    },
    moneyColor(money) {
      return money >= 0 ? { color: '#67C23A' } : { color: '#FA5555' }
    },
  },
}
</script>
