<template>
  <div class="template-form-edite">
    <el-drawer
      :title="textOptTitle"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div v-loading="submitLoading">
        <div class="drawer-form">
          <div class="blockquote blockquote-mini">{{ $t('pages.activityTemplateManage.section.basicInfo') }}</div>
          <el-alert
            v-if="isClose"
            :closable="false"
            type="info"
            show-icon
            style="margin-bottom: 10px;"
            :title="$t('pages.activityTemplateManage.message.endedNotEditable')"
          />
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item :label="$t('pages.activityTemplateManage.form.system')"> {{ sysOrigin }} </el-form-item>
            <el-form-item v-loading="loadingTemplateValueLoading" :label="$t('pages.activityTemplateManage.form.template')" prop="templateId">
              <el-select
                v-model="form.templateId"
                :placeholder="$t('pages.activityTemplateManage.placeholder.template')"
                style="width:100%;"
                class="filter-item"
                filterable
              >
                <el-option v-for="(item, index) in templateValues" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('pages.activityTemplateManage.form.time')" prop="startTime">
              <el-date-picker
                v-model="rangeDate"
                type="datetimerange"
                value-format="timestamp"
                style="width:100%;"
                :range-separator="$t('pages.activityTemplateManage.word.rangeSeparator')"
                :start-placeholder="$t('pages.activityTemplateManage.placeholder.startDate')"
                :end-placeholder="$t('pages.activityTemplateManage.placeholder.endDate')"
                clearable
              />
              <el-alert
                v-if="!isClose && isEndTimeLteNow"
                :closable="false"
                type="info"
                show-icon
                size="mini"
                style="margin-bottom: 10px;"
                :title="$t('pages.activityTemplateManage.message.expiredTimeWarning')"
              />
            </el-form-item>
            <el-form-item :label="$t('pages.activityTemplateManage.form.status')" prop="showcase">
              <el-select
                v-model="form.showcase"
                :placeholder="$t('pages.activityTemplateManage.placeholder.status')"
                style="width:100%;"
                class="filter-item"
              >
                <el-option :label="$t('pages.activityTemplateManage.word.offShelf')" :value="false" />
                <el-option :label="$t('pages.activityTemplateManage.word.onShelf')" :value="true" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('pages.activityTemplateManage.form.description')" prop="remark">
              <el-input v-model.trim="form.remark" resize="none" show-word-limit type="textarea" :rows="6" maxlength="200" />
            </el-form-item>
          </el-form>
          <div class="blockquote blockquote-mini">{{ $t('pages.activityTemplateManage.section.activityGift') }}</div>
          <div class="activity-gift flex-c">
            <div v-for="(item, index) in form.gifts" :key="index" class="gift-item">
              <div class="gift" @click="clickChangeGift(index)">
                <div class="tips">{{ $t('pages.activityTemplateManage.action.clickToChange') }}</div>
                <img v-if="item.id" :src="item.giftPhoto">
                <img v-else src="@/assets/default_img.png">
              </div>
              <div v-if="item.id" class="gift-amount flex-c">
                <img v-if="item.type === 'GOLD'" width="20" height="20" src="@/assets/gold_icon.png">
                <img v-if="item.type === 'DIAMOND'" width="20" height="20" src="@/assets/diamond_icon.png">
                {{ item.giftCandy }}
              </div>
              <div v-else class="gift-amount">{{ $t('pages.activityTemplateManage.placeholder.select') }}</div>
            </div>
          </div>
          <div class="blockquote blockquote-mini">{{ $t('pages.activityTemplateManage.section.rankingRewards') }}</div>
          <el-tabs v-model="activeName">
            <el-tab-pane :label="$t('pages.activityTemplateManage.section.prizeButton1')" name="but1">
              <reward-edit :sys-origin="sysOrigin" :rewards-group="form.butOneRewards" @change="rewards=> form.butOneRewards = rewards" />
            </el-tab-pane>
            <el-tab-pane :label="$t('pages.activityTemplateManage.section.prizeButton2')" name="but2">
              <reward-edit :sys-origin="sysOrigin" :rewards-group="form.butTwoRewards" @change="rewards=> form.butTwoRewards = rewards" />
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="drawer-footer">
          <el-button @click="handleClose()">{{ $t('pages.activityTemplateManage.action.cancel') }}</el-button>
          <el-button v-if="!isClose" type="primary" @click="submitForm()">{{ $t('pages.activityTemplateManage.action.save') }}</el-button>
        </div>
      </div>
    </el-drawer>

    <gift-select
      v-if="giftSelectVisible"
      :sys-origin="sysOrigin"
      @close="giftSelectVisible=false"
      @select="selectedGift"
    />
  </div>
