<template>
  <div class="app-container-region">
    <el-dialog
      :title="'游戏参数配置'"
      :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;">奖项配置</span>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          fit
          highlight-current-row
        >
          <el-table-column
            prop="sort"
            label="排序"
            width="100"
          />
          <el-table-column
            prop="prizeName"
            label="名称"
            width="120"
          />
          <el-table-column
            prop="prizeImg"
            label="图标"
            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="获得奖励倍数"
            width="120"
          />
          <el-table-column
            prop="prob"
            width="100"
            label="概率"
          >
            <template slot-scope="scope">
              {{ !scope.row.prob ? 0 : (scope.row.prob * 100).toFixed(2) }} %
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
              <el-button type="text" @click.native="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-dialog
        :title="'奖项配置'"
        :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="封面" 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="名称" prop="prizeName">
                <el-input v-model.trim="prize.prizeName" type="text" placeholder="请输入名称" minlength="1" maxlength="150" show-word-limit />
              </el-form-item>
              <el-form-item label="类型" prop="type">
                <el-select
                  v-model="prize.type"
                  placeholder="类型"
                  clearable
                  style="width:100%;"
                  class="filter-item"
                >
                  <el-option label="蔬菜" :value="1" />
                  <el-option label="披萨" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="获得奖励 X " prop="award">
                <el-input-number
                  v-model.trim="prize.award"
                  v-number
                  controls-position="right"
                  :min="0"
                  :max="99999999"
                  placeholder="请输入获得奖励"
                /><span> 倍</span>
              </el-form-item>
              <el-form-item label="概率" prop="prob">
                <el-input-number v-model="prize.prob" controls-position="right" :precision="2" :min="0" :max="99999" placeholder="概率" />%
              </el-form-item>
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model.trim="prize.sort" v-number :min="0" :max="99999" placeholder="降序排列(数字越大越靠前)" />
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" style="text-align: right;">
            <el-button @click="closePrizeDialog()">取消</el-button>
            <el-button type="primary" @click="submitPrize()">保存</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="蔬菜图标：" 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">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="披萨图标：" 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">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="下注金额配置" prop="code">
                <el-input
                  v-model.trim="form.wager"
                  placeholder="下注金额配置"
                  style="width: 250px;"
                  maxlength="20"
                  show-word-limit
                />
                <span>请用逗号隔开（例如：10,20.30.40）</span>
              </el-form-item>
              <el-form-item label="开出蔬菜拼盘盈利" prop="vegetableLotteryProfit">
                <el-input
                  v-model.trim="form.vegetableLotteryProfit"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  placeholder="开出蔬菜拼盘盈利"
                />
              </el-form-item>
              <el-form-item label="开出蔬菜拼盘次数" prop="vegetableNumber">
                <el-input
                  v-model.trim="form.vegetableNumber"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  placeholder="开出蔬菜拼盘次数"
                />
              </el-form-item>
              <el-form-item label="开出披萨拼盘盈利" prop="pizzaLotteryProfit">
                <el-input-number
                  v-model.trim="form.pizzaLotteryProfit"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  placeholder="开出披萨拼盘盈利"
                />
              </el-form-item>
              <el-form-item label="开出披萨拼盘次数" prop="pizzaNumber">
                <el-input
                  v-model.trim="form.pizzaNumber"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  placeholder="开出披萨拼盘次数"
                />
              </el-form-item>
              <el-form-item label="幸运转盘返奖" prop="code">
                <el-input-number
                  v-model="form.lossRatio"
                  controls-position="right"
                  style="width: 150px;"
                  :min="0"
                  :max="9999"
                  :precision="2"
                  placeholder="最小值"
                />% -
                <el-input-number
                  v-model="form.profitRatio"
                  controls-position="right"
                  style="width: 150px;"
                  :min="0"
                  :max="9999"
                  :precision="2"
                  placeholder="最大值"
                />% <span> （返奖率=平台支出/用户支出，默认：98-105%）</span>
              </el-form-item>

              <el-form-item label="当天亏损金额（充值榜补回）" prop="pizzaNumber">
                <el-input
                  v-model="form.todayLossLottery"
                  v-number
                  controls-position="right"
                  style="width: 250px;"
                  :min="0"
                  :max="99999999"
                  placeholder="当天亏损金额"
                />
              </el-form-item>
              <el-form-item label="亏损率（充值榜补回）" prop="pizzaNumber">
                <el-input-number
                  v-model="form.lossRatioLottery"
                  controls-position="right"
                  style="width: 150px;"
                  :precision="2"
                  :min="0"
                  :max="9999"
                  placeholder="亏损率"
                />%<span> （默认：90%）</span>
              </el-form-item>

              <el-form-item label="奖项下注金额达到" prop="pizzaNumber">
                <el-input
                  v-model.trim="form.hotBetAmount"
                  v-number
                  controls-position="right"
                  style="width: 150px;"
                  :min="0"
                  :max="99999999"
                  placeholder="奖项下注金额达到"
                /><span style="margin-left: 10px;">显示热门</span>
              </el-form-item>
            </el-form>
          </div>
          <div class="drawer-footer">
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="handleClose()">取消</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: '必填字段', 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('下注单位异常')
        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('下注单位只能为整数')
        return false
      }

      if (!configData.lossRatio || !configData.profitRatio) {
        this.$opsMessage.fail('返奖率不能为空')
        return false
      }

      if (configData.lossRatio >= configData.profitRatio) {
        this.$opsMessage.fail('返奖率最小值不能大于等于最大值')
        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>
