<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width: 200px"
        class="filter-item"
        collapse-tags
        @change="handleSearch"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>
      <div class="filter-item">
        <account-input v-model="listQuery.userId" :sys-origin="listQuery.sysOrigin" placeholder="用户ID" />
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="rangeDate"
          value-format="timestamp"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSearch"
        />
      </div>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        搜索
      </el-button>
    </div>
    <el-alert type="success" :closable="false">
      <div v-if="showProfitLossAmount" slot="title">收入{{ profitLossAmount.income }} - 支出{{ profitLossAmount.expenditure }} = 余{{ profitLossAmount.remain }}</div>

      <strong>注意:</strong> 每条数据的生命周期30天, 30天后记录将会清理
      <strong
        v-loading="prizePoolAmountLoading"
        element-loading-spinner="el-icon-loading"
        style="margin-left: 10px"
        class="cursor-pointer"
        @click="clickPrizePool"
      >
        <i class="el-icon-refresh" />奖金池: {{ prizePoolAmount || '-' }}
        、幸运池: {{ luckyPrizePoolAmount || '-' }}
      </strong>

      <el-tooltip class="item" effect="dark" content="抽取比率放入幸运池, 达到幸运礼物价值后必出">
        <strong
          v-loading="luckyDrawRatioLoading"
          style="margin-left: 10px"
          element-loading-spinner="el-icon-loading"
          class="cursor-pointer"
          @click="clickLuckyDrawRatio"
        >
          <i class="el-icon-edit">
            幸运抽%: {{ luckyDrawRatio }}
          </i>
        </strong>

      </el-tooltip>

      <el-tooltip class="item" effect="dark" content="用于分割本次奖金第一次放入抽取后的余额,抽奖结束后将投入奖金抽取作为第二次奖金投入奖金池, 提高游戏波动">
        <strong
          v-loading="poolPutRatioLoading"
          style="margin-left: 10px"
          element-loading-spinner="el-icon-loading"
          class="cursor-pointer"
          @click="clickPoolPutRatio"
        >
          <i class="el-icon-edit">
            投入奖金抽%: {{ poolPutRatio }}
          </i>
        </strong>
      </el-tooltip>
    </el-alert>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column label="用户" align="center" min-width="200">
        <template slot-scope="scope">
          <user-table-exhibit :user-profile="scope.row.userProfile" :query-details="true" />
        </template>
      </el-table-column>
      <el-table-column prop="tickets" label="门票" align="center" min-width="80" />
      <el-table-column prop="lotterySize" label="抽奖次数" align="center" min-width="80" />
      <el-table-column prop="giftTotalAmount" label="礼物总价值" align="center" min-width="80" />
      <el-table-column prop="earn" label="盈亏" align="center" min-width="80" />
      <el-table-column label="抽成" align="center" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.earn > 0">
            {{ scope.row.earn }} *  {{ scope.row.luckyDrawRatio }} = {{ scope.row.luckyDrawAmount }}
          </span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="clickQueryDetails(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="list && list.length > 0" style="text-align: center; margin-top:20px;">
      <el-button v-if="!notMore " size="mini" :disabled="listLoading" @click="clickLoadMore">加载更多</el-button>
      <span v-else>已加载全部</span>
    </div>

    <details-drawer
      v-if="dtailsDrawerVisible"
      :row="thatRow"
      @close="dtailsDrawerVisible=false"
    />
  </div>
</template>

<script>

