<template>
  <div class="app-container">
    <el-dialog
      v-loading="listLoading"
      :title="$t('pages.luckyBoxStandardConfig.dialog.probabilityTitle')"
      :visible="isDialog"
      :modal-append-to-body="true"
      :append-to-body="true"
      :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:820px;margin: 0rem 10px;margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span>{{ $t('pages.luckyBoxStandardConfig.probability.sort', { value: item.sort }) }}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="saveData(item)">{{ $t('pages.luckyBoxStandardConfig.action.save') }}</el-button>
          </div>
          <div style="padding-bottom: 20px;">
            <el-alert
              v-if="10000 - item.sumProbability > 0"
              :title="$t('pages.luckyBoxStandardConfig.probability.remaining', { value: 10000 - item.sumProbability })"
              type="warning"
              :closable="false"
            />
            <el-alert
              v-else-if="10000 == item.sumProbability"
              :title="$t('pages.luckyBoxStandardConfig.probability.completed')"
              type="success"
              :closable="false"
            />
            <el-alert
              v-else
              :title="$t('pages.luckyBoxStandardConfig.probability.exceeded', { value: item.sumProbability - 10000 })"
              type="error"
              :closable="false"
            />
            <el-alert
              v-if="10000 - item.sumLuckyProbability > 0"
              :title="$t('pages.luckyBoxStandardConfig.probability.luckyRemaining', { value: 10000 - item.sumLuckyProbability })"
              type="warning"
              :closable="false"
            />
            <el-alert
              v-else-if="10000 == item.sumLuckyProbability"
              :title="$t('pages.luckyBoxStandardConfig.probability.luckyCompleted')"
              type="success"
              :closable="false"
            />
            <el-alert
              v-else
              :title="$t('pages.luckyBoxStandardConfig.probability.luckyExceeded', { value: item.sumLuckyProbability - 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="$t('pages.luckyBoxStandardConfig.form.quantity')" class="gift-probability-label">
                <el-input v-model.trim="item.frequency" class="gift-probability-config" oninput="value=value.replace(/[^0-9.]/g,'')" />
              </el-form-item>
              <el-form-item :label="$t('pages.luckyBoxStandardConfig.form.gold')" class="gift-probability-label">
                <el-input v-model.trim="item.consumptionGold" class="gift-probability-config" oninput="value=value.replace(/[^0-9.]/g,'')" />
              </el-form-item>
            </el-form>
          </div>
          <el-divider>{{ $t('pages.luckyBoxStandardConfig.section.probability') }}</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: 30px;">{{ index1 + 1 }}</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="$t('pages.luckyBoxStandardConfig.placeholder.defaultProbability')" @input="calculateProbability(item)" /></div>
                      <div style="width: 130px;color:#f78e8e;margin-left: 0.3rem;"><el-input v-model.trim="item1.luckyProbability" oninput="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.luckyProbability')" @input="calculateProbability(item)" /></div>
                      <div style="width: 130px;color:#f78e8e;margin-left: 0.3rem;">
                        <el-select v-model="item1.giftConfigId" v-loading="loading" :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.select')" style="width:100%;">
                          <el-option
                            v-for="(item10, index10) in mapGiftConfig"
                            :key="index10"
                            :label="item10.name"
                            :value="item10.value"
                          />
                        </el-select>
                      </div>
                      <div style="width: 130px;color:#f78e8e;margin-left: 0.3rem;"><el-input v-model.trim="item1.quantity" oninput="value=value.replace(/[^0-9.]/g,'')" :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.stock')" /></div>
                      <div style="width: 30px;text-align: left; padding-left: 10px;"><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: 240px;">
                            <el-form-item
                              :prop="'tmpConfigList.' + index2 + '.probability'"
                              :rules="requiredRule"
                            >
                              <span><el-input v-model="item2.probability" v-number :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.probabilityExample')" oninput="value=value.replace(/[^0-9.]/g,'')" /></span>
                            </el-form-item>
                          </div>
                          <div style="width: 240px; margin: 0rem 0.1rem;">
                            <el-form-item
                              :prop="'tmpConfigList.' + index2 + '.luckyProbability'"
                              :rules="requiredRule"
                            >
                              <span><el-input v-model="item2.luckyProbability" :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.luckyProbability')" 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 + '.giftConfigId'"
                              :rules="requiredRule"
                            >
                              <el-select v-model="item2.giftConfigId" v-loading="loading" :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.relationGift')" style="width:100%;">
                                <el-option
                                  v-for="(item9, index9) in mapGiftConfig"
                                  :key="index9"
                                  :label="item9.name"
                                  :value="item9.value"
                                />
                              </el-select>
                            </el-form-item>
                          </div>
                          <div style="width: 120px; margin: 0rem 0.1rem;">
                            <el-form-item
                              :prop="'tmpConfigList.' + index2 + '.quantity'"
                              :rules="requiredRule"
                            >
                              <span><el-input v-model="item2.quantity" :placeholder="$t('pages.luckyBoxStandardConfig.placeholder.stock')" 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 style="text-align: center;">
                    <el-button type="text" @click="addContent(index, item)"><i class="el-icon-circle-plus" />{{ $t('pages.luckyBoxStandardConfig.action.addProbabilityDetail') }}</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-card>
      </div>
      <el-alert
        :title="$t('pages.luckyBoxStandardConfig.alert.probabilityRuleTitle')"
        type="warning"
        :description="$t('pages.luckyBoxStandardConfig.alert.probabilityRuleDescription')"
        show-icon
        :closable="false"
      />
      <el-divider>{{ $t('pages.luckyBoxStandardConfig.section.giftInfo') }}</el-divider>
      <div>
        <el-table
          v-loading="giftListLoading"
          :data="giftDataList"
          element-loading-text="Loading"
          fit
          highlight-current-row
        >
          <el-table-column type="index" width="50" label="No" />
          <el-table-column prop="sysOrigin" :label="$t('pages.luckyBoxStandardConfig.table.platform')" align="center" width="280" />
          <el-table-column prop="name" :label="$t('pages.luckyBoxStandardConfig.table.name')" align="center" width="280" />
          <el-table-column prop="giftCandy" :label="$t('pages.luckyBoxStandardConfig.table.gold')" align="center" width="280" />
          <el-table-column :label="$t('pages.luckyBoxStandardConfig.table.cover')" align="center">
            <template slot-scope="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.photoUrl"
                :preview-src-list="[scope.row.photoUrl]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" :label="$t('pages.luckyBoxStandardConfig.table.createdAt')" align="center" width="300">
            <template slot-scope="scope">
              {{ scope.row.createTime | dateFormat }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getGameLuckyBoxStandardDetailsConfig, addGameLuckyBoxStandardDetailsConfig, mapLuckyBoxGiftMap, getGameLuckyBoxGiftConfig } from '@/api/game-lucky-box-config'
