<template>
  <div class="app-container">
    <el-dialog
      v-loading="listLoading"
      title="概率配置"
      :visible="isDialog"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :fullscreen="true"
      top="20px"
    >
      <div style="display: inline-flex; flex-direction: row; justify-content: space-around;">
        <el-card v-for="(item, index) in configList" :key="index" class="box-card" style="width:500px;margin: 0rem 10px;margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>数量:{{ item.giftQuantity }}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="saveData(item)">保存</el-button>
          </div>
          <div style="padding-bottom: 20px;">
            <el-alert
              v-if="10000 - item.sumProbability > 0"
              :title="'概率还差' + (10000 - item.sumProbability) + '凑满10000'"
              type="warning"
              :closable="false"
            />
            <el-alert
              v-else-if="10000 == item.sumProbability"
              title="概率已拼凑完整"
              type="success"
              :closable="false"
            />
            <el-alert
              v-else
              :title="'概率已超过' + (item.sumProbability - 10000) + ',请调整！'"
              type="error"
              :closable="false"
            />
          </div>
          <div class="gift-probability-form">
            <el-form :ref="'configList' + index" :model="item" label-width="140px">
              <el-form-item label="用户亏钱连击次数" class="gift-probability-label">
                <el-input v-model.trim="item.comboIncrements" class="gift-probability-config" oninput="value=value.replace(/[^0-9.]/g,'')" />
              </el-form-item>
              <el-form-item label="累计送礼次数" class="gift-probability-label">
                <el-input v-model.trim="item.giftGiveTotal" class="gift-probability-config" oninput="value=value.replace(/[^0-9.]/g,'')" />
              </el-form-item>
              <el-form-item label="总签数" class="gift-probability-label">
                <el-input v-model.trim="item.signTotal" class="gift-probability-config" oninput="value=value.replace(/[^0-9.]/g,'')" />
              </el-form-item>
            </el-form>
          </div>
          <el-divider>概率</el-divider>
          <div class="luck-gift-probability-details-config-edit">
            <div class="form-edit">
              <el-form :ref="'formInfo' + index" :model="item.formInfo" label-width="80px" style="margin-right:50px;">
                <div class="dr-content">
                  <div ref="probabilityDetailsContent">
                    <div
                      v-for="(item1, index1) in item.formInfo.probabilityDetailsConfigList"
                      :key="index1"
                      style="display: flex;
                            flex-direction: row;
                            justify-content: space-around;
                            align-items: flex-start;margin: auto;
                            cursor:pointer;line-height:30px;align-items: center;"
                    >
                      <div class="sort" style="width: 20px;">{{ index1 + 1 }}</div>
                      <div style="width: 100px;margin-left: 0.3rem;"><el-input v-model.trim="item1.multiple" v-number placeholder="倍数" /></div>
                      <div style="width: 130px;color:#f78e8e;margin-left: 0.3rem;"><el-input v-model.trim="item1.probability" oninput="value=value.replace(/[^0-9.]/g,'')" placeholder="概率" @input="calculateProbability(item)" /></div>
                      <div style="width: 130px;margin-left: 0.3rem;">签数:{{ parseInt(item1.probability / 10000 * item.signTotal) }}</div>
                      <div style="width: 30px;text-align: left;"><i class="del el-icon-delete-solid" @click="deleteUpdateItem(item,index1)" /></div>
                    </div>
                  </div>
                </div>
                <el-form-item>
                  <div class="content-list">
                    <el-row v-for="(item2, index2) in item.formInfo.tmpConfigList" :key="index2">
                      <div class="content-box">
                        <div
                          style="display: flex;
                            flex-direction: row;
                            justify-content: space-around;
                            align-items: flex-start;margin: 0.1rem auto;"
                        >
                          <div style="width: 110px;">
                            <el-form-item
                              :prop="'tmpConfigList.' + index2 + '.multiple'"
                              :rules="{ required: true, message: '不可为空', trigger: 'blur'}"
                            >
                              <span><el-input v-model="item2.multiple" v-number placeholder="倍数" oninput="value=value.replace(/[^0-9.]/g,'')" /></span>
                            </el-form-item>
                          </div>
                          <div style="width: 215px; margin: 0rem 0.1rem;">
                            <el-form-item
                              :prop="'tmpConfigList.' + index2 + '.probability'"
                              :rules="{ required: true, message: '不可为空', trigger: 'blur'}"
                            >
                              <span><el-input v-model="item2.probability" placeholder="概率(1000就是10%)" oninput="value=value.replace(/[^0-9.]/g,'')" /></span>
                            </el-form-item>
                          </div>
                          <div style="width: 100px;">
                            <i class="del el-icon-delete-solid" @click="deleteItem(item)" />
                            <i class="save el-icon-success" @click="submitItem(index, item2, item)" />
                          </div>
                        </div>
                      </div>
                    </el-row>

                  </div>
                  <div>
                    <el-button type="text" @click="addContent(index, item)"><i class="el-icon-circle-plus" />添加概率详情</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>
      </div>
      <el-alert
        title="幸运礼物规则-必读"
        type="warning"
        description="规格概率配置，5个数量配置需要配置完整，才可关联幸运礼物！"
        show-icon
      />
    </el-dialog>
  </div>