import { listGameLuckyBox, getProfitLossAmount, getPrizePoolAmount, getLuckyPrizePoolAmount, getLuckyDrawRatio, setLuckyDrawRatio, getPoolPutRatio, setPoolPutRatio } from '@/api/game'
import { originPlatforms } from '@/constant/origin'
import { candyPurchasingTypes, currencyOrigins } from '@/constant/type'
import { pickerOptions } from '@/constant/el-const'
import { mapGetters } from 'vuex'
import DetailsDrawer from './details-drawer'
export default {
  name: 'GameLuckBox',
  components: { DetailsDrawer },
  data() {
    return {
      dtailsDrawerVisible: false,
      thatRow: {},
      searchDisabled: false,
      pickerOptions,
      thatSelectedUserId: '',
      originPlatforms,
      candyPurchasingTypes,
      currencyOrigins,
      list: [],
      total: 0,
      rangeDate: [],
      listQuery: {
        limit: 20,
        userId: '',
        startTime: '',
        endTime: '',
        sysOrigin: '',
        lastId: ''
      },
      listLoading: true,
      clickUserId: '',
      restaurants: [],
      notMore: false,
      profitLossAmount: {},
      prizePoolAmount: '',
      prizePoolAmountLoading: false,
      luckyDrawRatio: '',
      luckyDrawRatioLoading: false,
      poolPutRatio: '',
      poolPutRatioLoading: false,
      luckyPrizePoolAmount: ''
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    showProfitLossAmount() {
      return !!(this.listQuery.startTime && this.listQuery.endTime && this.listQuery.sysOrigin)
    }
  },
  watch: {
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0]
          this.listQuery.endTime = newVal[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
  },
  mounted() {
    this.restaurants = this.currencyOrigins
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
        that.listQuery.lastId = ''
      }
      that.listLoading = true
      that.loadProfitLossAmount()
      that.loadPrizePoolAmount()
      that.loadLuckyDrawRatio()
      that.loadPoolPutRatio()
      listGameLuckyBox(that.listQuery).then(res => {
        that.listLoading = false
        const { body } = res
        const list = body || []
        that.notMore = list.length <= 0
        that.list = that.list.concat(list)
        if (that.list && that.list.length > 0) {
          that.listQuery.lastId = that.list[that.list.length - 1].id
        }
      }).catch(er => {
        that.listLoading = false
        console.error(er)
      })
    },
    loadProfitLossAmount() {
      const that = this
      that.profitLossAmount = {}
      getProfitLossAmount(that.listQuery).then(res => {
        that.profitLossAmount = res.body || {}
      }).catch(er => {
        console.error(er)
      })
    },
    loadPrizePoolAmount() {
      const that = this
      that.prizePoolAmount = ''
      that.prizePoolAmountLoading = true
      getPrizePoolAmount(that.listQuery.sysOrigin).then(res => {
        that.prizePoolAmountLoading = false
        that.prizePoolAmount = res.body || ''
      }).catch(er => {
        that.prizePoolAmountLoading = false
        console.error(er)
      })

      getLuckyPrizePoolAmount(that.listQuery.sysOrigin).then(res => {
        that.luckyPrizePoolAmount = res.body || ''
      }).catch(er => {
        console.error(er)
      })
    },
    loadLuckyDrawRatio() {
      const that = this
      that.luckyDrawRatio = ''
      that.luckyDrawRatioLoading = true
      getLuckyDrawRatio(that.listQuery.sysOrigin).then(res => {
        that.luckyDrawRatioLoading = false
        that.luckyDrawRatio = res.body
      }).catch(er => {
        that.luckyDrawRatioLoading = false
        console.error(er)
      })
    },
    loadPoolPutRatio() {
      const that = this
      that.poolPutRatio = ''
      that.poolPutRatioLoading = true
      getPoolPutRatio(that.listQuery.sysOrigin).then(res => {
        that.poolPutRatioLoading = false
        that.poolPutRatio = res.body
      }).catch(er => {
        that.poolPutRatioLoading = false
        console.error(er)
      })
    },
    handleSearch() {
      this.renderData(true)
    },
    querySearch(queryString, cb) {
      var restaurants = currencyOrigins
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0) || (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    clickLoadMore() {
      this.renderData()
    },
    clickPrizePool() {
      this.loadPrizePoolAmount()
    },
    clickLuckyDrawRatio() {
      const that = this
      that.$prompt('计算方式:门票- (门票 * 概率)=抽取', 'Lucky抽取', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{1,5}(\.\d{0,5})?$/,
        inputErrorMessage: '范围0~99999小数最多5位'
      }).then(({ value }) => {
        that.luckyDrawRatioLoading = true
        setLuckyDrawRatio(that.listQuery.sysOrigin, value).then(res => {
          that.loadLuckyDrawRatio()
        }).catch(er => {
          console.error(er)
          that.luckyDrawRatioLoading = false
        })
      }).catch(() => {
      })
    },
    clickPoolPutRatio() {
      const that = this
      that.$prompt('计算方式:(门票- Lucky抽取) * 概率=抽取', '投入奖金池抽取', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{1,5}(\.\d{0,5})?$/,
        inputErrorMessage: '范围0~99999小数最多5位'
      }).then(({ value }) => {
        that.poolPutRatioLoading = true
        setPoolPutRatio(that.listQuery.sysOrigin, value).then(res => {
          that.loadPoolPutRatio()
        }).catch(er => {
          console.error(er)
          that.poolPutRatioLoading = false
        })
      }).catch(() => {
      })
    },
    clickQueryDetails(row) {
      this.thatRow = row
      this.dtailsDrawerVisible = true
    }
  }
}
</script>