import { mapGetters } from 'vuex'
export default {
  name: 'LuckyBoxProbabilityConfigEdit',
  props: {
    standardId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      disableAddContent: false,
      submitLoading: false,
      mapGiftConfig: [],
      configList: [
        { id: '', standardId: '', consumptionGold: '', frequency: '', sysOrigin: '', sumProbability: 0, sumLuckyProbability: 0, sort: 1, formInfo: {
          tmpConfigList: [],
          probabilityDetailsConfigList: []
        }},
        { id: '', standardId: '', consumptionGold: '', frequency: '', sysOrigin: '', sumProbability: 0, sumLuckyProbability: 0, sort: 2, formInfo: {
          tmpConfigList: [],
          probabilityDetailsConfigList: []
        }},
        { id: '', standardId: '', consumptionGold: '', frequency: '', sysOrigin: '', sumProbability: 0, sumLuckyProbability: 0, sort: 3, formInfo: {
          tmpConfigList: [],
          probabilityDetailsConfigList: []
        }}],
      submitDataInfo: {
        gameLuckyBoxTimeConfig: { id: '', standardId: '', consumptionGold: '', frequency: '', sysOrigin: '', sort: '' },
        gameLuckyBoxProbabilityConfigs: []
      },
      listQuery: {
        standardId: '',
        sysOrigin: 'HALAR'
      },
      isDialog: true,
      giftListLoading: true,
      giftDataList: [],
      listLoading: false
    }
  },
  computed: {
    requiredRule() {
      return { required: true, message: this.$t('pages.luckyBoxStandardConfig.validation.notEmpty'), trigger: 'blur' }
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])

  },
  watch: {
    standardId: {
      handler(newVal) {
        this.listQuery.standardId = newVal
        this.probabilityConfig()
        // 加载礼物配置
        this.loadMapLuckyBoxGiftConfig()
      },
      immediate: true
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderGiftData()
  },
  methods: {
    probabilityConfig() {
      const that = this
      that.listLoading = true
      getGameLuckyBoxStandardDetailsConfig(that.listQuery).then(res => {
        const { body } = res
        const dataList = body || []

        if (dataList) {
          that.configList.forEach((configItem, configIndex) => {
            const items = dataList.filter(item_ => item_.sort === configItem.sort)
            if (items.length > 0) {
              const item = items[0]
              var probabilityDetails_ = 0
              var luckyProbabilityDetails_ = 0
              item.gameLuckyBoxProbabilityConfigs.forEach(probabilityDetails => {
                probabilityDetails_ += probabilityDetails.probability
                luckyProbabilityDetails_ += probabilityDetails.luckyProbability
              })
              const dataTmp = {
                id: item.id,
                standardId: item.standardId,
                frequency: item.frequency,
                consumptionGold: item.consumptionGold,
                sysOrigin: item.sysOrigin,
                sort: item.sort,
                sumProbability: probabilityDetails_,
                sumLuckyProbability: luckyProbabilityDetails_,
                formInfo: {
                  tmpConfigList: [],
                  probabilityDetailsConfigList: item.gameLuckyBoxProbabilityConfigs
                }
              }
              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.frequency || parseInt(item.frequency) <= 0) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.quantityPositiveInteger'))
        return
      }
      if (!item.consumptionGold || parseInt(item.consumptionGold) <= 0) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.goldPositiveInteger'))
        return
      }
      if (item.formInfo.probabilityDetailsConfigList.length <= 0) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.configureProbabilityDetails'))
        return
      }
      var probability_ = 0
      var probabilityValue = 0
      var luckyProbability_ = 0
      var luckyProbabilityValue = 0
      item.formInfo.probabilityDetailsConfigList.forEach(detailsConfig => {
        probabilityValue = parseInt(detailsConfig.probability)
        probability_ += parseInt(detailsConfig.probability)
        luckyProbabilityValue = parseInt(detailsConfig.luckyProbability)
        luckyProbability_ += parseInt(detailsConfig.luckyProbability)
      })
      if (probability_ !== 10000) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.probabilityMustEqual10000'))
        return
      }
      if (luckyProbability_ !== 10000) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.luckyProbabilityMustEqual10000'))
        return
      }
      if (probabilityValue === 0) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.probabilityGreaterThanZero'))
        return
      }
      if (luckyProbabilityValue === 0) {
        that.$opsMessage.fail(this.$t('pages.luckyBoxStandardConfig.message.luckyProbabilityGreaterThanZero'))
        return
      }
      that.listLoading = true
      that.submitDataInfo.gameLuckyBoxProbabilityConfigs = item.formInfo.probabilityDetailsConfigList
      that.submitDataInfo.gameLuckyBoxTimeConfig.id = item.id
      that.submitDataInfo.gameLuckyBoxTimeConfig.frequency = item.frequency
      that.submitDataInfo.gameLuckyBoxTimeConfig.consumptionGold = item.consumptionGold
      that.submitDataInfo.gameLuckyBoxTimeConfig.sysOrigin = that.listQuery.sysOrigin
      that.submitDataInfo.gameLuckyBoxTimeConfig.standardId = that.listQuery.standardId
      that.submitDataInfo.gameLuckyBoxTimeConfig.sort = item.sort
      this.$confirm(this.$t('pages.luckyBoxStandardConfig.confirm.saveMessage'), this.$t('pages.luckyBoxStandardConfig.confirm.saveTitle'), {
        type: 'warning'
      }).then(() => {
        addGameLuckyBoxStandardDetailsConfig(that.submitDataInfo).then(res => {
          that.listLoading = false
          this.$opsMessage.success()
          this.probabilityConfig()
        }).catch(er => {
          that.listLoading = false
          this.$opsMessage.fail()
          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
      var sumLuckyProbability = 0
      item.formInfo.probabilityDetailsConfigList.forEach(details => {
        if (details.probability) {
          sumProbability += parseInt(details.probability)
        }
        if (details.luckyProbability) {
          sumLuckyProbability += parseInt(details.luckyProbability)
        }
      })
      item.sumProbability = sumProbability
      item.sumLuckyProbability = sumLuckyProbability
    },
    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({
          luckyProbability: '',
          probability: '',
          quantity: '',
          giftConfigId: ''
        })
      })
    },
    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({
          luckyProbability: item.luckyProbability,
          quantity: item.quantity,
          probability: item.probability,
          giftConfigId: item.giftConfigId
        })
        itemSuper.formInfo.tmpConfigList = []
        that.calculateProbability(itemSuper)
      })
    },
    loadMapLuckyBoxGiftConfig() {
      const that = this
      that.loading = true
      mapLuckyBoxGiftMap(that.listQuery).then(res => {
        that.mapGiftConfig = res.body || []
        that.loading = false
      }).catch(er => {
        that.loading = false
      })
    },
    renderGiftData() {
      const that = this
      that.giftListLoading = true
      getGameLuckyBoxGiftConfig(that.listQuery).then(res => {
        const { body } = res
        that.giftDataList = body
        that.giftListLoading = false
      }).catch(er => {
        that.giftListLoading = false
      })
    }
  }
}
</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>