</template>

<script>

import { addLuckyGiftProbabilityInfoConfig, gameLuckyGiftProbabilityInfoConfig } from '@/api/game-lucky-gift-config'
import { mapGetters } from 'vuex'
export default {
  name: 'LuckyGiftProbabilityConfigEdit',
  props: {
    standardInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      disableAddContent: false,
      submitLoading: false,
      configList: [{ id: '', standardId: '', giftQuantity: 1, comboIncrements: '', giftGiveTotal: '', signTotal: '', sysOrigin: '', sort: 0, sumProbability: 0, formInfo: {
        tmpConfigList: [],
        probabilityDetailsConfigList: []
      }},
      { id: '', standardId: '', giftQuantity: 7, comboIncrements: '', giftGiveTotal: '', signTotal: '', sysOrigin: '', sort: 1, sumProbability: 0, formInfo: {
        tmpConfigList: [],
        probabilityDetailsConfigList: []
      }},
      { id: '', standardId: '', giftQuantity: 77, comboIncrements: '', giftGiveTotal: '', signTotal: '', sysOrigin: '', sort: 2, sumProbability: 0, formInfo: {
        tmpConfigList: [],
        probabilityDetailsConfigList: []
      }},
      { id: '', standardId: '', giftQuantity: 177, comboIncrements: '', giftGiveTotal: '', signTotal: '', sysOrigin: '', sort: 3, sumProbability: 0, formInfo: {
        tmpConfigList: [],
        probabilityDetailsConfigList: []
      }},
      { id: '', standardId: '', giftQuantity: 777, comboIncrements: '', giftGiveTotal: '', signTotal: '', sysOrigin: '', sort: 4, sumProbability: 0, formInfo: {
        tmpConfigList: [],
        probabilityDetailsConfigList: []
      }}],
      submitDataInfo: {
        gameLuckyGiftProbability: { id: '', standardId: '', giftQuantity: '', comboIncrements: '', giftGiveTotal: '', signTotal: '', sysOrigin: '', sort: '' },
        gameLuckyGiftProbabilityDetails: []
      },
      listQuery: {
        standardId: '',
        sysOrigin: 'HALAR'
      },
      isDialog: true,
      listLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms'])

  },
  watch: {
    standardInfo: {
      handler(newVal) {
        console.log(newVal)
        this.listQuery.standardId = newVal.id
        this.listQuery.sysOrigin = newVal.sysOrigin
        this.probabilityConfig()
      },
      immediate: true
    }
  },
  methods: {
    probabilityConfig() {
      const that = this
      that.listLoading = true
      gameLuckyGiftProbabilityInfoConfig(that.listQuery).then(res => {
        const { body } = res
        const dataList = body || []

        if (dataList) {
          that.configList.forEach((configItem, configIndex) => {
            const items = dataList.filter(item_ => item_.giftQuantity === configItem.giftQuantity)
            if (items.length > 0) {
              const item = items[0]
              var probabilityDetails_ = 0
              item.gameLuckyGiftProbabilityDetails.forEach(probabilityDetails => {
                probabilityDetails_ += probabilityDetails.probability
              })
              const dataTmp = {
                id: item.id,
                standardId: item.standardId,
                giftQuantity: item.giftQuantity,
                comboIncrements: item.comboIncrements,
                giftGiveTotal: item.giftGiveTotal,
                signTotal: item.signTotal,
                sysOrigin: item.sysOrigin,
                sort: item.sort,
                sumProbability: probabilityDetails_,
                formInfo: {
                  tmpConfigList: [],
                  probabilityDetailsConfigList: item.gameLuckyGiftProbabilityDetails
                }
              }
              that.configList.splice(configIndex, 1, dataTmp)
            }
          })
        }
        that.listLoading = false
      }).catch(er => {
        that.listLoading = false
      })
    },

    handleClose() {
      this.$emit('close')
    },
    saveData(item) {
      const that = this
      if (!item.comboIncrements || item.comboIncrements < 0) {
        that.$message.error('连击次数不能为负数')
        return
      }
      if (!item.giftGiveTotal || item.giftGiveTotal < 0) {
        that.$message.error('累计送礼次数不能为负数')
        return
      }
      if (!item.signTotal || item.signTotal <= 0) {
        that.$message.error('总签数必须为大于的正整数')
        return
      }
      if (item.formInfo.probabilityDetailsConfigList.length <= 0) {
        that.$message.error('请配置概率详细')
        return
      }
      var probability_ = 0
      var signTotal_ = 0
      var probabilityValue = 0
      item.formInfo.probabilityDetailsConfigList.forEach(detailsConfig => {
        probabilityValue = parseInt(detailsConfig.probability)
        probability_ += parseInt(detailsConfig.probability)
        signTotal_ += parseInt((detailsConfig.probability / 10000) * item.signTotal)
      })
      if (probability_ !== 10000) {
        that.$message.error('概率必须等于10000')
        return
      }
      if (parseInt(signTotal_) !== parseInt(item.signTotal)) {
        that.$message.error('明细签数(' + signTotal_ + ')必须为等于总签数(' + item.signTotal + ')')
        return
      }
      if (probabilityValue === 0) {
        that.$message.error('概率必须大于0！')
        return
      }
      that.listLoading = true
      that.submitDataInfo.gameLuckyGiftProbabilityDetails = item.formInfo.probabilityDetailsConfigList
      that.submitDataInfo.gameLuckyGiftProbability.id = item.id
      that.submitDataInfo.gameLuckyGiftProbability.giftQuantity = item.giftQuantity
      that.submitDataInfo.gameLuckyGiftProbability.comboIncrements = item.comboIncrements
      that.submitDataInfo.gameLuckyGiftProbability.giftGiveTotal = item.giftGiveTotal
      that.submitDataInfo.gameLuckyGiftProbability.signTotal = item.signTotal
      that.submitDataInfo.gameLuckyGiftProbability.sort = item.sort
      that.submitDataInfo.gameLuckyGiftProbability.sysOrigin = that.listQuery.sysOrigin
      that.submitDataInfo.gameLuckyGiftProbability.standardId = that.listQuery.standardId
      this.$confirm('确认保存吗？', '如果继续保存，将会清除正在执行的数据！', {
        type: 'warning'
      }).then(() => {
        addLuckyGiftProbabilityInfoConfig(that.submitDataInfo).then(res => {
          that.listLoading = false
          that.$message.success('保存成功')
          this.probabilityConfig()
        }).catch(er => {
          that.listLoading = false
          that.$message.error('保存失败')
          this.probabilityConfig()
        })
      }).catch(() => {
        this.listLoading = false
      })
    },
    deleteItem(item) {
      item.formInfo.tmpConfigList = []
      this.calculateProbability(item)
    },
    deleteUpdateItem(item, index) {
      item.formInfo.probabilityDetailsConfigList.splice(index, 1)
      this.calculateProbability(item)
    },
    calculateProbability(item) {
      var sumProbability = 0
      item.formInfo.probabilityDetailsConfigList.forEach(details => {
        if (details.probability) {
          sumProbability += parseInt(details.probability)
        }
      })
      item.sumProbability = sumProbability
    },
    addContent(index, item) {
      const that = this

      that.$refs['formInfo' + index][0].validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        if (item.formInfo.tmpConfigList.length > 0) {
          return
        }

        item.formInfo.tmpConfigList.push({
          multiple: '',
          quantity: '',
          probability: ''
        })
      })
    },
    submitItem(index, item, itemSuper) {
      const that = this
      that.$refs['formInfo' + index][0].validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }

        itemSuper.formInfo.probabilityDetailsConfigList.push({
          multiple: item.multiple,
          quantity: item.quantity,
          probability: item.probability
        })
        itemSuper.formInfo.tmpConfigList = []
        that.calculateProbability(itemSuper)
      })
    }
  }
}
</script>
<style scoped lang="scss">
.app-container {
  .luck-gift-probability-details-config-edit {
    .form-edit {
      overflow: auto;
      .dr-content {
        padding: 5px 0px 5px 20px;
      }
      .sort {
        border-radius: 50%;
        width: 30px;
        height: 30px;
        background: #f7f6f5;
        margin: auto;
        text-align: center;
        line-height: 29px;
        font-weight: bold;
      }
      .del {
        font-size: 30px;
        color: #F56C6C;
        cursor: pointer;
      }
      .save {
        font-size: 30px;
        color: #FF9326;
        cursor: pointer;
      }
    }
  }
  .filter-container {
    .el-dropdown {
      vertical-align: top;
    }
    .el-dropdown + .el-dropdown {
      margin-left: 15px;
    }
    .el-icon-arrow-down {
      font-size: 12px;
    }
  }
  .form_ {
    display: flex;
    justify-content: space-around;
    flex-direction: row;
    align-items: center;
    text-align: center;
  }
}

  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 30%;
    margin-top: 10px;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }

  .clearfix:after {
      clear: both
  }
  .gift-probability-config{
    width: 75%;
  }
  .gift-probability-label{
    padding: 0px;
    text-align: left;
  }
  .table-column{
    padding: 0px;
  }
  .dialog-footer{
    font-size: medium;
    font-style: oblique;
    font-family: ui-rounded;
    color: rgb(255, 17, 0);
  }
</style>
