<template>
  <div class="egg-lottery-cnf">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="归属系统"
        style="width: 120px"
        class="filter-item"
        @change="changeSysOrigin"
      >
        <el-option
          v-for="(item, index) in permissionsSysOriginPlatforms"
          :key="index"
          :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>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch"> 搜索 </el-button>
      <el-button type="primary" class="filter-item" @click="clickAdd"> <i class="el-icon-circle-plus" /> 添加</el-button>
      <el-button type="primary" class="filter-item" :loading="submitLoading" :disabled="submitDisabled" @click="clickSave"><i class="el-icon-success" /> 保存</el-button>
      <!-- <el-button type="text" @click="clickSetEggExtractRatio">奖金池:{{ prizePool }}</el-button>
      <el-button type="text" :loading="extractRatioLoading" :disabled="extractRatioLoading" @click="clickSetEggExtractRatio">抽取率:{{ extractRatio || '-' }}</el-button> -->
    </div>
    <el-alert
      type="info"
      :closable="false"
      description="注意: 不要随意对记录数据进行删除操作, 如果用户已拥有碎片将会被同步删除"
    />
    <div class="conf-row">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column
          label="序号"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input v-model="scope.row.sort" size="small" placeholder="请输入序号" @input="submitDisabled=false" />
          </template>
        </el-table-column>

        <el-table-column
          label="奖品"
          min-width="80"
          align="center"
        >
          <template scope="scope">

            <el-dropdown>
              <span class="el-dropdown-link">
                <div v-if="scope.row.sourceCover" class="preview-img flex-c">
                  <div v-if="scope.row.sourceUrl" class="player">
                    <svgaplayer
                      type="popover"
                      :url="scope.row.sourceUrl || ''"
                    />
                  </div>
                  <img v-if="scope.row.sourceCover" :src="scope.row.sourceCover" alt="" width="35" height="35">
                </div>
                <div v-else-if="scope.row.sourceType">
                  <img v-if="scope.row.sourceType === 'GOLD'" src="@/assets/gold_icon.png" width="35" height="35">
                  <img v-else-if="scope.row.sourceType === 'DIAMOND'" src="@/assets/diamond_icon.png" width="35" height="35">
                  <img v-else-if="scope.row.sourceType === 'GAME_COUPON'" src="@/assets/game_coupon.png" width="35" height="35">
                  <img v-else-if="scope.row.sourceType === 'SPECIAL_ID'" src="@/assets/special_id.png" width="35" height="35">
                </div>
                <div v-else>设置<i class="el-icon-arrow-down el-icon--right" /></div>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="clickSelectReward('PROPS',scope.row)">道具</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('SPECIAL_ID',scope.row)">靓号</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('GOLD',scope.row)">金币</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('DIAMOND',scope.row)">钻石</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('GAME_COUPON',scope.row)">游戏券</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>

        <el-table-column
          label="奖品量"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input v-model="scope.row.prizeQuantity" size="small" placeholder="请输入奖品数量" @input="submitDisabled=false" />
          </template>
        </el-table-column>

        <el-table-column
          label="碎片"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input v-model="scope.row.fragmentsSize" size="small" placeholder="请输入碎片兑换数量" @input="submitDisabled=false" />
          </template>
        </el-table-column>
        <el-table-column
          label="碎片价值"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input v-model="scope.row.fragmentsAmount" size="small" placeholder="请输入碎片价值" @input="submitDisabled=false" />
          </template>
        </el-table-column>

        <el-table-column
          label="库存"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input v-model.number="scope.row.stockQuantity" size="small" placeholder="请输入库存" @input="submitDisabled=false" />
          </template>
        </el-table-column>

        <el-table-column
          label="已消耗"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            {{ scope.row.consumeStockQuantity||0 }}
            <el-button type="text" class="el-icon-refresh-right" @click="clickResetConsumeStockQuantity(scope.row)" />
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="80"
          align="center"
        >
          <template scope="scope">
            <el-button type="text" class="filter-item" @click="clickDel(scope.row, scope.$index)"> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <props-source-select-drawer
      v-if="propsSourceSelectDrawerVisible"
      :sys-origin="listQuery.sysOrigin"
      @close="propsSourceSelectDrawerVisible=false"
      @select="selectPropsSource"
    />
  </div>
