<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>
        <el-input style='width:100px;' placeholder="輸入檔案名稱" prefix-icon="el-icon-document" v-model="filename"></el-input>
        <el-button style='margin-bottom:20px;' type="primary" icon="document" @click="handleDownload" :loading="downloadLoading">匯出 excel</el-button>
      </div>
      <el-table show-summary :summary-method="getSummaries" :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.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="代理商上繳金額" prop="all" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.all)">{{scope.row.all}}</span>
            </template>
        </el-table-column>
        <el-table-column label="抽水％" align="center">
          <template slot-scope="scope">
            {{scope.row.feeRatio2}}
          </template>
        </el-table-column>    
        <el-table-column label="代理商上繳金額" prop="all" align="center">
            <template slot-scope="scope">
              <span :style="moneyColor(scope.row.all2)">{{scope.row.all2}}</span>
            </template>
        </el-table-column>
        <el-table-column label="上繳工作室金額70%" prop="all70" align="center">
          <template slot-scope="scope">
            <span :style="moneyColor(scope.row.all70)">{{scope.row.all70}}</span>
          </template>
        </el-table-column>
        <el-table-column label="總逞罰" prop="fredPunishment" align="center">
          <template slot-scope="scope">
            {{scope.row.fredPunishment}}
          </template>
        </el-table-column> 
        <el-table-column align="center" label="操作">
          <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-item label="抽水 ％ (只在列表顯示)" prop="feeRatio2">
            <el-input v-model="createFormData.feeRatio2"></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,fetchGroupAll } 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,
      downloadLoading: false,
      listQuery: {
        page: 1,
        limit: 9999999,
        name: ''
        // startAt: moment.utc(moment().day('sunday').hour(12).minute(0).second(0).subtract(1, 'weeks').day(7).hour(16).minute(0).second(0)).format(),
        // endAt: moment.utc(moment().day('sunday').hour(12).minute(0).second(0).day(7).hour(11).minute(59).second(59)).format()
      },
      filename: '',
      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: '',
        feeRatio2: '',
      }
    }
  },
  created() {
    this.SetVisible(1)
    this.getList()
  },
  computed: {
    ...mapGetters([
      'visible',
      'data',
    ])
  },
  methods: {
    ...mapActions([
      'SetVisible',
      'SetData',
    ]),
    async getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(async response => {

        // response.data.rows.map(agent => {
        for(const agent of response.data.rows) {
          let combine = []
          this.list = []   
          if(this.visible.firstLayer === true) {
            fetchGroupAll(agent, this.listQuery).then(response => {
              console.log('response' , response.data)
              this.list.push({
                // id: agent.GambleMember.id,
                // GambleMember: {
                //   id: agent.GambleMember.id,
                //   name: agent.GambleMember.name
                // },
                id: agent.GambleMember.id,
                name: agent.GambleMember.name.slice(19),
                createdAt: agent.GambleMember.createdAt,
                feeRatio: response.data.feeRatio,
                feeRatio2: response.data.feeRatio2,
                all: response.data.all,
                all2: response.data.all2,
                all70: response.data.all70,
                fredPunishment: response.data.fredPunishment
              })
            })
          }
          
          // 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,
          //       bookieWagerFee: 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, item => {
          //         return Math.abs(item.earned)
          //       });
          //       row.memberServiceFees = _.sumBy(bookie.false, 'serviceFees')*agent.feeRatio/100;
          //     }
          //     if (bookie.true) {
          //       row.bookieWagerFee = _.sumBy(bookie.true, (item) => {
          //         return item.wagerServiceFees
          //       }) * agent.feeRatio/100;
          //       row.bookieEarned = _.sumBy(bookie.true, item => {
          //         return Math.abs(item.earned)
          //       });
          //       row.bookieServiceFees = _.sumBy(bookie.true, (item) => { return item.serviceFees })*agent.feeRatio/100;
          //     }
          //     row.totalServiceFees =  Number(new Decimal(row.bookieServiceFees).plus(row.memberServiceFees).plus(row.bookieWagerFee).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.totalServiceFees}).toFixed(2)
          //   agent.all = (allUp+allDown-allChips-allServiceFees)*(-1)
          //   this.list.push(agent)
            
          //   this.listLoading = false
          // })
        // })
        }
        // this.total = response.data.count
        this.listLoading = false
        console.log('list', this.list)
      })
    },
    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
            })
          })
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['名稱', '抽水%', '代理商上繳金額', '上繳工作室金額70%' ]
        const filterVal = ['name', 'feeRatio', 'all', 'all70' ]
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel(tHeader, data, this.filename)
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    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' }
    },
    getSummaries(param) {
        let { columns, data } = param;
        let sums = [];
        data = data.filter(item => item.name !== '文')        
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合計 ( 扣除文 ) ';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return new Decimal(prev).plus(curr);
              } else {
                return new Decimal(prev);
              }
            }, 0).valueOf();
            sums[index];
          } else {
            sums[index] = 'N/A';
          }
        });
        // this.allCombine.push({
        //   name: (this.data.secondLayer.GambleMember.name).slice(19),
        //   allUp: sums[2],
        //   allDown: sums[3],
        //   allChips: sums[1],
        //   allEarned: sums[6],
        //   allServiceFees: sums[13],
        // });
        // console.log('ewqewqeqweq', this.sums)
        return sums;
    }
  },
}
</script>
