<template>
  <div class="egg-lottery-cnf">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.eggLotteryCnf.placeholder.system')"
        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">
        {{ $t('pages.eggLotteryCnf.action.search') }}
      </el-button>
      <el-button type="primary" class="filter-item" @click="clickAdd">
        <i class="el-icon-circle-plus" /> {{ $t('pages.eggLotteryCnf.action.add') }}
      </el-button>
      <el-button type="primary" class="filter-item" :loading="submitLoading" :disabled="submitDisabled" @click="clickSave">
        <i class="el-icon-success" /> {{ $t('pages.eggLotteryCnf.action.save') }}
      </el-button>
      <!-- <el-button type="text" @click="clickSetEggExtractRatio">{{ $t('pages.eggLotteryCnf.action.prizePool') }}{{ prizePool }}</el-button>
      <el-button type="text" :loading="extractRatioLoading" :disabled="extractRatioLoading" @click="clickSetEggExtractRatio">{{ $t('pages.eggLotteryCnf.action.extractRatio') }}{{ extractRatio || '-' }}</el-button> -->
    </div>
    <el-alert
      type="info"
      :closable="false"
      :description="$t('pages.eggLotteryCnf.message.notice')"
    />
    <div class="conf-row">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.sort')"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input
              v-model="scope.row.sort"
              size="small"
              :placeholder="$t('pages.eggLotteryCnf.placeholder.sort')"
              @input="submitDisabled = false"
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.prize')"
          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>
                  {{ $t('pages.eggLotteryCnf.action.set') }}<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)">{{ $t('pages.eggLotteryCnf.rewardType.props') }}</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('SPECIAL_ID', scope.row)">{{ $t('pages.eggLotteryCnf.rewardType.specialId') }}</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('GOLD', scope.row)">{{ $t('pages.eggLotteryCnf.rewardType.gold') }}</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('DIAMOND', scope.row)">{{ $t('pages.eggLotteryCnf.rewardType.diamond') }}</el-dropdown-item>
                <el-dropdown-item @click.native="clickAddReward('GAME_COUPON', scope.row)">{{ $t('pages.eggLotteryCnf.rewardType.gameCoupon') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.prizeQuantity')"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input
              v-model="scope.row.prizeQuantity"
              size="small"
              :placeholder="$t('pages.eggLotteryCnf.placeholder.prizeQuantity')"
              @input="submitDisabled = false"
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.fragmentsSize')"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input
              v-model="scope.row.fragmentsSize"
              size="small"
              :placeholder="$t('pages.eggLotteryCnf.placeholder.fragmentsSize')"
              @input="submitDisabled = false"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.fragmentsAmount')"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input
              v-model="scope.row.fragmentsAmount"
              size="small"
              :placeholder="$t('pages.eggLotteryCnf.placeholder.fragmentsAmount')"
              @input="submitDisabled = false"
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.stockQuantity')"
          min-width="80"
          align="center"
        >
          <template scope="scope">
            <el-input
              v-model.number="scope.row.stockQuantity"
              size="small"
              :placeholder="$t('pages.eggLotteryCnf.placeholder.stockQuantity')"
              @input="submitDisabled = false"
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('pages.eggLotteryCnf.table.consumeStockQuantity')"
          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="$t('pages.eggLotteryCnf.table.action')"
          width="80"
          align="center"
        >
          <template scope="scope">
            <el-button type="text" class="filter-item" @click="clickDel(scope.row, scope.$index)">
              {{ $t('pages.eggLotteryCnf.action.delete') }}
            </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
    },
    getValidationMessage(type, index) {
      return this.$t(`pages.eggLotteryCnf.validation.${type}`, { index: index + 1 })
    },
    clickSave() {
      const that = this
      if (that.submitDisabled) {
        that.$opsMessage.warn(that.$t('pages.eggLotteryCnf.message.noChanges'))
        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(that.getValidationMessage('sort', index))
        }
        if (!item.sourceType) {
          errors.push(that.getValidationMessage('prize', index))
        }
        if (!that.validNumber(item.prizeQuantity, 0, 99999999)) {
          errors.push(that.getValidationMessage('prizeQuantity', index))
        }
        if (!that.validNumber(item.stockQuantity, -1, 99999999)) {
          errors.push(that.getValidationMessage('stockQuantity', index))
        }
        if (!that.validNumber(item.fragmentsSize, 1, 99999999)) {
          errors.push(that.getValidationMessage('fragmentsSize', index))
        }
        if (!that.validNumber(item.fragmentsAmount, 1, 99999999)) {
          errors.push(that.getValidationMessage('fragmentsAmount', index))
        }
        if (errors.length > 0) {
          errors.push(that.$t('pages.eggLotteryCnf.validation.fixAndSubmit'))
          that.$confirm(errors.join('<br>'), that.$t('pages.eggLotteryCnf.dialog.title'), {
            confirmButtonText: that.$t('pages.eggLotteryCnf.dialog.confirm'),
            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(that.$t('pages.eggLotteryCnf.dialog.deleteConfirm'), that.$t('pages.eggLotteryCnf.dialog.title'), {
        confirmButtonText: that.$t('pages.eggLotteryCnf.dialog.confirm'),
        cancelButtonText: that.$t('pages.eggLotteryCnf.dialog.cancel'),
        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(that.$t('pages.eggLotteryCnf.dialog.resetConfirm'), that.$t('pages.eggLotteryCnf.dialog.title'), {
        confirmButtonText: that.$t('pages.eggLotteryCnf.dialog.confirm'),
        cancelButtonText: that.$t('pages.eggLotteryCnf.dialog.cancel'),
        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(that.$t('pages.eggLotteryCnf.dialog.extractFormula'), that.$t('pages.eggLotteryCnf.dialog.extractTitle'), {
        confirmButtonText: that.$t('pages.eggLotteryCnf.dialog.confirm'),
        cancelButtonText: that.$t('pages.eggLotteryCnf.dialog.cancel'),
        inputPattern: /^\d{1,5}(\.\d{0,5})?$/,
        inputErrorMessage: that.$t('pages.eggLotteryCnf.dialog.extractInputError')
      }).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: 0;
      top: -10px;
    }
  }
}
</style>