</template>

<script>

import PropsSourceSelectDrawer from '@/components/data/PropsSourceSelectDrawer'
import { getEggConfig, updateEggConfig, resetEggConsumeStockQuantity, getEggExtractRatio, setEggExtractRatio, getEggPrizePool } from '@/api/game'
import { pickerOptions } from '@/constant/el-const'
import { sysOriginPlatforms } from '@/constant/origin'
import { mapGetters } from 'vuex'

export default {
  name: 'EggLotteryRecord',
  components: { PropsSourceSelectDrawer },
  data() {
    return {
      propsSourceSelectDrawerVisible: false,
      sysOriginPlatforms,
      searchDisabled: false,
      pickerOptions,
      userDeatilsDrawerVisible: false,
      thatSelectedGameId: '',
      gameTotals: [0, 0],
      list: [],
      total: 0,
      rangeDate: [],
      listQuery: {
        sysOrigin: ''
      },
      listLoading: false,
      thatRow: {},
      submitDisabled: true,
      submitLoading: false,
      removeIds: [],
      preSysOrigin: '',
      extractRatioLoading: false,
      extractRatio: '',
      prizePool: ''
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.preSysOrigin = that.listQuery.sysOrigin
    that.renderData(true)
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
      }
      that.loadEggPrizePool()
      that.loadEggExtractRatio()
      that.listLoading = true
      getEggConfig(that.listQuery).then(res => {
        that.listLoading = false
        const { body } = res
        that.list = body || []
      }).catch(er => {
        that.listLoading = false
      })
    },
    handleSearch() {
      this.renderData(true)
    },
    clickSelectReward(type, row) {
      this.thatRow = row
      this.thatRow.sourceType = type
      this.propsSourceSelectDrawerVisible = true
      this.submitDisabled = false
    },
    clickAddReward(type, row) {
      if (row.sourceType === type) {
        return
      }
      row.sourceType = type
      row.sourceDetailType = type
      row.sourceCover = ''
      row.sourceUrl = ''
      row.fragmentsAmount = 0
      this.submitDisabled = false
    },
    selectPropsSource(item) {
      this.thatRow.sourceCover = item.cover
      this.thatRow.sourceUrl = item.sourceUrl
      this.thatRow.sourceDetailType = item.type
      this.thatRow.sourceId = item.id
      if (item.amount && this.validNumber(this.thatRow.prizeQuantity, 1, 99999999) && this.validNumber(this.thatRow.fragmentsSize, 1, 99999999)) {
        console.log(item.amount * this.thatRow.prizeQuantity / this.thatRow.fragmentsSize)
        this.thatRow.fragmentsAmount = Math.floor(item.amount * this.thatRow.prizeQuantity / this.thatRow.fragmentsSize)
      }
      this.propsSourceSelectDrawerVisible = false
    },
    createConfItem() {
      return {
        id: '',
        sort: '0',
        sourceId: '',
        sourceType: '',
        sourceDetailType: '',
        sourceCover: '',
        sourceUrl: '',
        prizeQuantity: 1,
        stockQuantity: -1,
        fragmentsSize: 1,
        fragmentsAmount: 1,
        sysOrigin: this.listQuery.sysOrigin
      }
    },
    clickAdd() {
      this.list.push(this.createConfItem())
      this.submitDisabled = false
    },
    clickSave() {
      const that = this
      if (that.submitDisabled) {
        that.$opsMessage.warn('当前没有任何操作~')
        return
      }
      const errors = []
      for (let index = 0; index < that.list.length; index++) {
        const item = that.list[index]
        if (!that.validNumber(item.sort, 0, 99999999)) {
          errors.push(`[${index + 1}行]序号, 错误请输入阿拉伯数字>=0 && <= 99999999`)
        }
        if (!item.sourceType) {
          errors.push(`[${index + 1}行]奖品, 为空`)
        }
        if (!that.validNumber(item.prizeQuantity, 0, 99999999)) {
          errors.push(`[${index + 1}行]奖品数量, 错误请输入阿拉伯数字>=1 && <= 99999999`)
        }
        if (!that.validNumber(item.stockQuantity, -1, 99999999)) {
          errors.push(`[${index + 1}行]库存数量, 错误请输入阿拉伯数字>=-1 && <= 99999999`)
        }
        if (!that.validNumber(item.fragmentsSize, 1, 99999999)) {
          errors.push(`[${index + 1}行]碎片数量, 错误请输入阿拉伯数字>=1 && <= 99999999`)
        }
        if (!that.validNumber(item.fragmentsAmount, 1, 99999999)) {
          errors.push(`[${index + 1}行]碎片价值, 错误请输入阿拉伯数字>=1 && <= 99999999`)
        }
        if (errors.length > 0) {
          errors.push('请更正后重新提交!!!')
          that.$confirm(errors.join('<br>'), '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
          }).catch(() => {
          })
          return
        }
      }

      that.submitDisabled = true
      that.submitLoading = true
      updateEggConfig({
        sysOrigin: that.listQuery.sysOrigin,
        configs: that.list,
        removeIds: that.removeIds
      }).then(res => {
        that.submitLoading = false
        that.$opsMessage.success()
      }).catch(er => {
        that.submitDisabled = false
        that.submitLoading = false
      })
    },
    validNumber(num, startRange, endRange) {
      return /^-?\d+$/.test(String(num)) && Number(num) >= startRange && Number(num) <= endRange
    },
    changeSysOrigin() {
      this.handleSearch(true)
    },
    clickDel(row, index) {
      const that = this
      that.$confirm('用户已拥有对应碎片数据将会同步删除, 是否继续？', '提示', {
        type: 'warning'
      }).then(() => {
        that.list.splice(index, 1)
        if (row.id) {
          that.removeIds.push(row.id)
          that.submitDisabled = false
        }
      }).catch(er => {
      })
    },
    clickResetConsumeStockQuantity(row) {
      const that = this
      that.$confirm('是否确定重置库存消耗', '提示', {
        type: 'warning'
      }).then(() => {
        resetEggConsumeStockQuantity(row.id).then(res => {
          that.$opsMessage.success()
        }).catch(er => {
          console.error(er)
        })
      }).catch(er => {
      })
    },
    loadEggPrizePool() {
      const that = this
      getEggPrizePool(that.listQuery.sysOrigin).then(res => {
        that.prizePool = res.body || ''
      }).catch(er => {
        console.error(er)
      })
    },
    loadEggExtractRatio() {
      const that = this
      that.extractRatioLoading = true
      getEggExtractRatio(that.listQuery.sysOrigin).then(res => {
        that.extractRatioLoading = false
        that.extractRatio = res.body || ''
      }).catch(er => {
        console.error(er)
        that.extractRatioLoading = false
      })
    },
    clickSetEggExtractRatio() {
      const that = this
      that.$prompt('计算方式:门票- (门票 * 概率)=抽取', '门票抽取', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d{1,5}(\.\d{0,5})?$/,
        inputErrorMessage: '范围0~99999小数最多5位'
      }).then(({ value }) => {
        that.extractRatioLoading = true
        setEggExtractRatio(that.listQuery.sysOrigin, value).then(res => {
          that.extractRatioLoading = false
          that.loadEggExtractRatio()
        }).catch(er => {
          console.error(er)
          that.extractRatioLoading = false
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style scoped lang="scss">
.egg-lottery-cnf {
  .preview-img {
    position: relative;
    .player {
      position: absolute;
      right: 0px;
      top: -10px;
    }
  }
}
</style>
