<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">基础信息</div>
          <el-alert
            v-if="isClose"
            :closable="false"
            type="info"
            show-icon
            style="margin-bottom: 10px;"
            title="活动结束后不可用在编辑"
          />
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="系统"> {{ sysOrigin }} </el-form-item>
            <el-form-item v-loading="loadingTemplateValueLoading" label="模版" prop="templateId">
              <el-select
                v-model="form.templateId"
                placeholder="模版"
                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="时间" prop="startTime">
              <el-date-picker
                v-model="rangeDate"
                type="datetimerange"
                value-format="timestamp"
                style="width:100%;"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
              />
              <el-alert
                v-if="!isClose && isEndTimeLteNow"
                :closable="false"
                type="info"
                show-icon
                size="mini"
                style="margin-bottom: 10px;"
                title="过期活动将不可编辑, 请检查活动时间"
              />
            </el-form-item>
            <el-form-item label="状态" prop="showcase">
              <el-select
                v-model="form.showcase"
                placeholder="状态"
                style="width:100%;"
                class="filter-item"
              >
                <el-option label="下架" :value="false" />
                <el-option label="上架" :value="true" />
              </el-select>
            </el-form-item>
            <el-form-item label="描述" 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">活动礼物</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">点击更换</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">请选择</div>
            </div>
          </div>
          <div class="blockquote blockquote-mini">活动排名奖品</div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="奖品-按钮1" name="but1">
              <reward-edit :sys-origin="sysOrigin" :rewards-group="form.butOneRewards" @change="rewards=> form.butOneRewards = rewards" />
            </el-tab-pane>
            <el-tab-pane label="奖品-按钮2" 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()">取消</el-button>
          <el-button v-if="!isClose" type="primary" @click="submitForm()">保存</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: '必填字段', 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 ? '修改' : '新增'
    },
    ...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('活动已结束,不可在此编辑!')
        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('礼物数量不足3个')
        }

        if (!submitForm.butOneRewards || submitForm.butOneRewards.length <= 0) {
          tips.push('[奖品-按钮1] 没有关联活动排名奖品')
        } else {
          submitForm.butOneRewards = that.filterConvertRewards(submitForm.butOneRewards)
        }
        if (submitForm.butOneRewards.length !== that.form.butOneRewards.length) {
          tips.push('[奖品-按钮1] 存在错误记录,系统将自动矫正排除')
        }

        if (!submitForm.butTwoRewards || submitForm.butTwoRewards.length <= 0) {
          tips.push('[奖品-按钮2] 没有关联活动排名奖品')
        } else {
          submitForm.butTwoRewards = that.filterConvertRewards(submitForm.butTwoRewards)
        }
        if (submitForm.butTwoRewards.length !== that.form.butTwoRewards.length) {
          tips.push('[奖品-按钮2] 存在错误记录,系统将自动矫正排除')
        }

        if (tips.length > 0) {
          tips.push('如果继续请点击确认按钮, 是否继续?')
          that.$confirm(tips.join('<br>'), '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
            that.submit(submitForm)
          }).catch(() => {
          })
          return
        }
        that.submit(submitForm)
      })
    },
    submit(submitForm) {
      const that = this
      if (!that.sysOrigin) {
        that.$opsMessage.fail('归属系统不可为空!')
        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>
