<template>
  <div class="app-container-region">
    <el-dialog
      :title="$t('pages.gameConfig.fruit.gameParamsTitle')"
      :visible="true"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div style="margin-left: 10%;">
        <span class="custom-font" style="size: 20;">{{ $t('pages.gameConfig.fruit.prizeConfig') }}</span>
        <el-table
          v-loading="listLoading"
          :data="list"
          :element-loading-text="$t('pages.gameConfig.common.loading')"
          fit
          highlight-current-row
        >
          <el-table-column
            prop="sort"
            :label="$t('pages.gameConfig.common.sort')"
            width="100"
          />
          <el-table-column
            prop="prizeName"
            :label="$t('pages.gameConfig.common.name')"
            width="120"
          />
          <el-table-column
            prop="prizeImg"
            :label="$t('pages.gameConfig.common.icon')"
            width="150"
          >
            <template slot-scope="scope">
              <el-image
                :lazy="true"
                style="width: 50px; height: 50px"
                :src="scope.row.prizeImg"
                :preview-src-list="[scope.row.prizeImg]"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="award"
            :label="$t('pages.gameConfig.fruit.awardMultiplier')"
            width="120"
          />
          <el-table-column
            prop="prob"
            width="100"
            :label="$t('pages.gameConfig.common.probability')"
          >
            <template slot-scope="scope">
              {{ !scope.row.prob ? 0 : (scope.row.prob * 100).toFixed(2) }} %
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('pages.gameConfig.common.actions')"
            width="120"
          >
            <template slot-scope="scope">
              <el-button type="text" @click.native="handleUpdate(scope.row)">{{ $t('pages.gameConfig.action.edit') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog
        :title="$t('pages.gameConfig.fruit.prizeConfig')"
        :visible="innerVisible"
        :modal-append-to-body="true"
        :before-close="closePrizeDialog"
        :close-on-click-modal="false"
        width="550px"
        top="50px"
        append-to-body
      >
        <div v-loading="prizeLoading">
          <div class="form-contetn">
            <el-form ref="form" :model="prize" :rules="rules" label-width="110px" style="margin-right: 50px;">
              <el-form-item :label="$t('pages.gameConfig.common.cover')" prop="prizeImg">
                <el-upload
                  :disabled="coverUploadLoading"
                  :file-list="coverFileList"
                  :class="{'upload-but-hide': !isShowCoverUpload}"
                  action=""
                  list-type="picture-card"
                  :http-request="uploadCover"
                  :show-file-list="!isShowCoverUpload"
                  :on-remove="handleCoverFileRemove"
                  accept="image/*"
                >
                  <i slot="default" v-loading="coverUploadLoading" class="el-icon-plus" />
                </el-upload>
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.common.name')" prop="prizeName">
                <el-input v-model.trim="prize.prizeName" type="text" :placeholder="$t('pages.gameConfig.placeholder.name')" minlength="1" maxlength="150" show-word-limit />
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.common.type')" prop="type">
                <el-select
                  v-model="prize.type"
                  :placeholder="$t('pages.gameConfig.common.type')"
                  clearable
                  style="width:100%;"
                  class="filter-item"
                >
                  <el-option :label="$t('pages.gameConfig.fruit.vegetable')" :value="1" />
                  <el-option :label="$t('pages.gameConfig.fruit.pizza')" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.awardX')" prop="award">
                <el-input-number
                  v-model.trim="prize.award"
                  v-number
                  controls-position="right"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.awardPlaceholder')"
                /><span> {{ $t('pages.gameConfig.fruit.times') }}</span>
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.common.probability')" prop="prob">
                <el-input-number v-model="prize.prob" controls-position="right" :precision="2" :min="0" :max="99999" :placeholder="$t('pages.gameConfig.common.probability')" />%
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.common.sort')" prop="sort">
                <el-input-number v-model.trim="prize.sort" v-number :min="0" :max="99999" :placeholder="$t('pages.gameConfig.placeholder.sort')" />
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" style="text-align: right;">
            <el-button @click="closePrizeDialog()">{{ $t('common.cancel') }}</el-button>
            <el-button type="primary" @click="submitPrize()">{{ $t('common.save') }}</el-button>
          </div>
        </div>
      </el-dialog>

      <div style="padding-top: 100px;" />
      <div v-loading="submitLoading">

        <el-row :gutter="10">
          <div class="drawer-form">
            <el-form
              v-if="form"
              ref="configForm"
              :model="form"
              :rules="configRules"
              label-width="140px"
            >
              <el-form-item :label="$t('pages.gameConfig.fruit.vegetableIcon')" prop="vegetableImg">
                <el-upload
                  class="upload-demo"
                  action=""
                  :http-request="httpRequest"
                  :show-file-list="false"
                  accept="image/png,image/jpg,image/jpeg"
                >
                  <el-image v-if="form.vegetableImg" :src="form.vegetableImg" fit="fill" style="width: 150px; height: 150px" />
                  <el-button v-loading="uploadLoading" size="small" type="primary">{{ $t('pages.gameConfig.upload.clickUpload') }}</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.pizzaIcon')" prop="pizzaImg">
                <el-upload
                  class="upload-demo"
                  action=""
                  :http-request="httpRequestPizz"
                  :show-file-list="false"
                  accept="image/png,image/jpg,image/jpeg"
                >
                  <el-image v-if="form.pizzaImg" :src="form.pizzaImg" fit="fill" style="width: 150px; height: 150px" />
                  <el-button v-loading="uploadPizzLoading" size="small" type="primary">{{ $t('pages.gameConfig.upload.clickUpload') }}</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.wagerConfig')" prop="code">
                <el-input
                  v-model.trim="form.wager"
                  :placeholder="$t('pages.gameConfig.fruit.wagerConfig')"
                  style="width: 250px;"
                  maxlength="20"
                  show-word-limit
                />
                <span>{{ $t('pages.gameConfig.fruit.wagerTip') }}</span>
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.vegetableLotteryProfit')" prop="vegetableLotteryProfit">
                <el-input
                  v-model.trim="form.vegetableLotteryProfit"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.vegetableLotteryProfit')"
                />
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.vegetableNumber')" prop="vegetableNumber">
                <el-input
                  v-model.trim="form.vegetableNumber"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.vegetableNumber')"
                />
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.pizzaLotteryProfit')" prop="pizzaLotteryProfit">
                <el-input-number
                  v-model.trim="form.pizzaLotteryProfit"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.pizzaLotteryProfit')"
                />
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.pizzaNumber')" prop="pizzaNumber">
                <el-input
                  v-model.trim="form.pizzaNumber"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.pizzaNumber')"
                />
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.luckyWheelReturn')" prop="code">
                <el-input-number
                  v-model="form.lossRatio"
                  controls-position="right"
                  style="width: 150px;"
                  :min="0"
                  :max="9999"
                  :precision="2"
                  :placeholder="$t('pages.gameConfig.placeholder.min')"
                />% -
                <el-input-number
                  v-model="form.profitRatio"
                  controls-position="right"
                  style="width: 150px;"
                  :min="0"
                  :max="9999"
                  :precision="2"
                  :placeholder="$t('pages.gameConfig.placeholder.max')"
                />% <span> {{ $t('pages.gameConfig.fruit.returnRateTip') }}</span>
              </el-form-item>

              <el-form-item :label="$t('pages.gameConfig.fruit.todayLossLottery')" prop="pizzaNumber">
                <el-input
                  v-model="form.todayLossLottery"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.todayLossLotteryPlaceholder')"
                />
              </el-form-item>
              <el-form-item :label="$t('pages.gameConfig.fruit.lossRatioLottery')" prop="pizzaNumber">
                <el-input-number
                  v-model="form.lossRatioLottery"
                  controls-position="right"
                  style="width: 150px;"
                  :precision="2"
                  :min="0"
                  :max="9999"
                  :placeholder="$t('pages.gameConfig.fruit.lossRatioPlaceholder')"
                />%<span> {{ $t('pages.gameConfig.fruit.defaultNinetyPercent') }}</span>
              </el-form-item>

              <el-form-item :label="$t('pages.gameConfig.fruit.hotBetAmount')" prop="pizzaNumber">
                <el-input
                  v-model.trim="form.hotBetAmount"
                  v-number
                  controls-position="right"
                  style="width: 150px;"
                  :min="0"
                  :max="99999999"
                  :placeholder="$t('pages.gameConfig.fruit.hotBetAmount')"
                /><span style="margin-left: 10px;">{{ $t('pages.gameConfig.fruit.showHot') }}</span>
              </el-form-item>
            </el-form>
          </div>
          <div class="drawer-footer">
            <el-button type="primary" @click="submitForm()">{{ $t('common.save') }}</el-button>
            <el-button @click="handleClose()">{{ $t('common.cancel') }}</el-button>
          </div>
        </el-row></div>
    </el-dialog>

  </div>
</template>

<script>
import { prizeList, addPrize, updatePrize, getGameFruitRule, updateGameFruitRule } from '@/api/game'
import { getElementUiUploadFile } from '@/utils'
function getFormData() {
  return {
    id: '',
    wager: '',
    // 蔬菜圖片.
    vegetableImg: '',
    // 蔬菜开奖盈利.
    vegetableLotteryProfit: '',
    // 蔬菜开奖次数.
    vegetableNumber: '',
    // 披萨图片
    pizzaImg: '',
    // 披萨开奖盈利.
    pizzaLotteryProfit: '',
    // 披萨开奖次数.
    pizzaNumber: '',
    // 返奖率最小值(例如为0.98:1-0.98=亏损率).
    lossRatio: '',
    // 返奖率最打值（例如为1.05:1.05-1=盈利率）.
    profitRatio: '',
    //  当日亏损多少得奖.
    todayLossLottery: '',
    // 亏损率百分之多少得奖.
    lossRatioLottery: '',
    // 单项奖下注多少显示热门
    hotBetAmount: '',
    // 游戏规则.
    rule: ''
  }
}

function getPrizeData() {
  return {
    id: '',
    prizeName: '',
    type: 1,
    prizeImg: '',
    award: '',
    prob: '',
    sort: ''
  }
}
export default {
  name: 'ConfigData',
  props: {
    code: {
      type: String,
      require: false,
      default: () => ''
    },
    sysOrigin: {
      type: String,
      require: false,
      default: () => ''
    }
  },
  data() {
    const commonRules = [{ required: true, message: this.$t('pages.gameConfig.validation.required'), trigger: 'blur' }]
    return {
      list: [],
      listQuery: {
        sysOrigin: 'HALAR'
      },
      isOpen: false,
      innerVisible: false,
      coverFileList: [],
      prize: getPrizeData(),
      textOptTitle: '',
      form: getFormData(),
      submitLoading: false,
      prizeLoading: false,
      uploadLoading: false,
      uploadPizzLoading: false,
      coverUploadLoading: false,
      rules: {
        prizeName: commonRules,
        type: commonRules,
        prizeImg: commonRules,
        award: commonRules,
        prob: commonRules,
        sort: commonRules
      },
      configRules: {
        wager: commonRules,
        vegetableImg: commonRules,
        vegetableLotteryProfit: commonRules,
        vegetableNumber: commonRules,
        pizzaImg: commonRules,
        pizzaLotteryProfit: commonRules,
        pizzaNumber: commonRules,
        lossRatio: commonRules,
        profitRatio: commonRules,
        todayLossLottery: commonRules,
        lossRatioLottery: commonRules,
        hotBetAmount: commonRules
      },
      listLoading: true
    }
  },
  computed: {
    isShowCoverUpload() {
      return !this.prize.prizeImg
    }
  },
  watch: {
    form: {
      handler(newVal) {
        if (newVal) {
          if (!newVal) {
            return
          }
          if (newVal) {
            this.renderData()
            this.initdata()
          }
        }
      },
      immediate: true
    },
    innerVisible: {
      handler(val) {
        if (val) {
          this.coverFileList = getElementUiUploadFile(this.prize.prizeImg)
        }
      }
    }
  },
  methods: {
    renderData() {
      const that = this
      that.listLoading = true
      prizeList({ sysOrigin: this.sysOrigin }).then(res => {
        const { body } = res
        // that.form.code = 'GAME_FRUIT'
        if (body && body.length) {
          console.log(111)
          that.list = body
          if (that.list.length < 8) {
            for (let index = 0; index <= 8 - that.list.length; index++) {
              that.list.push({})
            }
          }
        } else {
          that.list = [{}, {}, {}, {}, {}, {}, {}, {}]
          console.log(222)
        }
        that.listLoading = false
      })
    },
    initdata() {
      getGameFruitRule({ sysOrigin: this.sysOrigin }).then(res => {
        const that = this
        that.listLoading = true
        const { body } = res
        // that.form.code = 'GAME_FRUIT'
        if (body) {
          that.form = Object.assign(that.form, body)
          that.form.lossRatio = Number.isInteger(that.form.lossRatio * 100) ? Math.trunc(that.form.lossRatio * 100)
            : (that.form.lossRatio * 100).toFixed(4)
          that.form.profitRatio = Number.isInteger(that.form.profitRatio * 100) ? Math.trunc(that.form.profitRatio * 100)
            : (that.form.profitRatio * 100).toFixed(4)
          that.form.lossRatioLottery = Number.isInteger(that.form.lossRatioLottery * 100) ? Math.trunc(that.form.lossRatioLottery * 100)
            : (that.form.lossRatioLottery * 100).toFixed(4)
        }
        that.listLoading = false
      })
    },
    submitForm() {
      const that = this
      that.$refs.configForm.validate(valid => {
        if (valid) {
          const configData = that.form
          const isPass = this.checkSubmitData(configData)
          if (!isPass) {
            return
          }
          that.form.lossRatio = (that.form.lossRatio / 100).toFixed(4)
          that.form.profitRatio = (that.form.profitRatio / 100).toFixed(4)
          that.form.lossRatioLottery = (that.form.lossRatioLottery / 100).toFixed(4)
          that.submitLoading = true
          updateGameFruitRule(that.form).then(res => {
            if (res.status) {
              that.$opsMessage.success()
              that.$emit('success', Object.assign({}, that.formData))
              that.handleClose()
            }
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    checkSubmitData(configData) {
      console.log(configData.wager)
      if (!configData.wager || configData.wager.split(',').length !== 4) {
        this.$opsMessage.fail(this.$t('pages.gameConfig.fruit.message.invalidWagerUnit'))
        return false
      }
      const wagers = configData.wager.split(',')

      console.log('wagers', wagers)
      let isInt = true
      wagers.forEach(element => {
        if (isNaN(element) && isInt) {
          isInt = false
        }
      })
      if (!isInt) {
        this.$opsMessage.fail(this.$t('pages.gameConfig.fruit.message.wagerIntegerOnly'))
        return false
      }

      if (!configData.lossRatio || !configData.profitRatio) {
        this.$opsMessage.fail(this.$t('pages.gameConfig.fruit.message.returnRateRequired'))
        return false
      }

      if (configData.lossRatio >= configData.profitRatio) {
        this.$opsMessage.fail(this.$t('pages.gameConfig.fruit.message.returnRateMinLessThanMax'))
        return false
      }
      return true
    },
    httpRequest(file) {
      const that = this
      that.uploadLoading = true
      this.$simpleUploadFlie(file).then(res => {
        that.uploadLoading = false
        that.form.vegetableImg = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.uploadLoading = false
      })
    },
    httpRequestPizz(file) {
      const that = this
      that.uploadPizzLoading = true
      this.$simpleUploadFlie(file).then(res => {
        that.uploadPizzLoading = false
        that.form.pizzaImg = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.uploadPizzLoading = false
      })
    },
    uploadCover(file) {
      const that = this
      that.coverUploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.other).then(res => {
        that.coverUploadLoading = false
        that.prize.prizeImg = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.coverUploadLoading = false
      })
    },
    handleCoverFileRemove(file, fileList) {
      this.prize.prizeImg = ''
      this.coverUploadLoading = false
    },
    handleUpdate(row) {
      this.prize = Object.assign(this.prize, row)
      this.prize.prob = !this.prize ? 0 : Math.abs(this.prize.prob * 100)
      this.innerVisible = true
    },
    closePrizeDialog() {
      this.innerVisible = false
      this.prize = getPrizeData()
    },
    handleClose() {
      this.isOpen = false
      this.$emit('close')
    },
    submitPrize() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        that.prize.prob = (that.prize.prob / 100).toFixed(4)
        const submitForm = Object.assign({}, that.prize)
        that.prizeLoading = true
        if (that.prize.id) {
          updatePrize(submitForm).then(res => {
            this.closePrizeDialog()
            this.renderData()
            that.prizeLoading = false
          }).catch(er => {
            that.prizeLoading = false
          })
          return
        }
        addPrize(submitForm).then(res => {
          this.closePrizeDialog()
          this.renderData()
          that.prizeLoading = false
        }).catch(er => {
          that.prizeLoading = false
          that.$emit('fial', er)
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.form-contetn {
    max-height: 550px;
    overflow: auto;
}
/* 使用字体系列和字体大小 */
.custom-font {
            font-family: Arial, sans-serif;
            font-size: 18px;
            font-weight: bold;
        }

        /* 使用字体粗细 */
</style>