</template>
<script>

import { addActivityConf, updateActivityConf, listTemplateValues } from '@/api/sys'
import { mapGetters } from 'vuex'
import GiftSelect from '@/components/data/GiftSelect'
import RewardEdit from './reward-edit'
import { deepClone } from '@/utils'
export default {
  components: { GiftSelect, RewardEdit },
  props: {
    sysOrigin: {
      type: String,
      default: ''
    },
    row: {
      type: Object,
      default: null
    }
  },
  data() {
    const commonRules = [{ required: true, message: this.$t('pages.activityTemplateManage.validation.requiredField'), trigger: 'blur' }]
    return {
      activeName: 'but1',
      giftSelectVisible: false,
      rangeDate: [],
      form: {
        id: '',
        sysOrigin: '',
        templateId: '',
        startTime: '',
        endTime: '',
        showcase: false,
        butOneRewards: [],
        butTwoRewards: [],
        gifts: [],
        remark: ''
      },
      submitLoading: false,
      rules: {
        sysOrigin: commonRules,
        startTime: commonRules,
        showcase: commonRules,
        templateId: commonRules
      },
      loadingTemplateValueLoading: false,
      templateValues: [],
      giftSelectedIndex: -1
    }
  },
  computed: {
    isEndTimeLteNow() {
      return this.form.endTime && new Date().getTime() >= this.form.endTime
    },
    isClose() {
      return this.row && this.row.status === 2
    },
    textOptTitle() {
      return this.row && this.row.id ? this.$t('pages.activityTemplateManage.action.edit') : this.$t('pages.activityTemplateManage.action.create')
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  watch: {
    row: {
      handler(val) {
        if (!val) {
          this.form.gifts = this.fillEmptyGfts(this.form.gifts, 3)
          return
        }

        const rowVal = deepClone(val)
        const form = rowVal.config

        if (form.startTime && form.endTime) {
          this.rangeDate = [form.startTime, form.endTime]
        }

        form.butOneRewards = rowVal.butOneRewards || []
        form.butTwoRewards = rowVal.butTwoRewards || []
        form.gifts = this.fillEmptyGfts(rowVal.gifts, 3)
        this.form = form
      },
      immediate: true
    },
    rangeDate: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.form.startTime = newVal[0]
          this.form.endTime = newVal[1]
          return
        }
        this.form.startTime = ''
        this.form.endTime = ''
      }
    }
  },
  created() {
    this.loadTemplateValues()
  },
  methods: {
    fillEmptyGfts(gifts, fillEmptuSize) {
      const giftList = deepClone(gifts || [])
      const fillSize = fillEmptuSize - giftList.length
      for (let index = 0; index < fillSize; index++) {
        giftList.push({})
      }
      return giftList
    },
    loadTemplateValues() {
      const that = this
      that.loadingTemplateValueLoading = true
      listTemplateValues().then(res => {
        that.loadingTemplateValueLoading = false
        that.templateValues = res.body || []
      }).catch(er => {
        that.loadingTemplateValueLoading = false
      })
    },

    handleClose() {
      this.$emit('close')
    },
    filterConvertRewards(rewards) {
      if (!rewards || rewards.length <= 0) {
        return []
      }
      return rewards.map(item => {
        return {
          rankRange: (item.rankRange || '').trim(),
          resourceGroupId: item.resourceGroupId
        }
      }).filter(item => {
        if (!item.rankRange || !item.resourceGroupId) {
          return false
        }
        const regNumber = /^\d+$/

        if (regNumber.test(item.rankRange)) {
          return true
        }

        const range = item.rankRange.split('~')
        if (!range || range.length <= 0) {
          return false
        }

        const rangeOne = String(range[0])
        if (!rangeOne) {
          return false
        }

        if (!regNumber.test(rangeOne)) {
          return false
        }

        const rangeTwo = String(range[1])
        if (!rangeTwo) {
          return false
        }

        if (!regNumber.test(rangeTwo)) {
          return false
        }

        if (Number(rangeOne) > Number(rangeTwo)) {
          return false
        }
        return true
      })
    },
    submitForm() {
      const that = this
      if (this.isClose) {
        that.$opsMessage.fail(that.$t('pages.activityTemplateManage.message.endedCannotEdit'))
        return
      }
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        const submitForm = deepClone(that.form)
        submitForm.giftIds = submitForm.gifts.filter(item => item && item.id).map(item => item.id)
        submitForm.gifts = null
        const tips = []
        if (!submitForm.giftIds || submitForm.giftIds.length < 3) {
          tips.push(that.$t('pages.activityTemplateManage.message.giftQuantityInsufficient'))
        }

        if (!submitForm.butOneRewards || submitForm.butOneRewards.length <= 0) {
          tips.push(that.$t('pages.activityTemplateManage.message.noButtonReward', { button: that.$t('pages.activityTemplateManage.section.prizeButton1') }))
        } else {
          submitForm.butOneRewards = that.filterConvertRewards(submitForm.butOneRewards)
        }
        if (submitForm.butOneRewards.length !== that.form.butOneRewards.length) {
          tips.push(that.$t('pages.activityTemplateManage.message.invalidButtonReward', { button: that.$t('pages.activityTemplateManage.section.prizeButton1') }))
        }

        if (!submitForm.butTwoRewards || submitForm.butTwoRewards.length <= 0) {
          tips.push(that.$t('pages.activityTemplateManage.message.noButtonReward', { button: that.$t('pages.activityTemplateManage.section.prizeButton2') }))
        } else {
          submitForm.butTwoRewards = that.filterConvertRewards(submitForm.butTwoRewards)
        }
        if (submitForm.butTwoRewards.length !== that.form.butTwoRewards.length) {
          tips.push(that.$t('pages.activityTemplateManage.message.invalidButtonReward', { button: that.$t('pages.activityTemplateManage.section.prizeButton2') }))
        }

        if (tips.length > 0) {
          tips.push(that.$t('pages.activityTemplateManage.message.continueConfirm'))
          that.$confirm(tips.join('<br>'), that.$t('pages.activityTemplateManage.confirm.title'), {
            confirmButtonText: that.$t('pages.activityTemplateManage.action.confirm'),
            cancelButtonText: that.$t('pages.activityTemplateManage.action.cancel'),
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
            that.submit(submitForm)
          }).catch(() => {
          })
          return
        }
        that.submit(submitForm)
      })
    },
    submit(submitForm) {
      const that = this
      if (!that.sysOrigin) {
        that.$opsMessage.fail(that.$t('pages.activityTemplateManage.message.sysOriginRequired'))
        return
      }
      submitForm.sysOrigin = that.sysOrigin
      that.submitLoading = true
      if (submitForm.id) {
        updateActivityConf(submitForm).then(res => {
          that.submitLoading = false
          that.$emit('success', res)
        }).catch(er => {
          that.submitLoading = false
          that.$emit('fial', er)
        })
        return
      }
      addActivityConf(submitForm).then(res => {
        that.submitLoading = false
        that.$emit('success', res)
      }).catch(er => {
        that.submitLoading = false
        console.error(er)
        that.$emit('fial', er)
      })
    },
    clickChangeGift(index) {
      this.giftSelectVisible = true
      this.giftSelectedIndex = index
    },
    selectedGift(gift) {
      this.giftSelectVisible = false
      if (this.giftSelectedIndex >= 0) {
        this.form.gifts[this.giftSelectedIndex] = gift
      }
    }
  }
}
</script>
<style scoped lang="scss">
.activity-gift {
  padding: 10px;
  .gift-item {
    position: relative;
    .gift {
      position: relative;
      border: 1px dashed #999999;
      border-radius: 5px;
      margin: 5px 15px;
      height: 120px;
      width: 120px;
      overflow: hidden;
      cursor: pointer;
      .tips {
        position: absolute;
        color: #FFFFFF;
        left: 30%;
        top: 40%;
        cursor: pointer;
        display: none;
      }
      img {
        width: 100%;
        height: 100%;
      }
      &:hover {
        .tips {
          display: block !important;
        }
      }
    }
    .gift-amount {
        text-align: center;
    }
  }

}
</style>
