<template>
  <div class="props-activity-reward-config-edit">
    <el-dialog
      :title="textOptTitle"
      :visible="true"
      :modal-append-to-body="true"
      :append-to-body="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="90%"
      top="20px"
    >
      <div class="form-edit">
        <el-form ref="form" :model="form" :rules="formRules" label-width="110px" style="margin-right:50px;">
          <el-form-item prop="gameType" :label="$t('pages.gameLotteryConfigForm.form.gameType')">
            <el-select
              v-model="form.gameType"
              :placeholder="$t('pages.gameLotteryConfigForm.placeholder.gameType')"
              style="width:100%;"
              class="filter-item"
            >
              <el-option v-for="(item, index) in (lotteryGameTypes || [])" :key="index" :label="getLotteryGameTypeLabel(item)" :value="item.value">
                <div style="float: left;margin-left:10px">
                  {{ getLotteryGameTypeLabel(item) }}
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <div class="dr-content">
            <div ref="rewardContent">
              <el-row v-for="(item, index) in form.rewardConfigList" :key="index" style="cursor:pointer;line-height:30px;">
                <el-col :span="2">
                  <div class="sort">{{ index + 1 }}</div>
                </el-col>
                <el-col :span="2" style="text-align:center;">
                  <div v-if="item.type === 'GOLD'">
                    <img src="@/assets/gold_icon.png" style="width:30px;height:30px;cursor: pointer;">
                  </div>
                  <div v-else-if="item.type === 'DIAMOND'">
                    <img src="@/assets/diamond_icon.png" style="width:30px;height:30px;cursor: pointer;">
                  </div>
                  <div v-else-if="item.type === 'SPECIAL_ID'">
                    <img src="@/assets/special_id.png" style="width:30px;height:30px;cursor: pointer;">
                  </div>
                  <div v-else-if="isGameCoupon(item.type)">
                    <img src="@/assets/game_coupon.png" style="width:30px;height:30px;cursor: pointer;">
                  </div>
                  <div v-else class="preview-img" style="width: 36px; height: 36px">
                    <el-image
                      style="width: 100%; height: 100%"
                      :src="item.cover"
                      :preview-src-list="[item.cover]"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline" />
                      </div>
                    </el-image>
                    <div class="preview-svga">
                      <svgaplayer
                        type="popover"
                        :url="item.sourceUrl"
                      />
                    </div>
                  </div>
                </el-col>
                <el-col :span="14" style="text-align: right;">
                  <span style="font-weight:bold;"> {{ getTypeName(item) }}</span>
                  <span v-if="item.type === 'SPECIAL_ID'" style="margin-left: 0.3rem;">
                    <span style="margin-right: 0.3rem;">{{ $t('pages.gameLotteryConfigForm.label.type') }}:{{ item.content }}</span>{{ $t('pages.gameLotteryConfigForm.label.quantity') }}:<el-input v-model="item.quantity" v-number :value="item.quantity" style="width: 10%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.quantity')" />
                  </span>
                  <span v-else-if="item.type === 'GOLD' || item.type === 'DIAMOND' || isGameCoupon(item.type)" style="margin-left: 0.3rem;">
                    {{ $t('pages.gameLotteryConfigForm.label.quantity') }}:<el-input v-model="item.content" v-number :value="item.content" style="width: 10%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.quantity')" />
                  </span>
                  <span v-else-if="item.type === 'BADGE'" style="margin-left: 0.3rem;">
                    <span style="margin-right: 0.3rem;">{{ item.badgeName }}</span>{{ $t('pages.gameLotteryConfigForm.label.days') }}:<el-input v-model="item.quantity" v-number :value="item.quantity" style="width: 10%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.days')" /></span>
                  <span v-else>
                    <span v-if="item.type === 'GIFT'" style="margin-left: 0.3rem;">{{ $t('pages.gameLotteryConfigForm.label.quantity') }}:</span>
                    <span v-else>{{ $t('pages.gameLotteryConfigForm.label.days') }}:</span>
                    <el-input v-model="item.quantity" v-number :value="item.quantity" style="width: 10%;" :placeholder="item.type === 'GIFT' ? $t('pages.gameLotteryConfigForm.placeholder.quantity') : $t('pages.gameLotteryConfigForm.placeholder.days')" />
                  </span>
                  <span style="margin-left: 0.3rem;">{{ $t('pages.gameLotteryConfigForm.label.inventory') }}:<el-input v-model="item.inventory" v-number :value="item.inventory" style="width: 10%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.inventory')" /></span>
                  <span v-if="form.gameType === 'EGG'" style="color:#d8ae36;margin-left: 0.3rem;">
                    {{ $t('pages.gameLotteryConfigForm.label.requiredFragments') }}:<el-input v-model="item.dataHelp" v-number :value="item.dataHelp" style="width: 7%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.requiredFragments')" />
                  </span>
                  <span style="color:#f78e8e;margin-left: 0.3rem;">
                    {{ $t('pages.gameLotteryConfigForm.label.probability') }}:<el-input v-model="item.probability" oninput="value=value.replace(/[^0-9.]/g,'')" :value="item.probability" style="width: 10%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.probability')" />
                  </span>
                </el-col>
                <el-col :span="2" style="text-align: right;">
                  <i class="del el-icon-delete-solid" @click="deleteUpdateItem(index)" />
                </el-col>
              </el-row>
            </div>
          </div>
          <el-form-item :label="$t('pages.gameLotteryConfigForm.form.addConfig')">
            <div class="content-list">
              <el-row v-for="(item, index) in form.tmpConfigList" :key="index">
                <div class="content-box">
                  <div class="content-box-label">
                    <span>{{ item.ext.title }}</span>
                  </div>
                  <el-row v-if="item.clickType === 'SPECIAL_ID'" :gutter="10">
                    <el-col :span="4">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.content'"
                        :rules="getRequiredFieldRule()"
                      >
                        <el-select
                          v-model="item.content"
                          :placeholder="$t('pages.gameLotteryConfigForm.placeholder.select')"
                          style="width:100%"
                          filterable
                        >
                          <el-option v-for="(pItem, pIndex) in specialIdTypes" :key="pIndex" :label="pItem.name" :value="pItem.value" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.quantity'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.quantity" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.quantity')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.inventory'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.inventory" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.inventory')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="form.gameType === 'EGG'" :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.dataHelp'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.dataHelp" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.requiredFragments')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.probability'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.probability" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.probabilityExample')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <i class="del el-icon-delete-solid" @click="deleteItem()" />
                      <i class="save el-icon-success" @click="submitItem(index)" />
                    </el-col>
                  </el-row>
                  <el-row v-else-if="isCurrency(item.clickType) || isGameCoupon(item.clickType)" :gutter="10">
                    <el-col :span="5">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.content'"
                        :rules="getRequiredFieldRule()"
                      >
                        <el-input v-model.trim="item.content" v-number type="text" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.inputContent')" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.inventory'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.inventory" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.inventory')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="form.gameType === 'EGG'" :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.dataHelp'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.dataHelp" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.requiredFragments')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.probability'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.probability" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.probabilityExample')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <i class="del el-icon-delete-solid" @click="deleteItem()" />
                      <i class="save el-icon-success" @click="submitItem(index)" />
                    </el-col>
                  </el-row>
                  <el-row v-else-if="isBadge(item.clickType)" :gutter="10">
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.content'"
                        :rules="getRequiredFieldRule()"
                      >
                        <el-select
                          v-model="item.content"
                          :placeholder="$t('pages.gameLotteryConfigForm.placeholder.select')"
                          style="width:100%"
                          filterable
                          @change="(val)=> changeContent(item, val)"
                        >
                          <el-option v-for="(pItem, pIndex) in propsTypeData[item.clickType].list" :key="pIndex" :label="pItem.name" :value="pItem.id">
                            <div style="float: left;">
                              <img :src="pItem.cover" width="40px" height="40px">
                            </div>
                            <div style="float: left;margin-left:10px">
                              {{ pItem.name }}
                            </div>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.quantity'"
                        :rules="getNotEmptyRule()"
                      >
                        <!-- <span><el-input v-model="item.quantity" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.days')" /></span> -->

                        <el-autocomplete
                          v-model="item.quantity"
                          v-number
                          popper-class="my-autocomplete"
                          :fetch-suggestions="querySearchBadgeRestaurants"
                          :placeholder="$t('pages.gameLotteryConfigForm.placeholder.days')"
                        >
                          <template slot-scope="{ item }">
                            <div class="name">{{ item.value }}</div>
                            <span class="addr">{{ item.label }}</span>
                          </template>
                        </el-autocomplete>

                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.inventory'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.inventory" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.inventory')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="form.gameType === 'EGG'" :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.dataHelp'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.dataHelp" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.requiredFragments')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.probability'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.probability" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.probabilityExample')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="5">
                      <i class="del el-icon-delete-solid" @click="deleteItem()" />
                      <i class="save el-icon-success" @click="submitItem(index)" />
                    </el-col>
                  </el-row>
                  <el-row v-else :gutter="10">
                    <el-col :span="3">
                      <div class="preview-img" style="width: 36px; height: 36px">
                        <el-image
                          style="width: 100%; height: 100%"
                          :src="item.ext.selectVal.cover"
                          :preview-src-list="[item.ext.selectVal.cover]"
                        >
                          <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline" />
                          </div>
                        </el-image>
                        <div class="preview-svga">
                          <svgaplayer
                            type="popover"
                            :url="item.ext.selectVal.sourceUrl"
                          />
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.content'"
                        :rules="getRequiredFieldRule()"
                      >
                        <el-select
                          v-model="item.content"
                          :placeholder="$t('pages.gameLotteryConfigForm.placeholder.select')"
                          style="width:100%"
                          filterable
                          @change="(val)=> changeContent(item, val)"
                        >
                          <el-option v-for="(pItem, pIndex) in propsTypeData[item.clickType].list" :key="pIndex" :label="pItem.name" :value="pItem.id">
                            <div style="float: left;">
                              <img :src="pItem.cover" width="40px" height="40px">
                            </div>
                            <div style="float: left;margin-left:10px">
                              {{ pItem.name }}
                            </div>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.quantity'"
                        :rules="getNotEmptyRule()"
                      >
                        <div><el-input v-model="item.quantity" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.quantityOrDays')" /></div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.inventory'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.inventory" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.inventory')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="form.gameType === 'EGG'" :span="3">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.dataHelp'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.dataHelp" v-number style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.requiredFragments')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="4">
                      <el-form-item
                        :prop="'tmpConfigList.' + index + '.probability'"
                        :rules="getNotEmptyRule()"
                      >
                        <span><el-input v-model="item.probability" oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 100%;" :placeholder="$t('pages.gameLotteryConfigForm.placeholder.probabilityExample')" /></span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="3">
                      <i class="del el-icon-delete-solid" @click="deleteItem()" />
                      <i class="save el-icon-success" @click="submitItem(index)" />
                    </el-col>
                  </el-row>
                </div>
              </el-row>

            </div>
            <div>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['AVATAR_FRAME'].loading" @click="addContent('AVATAR_FRAME')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('AVATAR_FRAME') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['RIDE'].loading" @click="addContent('RIDE')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('RIDE') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['NOBLE_VIP'].loading" @click="addContent('NOBLE_VIP')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('NOBLE_VIP') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['THEME'].loading" @click="addContent('THEME')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('THEME') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['GIFT'].loading" @click="addContent('GIFT')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('GIFT') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" @click="addContent('SPECIAL_ID')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('SPECIAL_ID') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" @click="addContent('GOLD')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('GOLD') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" @click="addContent('DIAMOND')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('DIAMOND') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" @click="addContent('GAME_COUPON')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('GAME_COUPON') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['BADGE'].loading" @click="addContent('BADGE')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('BADGE') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['ROOM_BADGE'].loading" @click="addContent('ROOM_BADGE')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('ROOM_BADGE') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['EMOJI'].loading" @click="addContent('EMOJI')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('EMOJI') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['FLOAT_PICTURE'].loading" @click="addContent('FLOAT_PICTURE')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('FLOAT_PICTURE') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['CHAT_BUBBLE'].loading" @click="addContent('CHAT_BUBBLE')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('CHAT_BUBBLE') }}</el-button>
              <el-button type="text" :disabled="disableAddContent" :loading="propsTypeData['FRAGMENTS'].loading" @click="addContent('FRAGMENTS')"><i class="el-icon-circle-plus" />{{ getAddButtonLabel('FRAGMENTS') }}</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <span v-if="1 - sumProbability > 0">{{ $t('pages.gameLotteryConfigForm.message.probabilityRemaining', { value: (1 - sumProbability).toFixed(3) }) }} <span style="color: #b3b1b1;">{{ $t('pages.gameLotteryConfigForm.message.totalProbabilityHint') }}</span></span>
            <span v-else-if="1 == sumProbability" style="color:#38c95e;">{{ $t('pages.gameLotteryConfigForm.message.probabilityComplete') }} </span>
            <span v-else style="color:#ebbe40;">{{ $t('pages.gameLotteryConfigForm.message.probabilityExceeded', { value: (sumProbability - 1).toFixed(3) }) }} <span style="color: #b3b1b1;">{{ $t('pages.gameLotteryConfigForm.message.totalProbabilityHint') }}</span></span>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer">
        <el-button @click="handleClose()">{{ $t('pages.gameLotteryConfigForm.action.cancel') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm()">{{ $t('pages.gameLotteryConfigForm.action.save') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>

import { listGiftBySysOrigin } from '@/api/gift'
import { listBadgePictureBySysOrigin } from '@/api/badge'
import { saveOrUpdateGameLotteryGroup } from '@/api/game'
import { listSysOriginTypeList, listNotFamilyBySysOriginType } from '@/api/props'
import { lotteryGameTypes, propsTypes, propsCurrencyType, propsValidDays, specialIdTypes } from '@/constant/type'
import { deepClone } from '@/utils'
import Sortable from 'sortablejs'
import { listGroupBySysOrigin } from '@/api/sys-emoji'
export default {
  props: {
    row: {
      type: Object,
      require: false,
      default: () => {}
    },
    sysOrigin: {
      type: String,
      return: true,
      default: ''
    }
  },
  data() {
    const commonRules = [
      { required: true, message: this.$t('pages.propsSourceGroupForm.validation.requiredField'), trigger: 'blur' }
    ]
    return {
      specialIdTypes,
      disableAddContent: false,
      propsTypeData: {
        'AVATAR_FRAME': {
          loading: false,
          loadData: false,
          list: []
        },
        'CHAT_BUBBLE': {
          loading: false,
          loadData: false,
          list: []
        },
        'FRAGMENTS': {
          loading: false,
          loadData: false,
          list: []
        },
        'RIDE': {
          loading: false,
          loadData: false,
          list: []
        },
        'NOBLE_VIP': {
          loading: false,
          loadData: false,
          list: []
        },
        'THEME': {
          loading: false,
          loadData: false,
          list: []
        },
        'GIFT': {
          loading: false,
          loadData: false,
          list: []
        },
        'BADGE': {
          loading: false,
          loadData: false,
          list: []
        },
        'ROOM_BADGE': {
          loading: false,
          loadData: false,
          list: []
        },
        'EMOJI': {
          loading: false,
          loadData: false,
          list: []
        },
        'FLOAT_PICTURE': {
          loading: false,
          loadData: false,
          list: []
        }
      },
      isChangeSource: false,
      propsValidDays,
      propsCurrencyType,
      svgaplayerVisable: false,
      coverUploadLoading: false,
      coverFileList: [],
      sourceUploadLoading: false,
      sourceUrlFileList: [],
      propsTypes,
      lotteryGameTypes,
      submitLoading: false,
      sumProbability: 0.000,
      form: {
        id: '',
        shelfStatus: true,
        tmpConfigList: [],
        rewardConfigList: [],
        sysOrigin: '',
        gameType: ''
      },
      formRules: {
        shelfStatus: commonRules,
        sysOrigin: commonRules,
        gameType: commonRules
      },
      sourceTypeList: [],
      selectType: {},
      isLoadSourceTypeList: false,
      listTypeLoading: false
    }
  },
  computed: {
    badgeRestaurants() {
      const locale = this.$locale
      void locale
      return [{ value: '0', label: this.$t('pages.gameLotteryConfigForm.word.permanent') }]
    },
    rowCover() {
      return this.row ? this.row.propsSourceRecordDTO.cover : ''
    },
    rowSourceUrl() {
      return this.row ? this.row.propsSourceRecordDTO.sourceUrl : ''
    },
    isShowCoverUpload() {
      return !this.form.cover
    },
    isShowSourceUpload() {
      return !this.form.sourceUrl
    },
    textOptTitle() {
      return this.$t('pages.gameLotteryConfigForm.dialog.title', {
        action: this.isUpdate ? this.$t('pages.gameLotteryConfigForm.action.edit') : this.$t('pages.gameLotteryConfigForm.action.add'),
        system: this.sysOrigin
      })
    },
    isUpdate() {
      return this.row && this.row.id
    }
  },
  watch: {
    row: {
      handler(newVal) {
        if (!newVal) {
          return
        }
        const newForm = deepClone(newVal)
        newForm.tmpConfigList = []
        this.form = newForm
        this.form.sysOrigin = this.sysOrigin
        if (!this.form.rewardConfigList) {
          this.form.rewardConfigList = []
        }
        this.calculateProbability()
      },
      immediate: true
    },
    sysOrigin: {
      handler(newVal) {
        if (!newVal) {
          return
        }
        this.form.sysOrigin = newVal
      },
      immediate: true
    }
  },
  mounted() {
    const that = this
    that.$nextTick(() => {
      Sortable.create(that.$refs.rewardContent, {
        onEnd: function(evt) {
          const oldIndex = evt.oldIndex
          const newIndex = evt.newIndex
          if (newIndex === oldIndex) {
            return
          }

          that.form.rewardConfigList.splice(newIndex, 0, that.form.rewardConfigList.splice(oldIndex, 1)[0])
          const newList = that.form.rewardConfigList.splice(0)
          that.form.rewardConfigList = []
          that.$nextTick(() => {
            that.form.rewardConfigList = newList
          })
        }
      })
    })
  },
  methods: {
    getRequiredFieldRule() {
      return { required: true, message: this.$t('pages.propsSourceGroupForm.validation.requiredField'), trigger: 'blur' }
    },
    getNotEmptyRule() {
      return { required: true, message: this.$t('pages.propsSourceGroupForm.validation.notEmpty'), trigger: 'blur' }
    },
    getLotteryGameTypeLabel(item) {
      if (!item) {
        return ''
      }
      if (item.value === 'EGG') {
        return this.$t('pages.gameLotteryConfigForm.gameType.egg')
      }
      return item.name
    },
    getPropsTypeValue(type) {
      if (type === 'EMOJI') {
        return 'EMOJI'
      }
      if (type === 'BADGE' || type === 'ROOM_BADGE') {
        return 'BADGE'
      }
      if (type === 'GIFT' || type === 'GOLD' || type === 'DIAMOND' || type === 'SPECIAL_ID' || type === 'GAME_COUPON') {
        return type
      }
      return 'PROPS'
    },
    getResourceTypeName(type) {
      const keyMap = {
        AVATAR_FRAME: 'avatarFrame',
        RIDE: 'ride',
        NOBLE_VIP: 'nobleVip',
        THEME: 'theme',
        GIFT: 'gift',
        SPECIAL_ID: 'specialId',
        GOLD: 'gold',
        DIAMOND: 'diamond',
        GAME_COUPON: 'gameCoupon',
        BADGE: 'userBadge',
        ROOM_BADGE: 'roomBadge',
        EMOJI: 'emoji',
        FLOAT_PICTURE: 'floatPicture',
        CHAT_BUBBLE: 'chatBubble',
        FRAGMENTS: 'fragments'
      }
      const key = keyMap[type]
      return key ? this.$t(`pages.propsSourceGroupForm.resourceType.${key}`) : ''
    },
    getAddButtonLabel(type) {
      return this.getResourceTypeName(type)
    },
    querySearchBadgeRestaurants(queryString, cb) {
      const badgeRestaurants = this.badgeRestaurants
      const results = queryString ? badgeRestaurants.filter(restaurant => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }) : badgeRestaurants
      cb(results)
    },
    changeContent(item, val) {
      const that = this
      const typeData = that.propsTypeData[item.clickType]
      if (!typeData) {
        return
      }

      const list = typeData.list

      if (!list && list.length < 1) {
        return
      }

      const data = typeData.list.find(typeItem => typeItem.id === val)
      item.ext.selectVal.id = data.id
      item.ext.selectVal.cover = data.cover
      item.ext.selectVal.sourceUrl = data.sourceUrl
    },
    deleteItem() {
      const that = this
      that.form.tmpConfigList = []
      this.calculateProbability()
    },
    submitItem(index) {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        const item = that.form.tmpConfigList[0]
        const itemExt = item.ext
        that.form.rewardConfigList.push({
          type: item.type,
          content: item.content,
          detailType: item.clickType,
          quantity: item.quantity,
          cover: itemExt.selectVal.cover,
          sourceUrl: itemExt.selectVal.sourceUrl,
          probability: item.probability,
          inventory: item.inventory,
          dataHelp: item.dataHelp
        })
        that.form.tmpConfigList.splice(index, 1)
        this.calculateProbability()
      })
    },
    getTypeName(item) {
      return this.getResourceTypeName(item.detailType)
    },
    deleteUpdateItem(index) {
      this.form.rewardConfigList.splice(index, 1)
      this.calculateProbability()
    },
    calculateProbability() {
      const that = this
      that.sumProbability = 0.000
      that.form.rewardConfigList.forEach((item, index) => {
        that.sumProbability = parseFloat(that.sumProbability) + parseFloat(item.probability)
      })
      that.sumProbability = that.sumProbability.toFixed(3)
    },
    addContent(type) {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }

        if (that.form.tmpConfigList && that.form.tmpConfigList.length > 0) {
          that.submitItem(0)
        }
        if (that.isGoldOrDiamond(type) || type === 'SPECIAL_ID') {
          that.addContentData(type)
          return
        }
        if (that.isGameCoupon(type)) {
          that.addContentData(type)
          return
        }
        if (that.propsTypeData[type].loadData === true) {
          that.addContentData(type)
          return
        }
        that.propsTypeData[type].loading = true

        if (that.isGift(type)) {
          that.disableAddContent = true
          listGiftBySysOrigin(that.form.sysOrigin).then(res => {
            that.disableAddContent = false
            that.propsTypeData[type].loadData = true
            that.propsTypeData[type].loading = false
            const list = res.body || []
            that.propsTypeData[type].list = list.map(item => {
              return { type, id: item.id, name: item.giftName, amount: item.giftCandy, cover: item.giftPhoto, sourceUrl: item.giftSourceUrl }
            })
            that.addContentData(type)
          }).catch(er => {
            that.disableAddContent = false
            that.propsTypeData[type].loading = false
            console.error(er)
          })
          return
        }

        const badgeType = that.getBadgeType(type)
        if (badgeType) {
          that.disableAddContent = true
          listBadgePictureBySysOrigin(that.form.sysOrigin, badgeType).then(res => {
            that.disableAddContent = false
            that.propsTypeData[type].loadData = true
            that.propsTypeData[type].loading = false
            const list = res.body || []
            that.propsTypeData[type].list = list.map(item => {
              return { type, id: item.badgeConfigId, name: item.badgeName, amount: 0, cover: item.selectUrl, sourceUrl: item.animationUrl }
            })
            that.addContentData(type)
          }).catch(er => {
            that.disableAddContent = false
            that.propsTypeData[type].loading = false
            console.error(er)
          })
          return
        }

        if (type === 'NOBLE_VIP') {
          that.disableAddContent = true
          listNotFamilyBySysOriginType(that.form.sysOrigin, 'NOBLE_VIP').then(res => {
            that.disableAddContent = false
            that.propsTypeData[type].loadData = true
            that.propsTypeData[type].loading = false
            const list = res.body || []
            that.propsTypeData[type].list = list.map(item => {
              return { type, id: item.id, name: item.name, amount: item.amount, cover: item.cover, sourceUrl: item.sourceUrl }
            })
            that.addContentData(type)
          }).catch(er => {
            that.disableAddContent = false
            that.propsTypeData[type].loading = false
            console.error(er)
          })
          return
        }

        if (type === 'EMOJI') {
          listGroupBySysOrigin(that.form.sysOrigin).then(res => {
            that.disableAddContent = false
            that.propsTypeData[type].loadData = true
            that.propsTypeData[type].loading = false
            const list = res.body || []
            that.propsTypeData[type].list = list.map(item => {
              return { type, id: item.id, name: item.groupName, cover: item.cover }
            })
            that.addContentData(type)
          }).catch(er => {
            that.disableAddContent = false
            that.propsTypeData[type].loading = false
            console.error(er)
          })
          return
        }

        that.disableAddContent = true
        listSysOriginTypeList(that.sysOrigin, type).then(res => {
          that.disableAddContent = false
          that.propsTypeData[type].loadData = true
          that.propsTypeData[type].loading = false
          const list = res.body || []
          that.propsTypeData[type].list = list.map(item => {
            return { type, id: item.id, name: item.name, amount: item.amount, cover: item.cover, sourceUrl: item.sourceUrl }
          })
          that.addContentData(type)
        }).catch(er => {
          that.disableAddContent = false
          that.propsTypeData[type].loading = false
          console.error(er)
        })
      })
    },
    getBadgeType(type) {
      if (this.isUserBadge(type)) {
        return 'ACTIVITY'
      }

      if (this.isRoomBadge(type)) {
        return 'ROOM_ACHIEVEMENT'
      }
      return null
    },
    isCurrency(type) {
      return type === 'GOLD' || type === 'DIAMOND'
    },
    isGameCoupon(type) {
      return type === 'GAME_COUPON'
    },
    isBadge(type) {
      return this.isRoomBadge(type) || this.isUserBadge(type)
    },
    isUserBadge(type) {
      return type === 'BADGE'
    },
    isRoomBadge(type) {
      return type === 'ROOM_BADGE'
    },
    isGift(type) {
      return type === 'GIFT'
    },
    isTheme(type) {
      return type === 'THEME'
    },
    addContentData(type) {
      const that = this
      that.form.tmpConfigList.push({
        type: that.getPropsTypeValue(type),
        clickType: type,
        content: '',
        quantity: '',
        probability: '',
        inventory: '',
        dataHelp: '',
        ext: {
          title: that.getResourceTypeName(type),
          selectVal: { id: '', cover: '', sourceUrl: '' }
        }
      })
    },
    isGoldOrDiamond(type) {
      return type === 'GOLD' || type === 'DIAMOND'
    },
    clickChangeSource() {
      this.isChangeSource = !this.isChangeSource
      if (this.isChangeSource === true && this.isLoadSourceTypeList === false) {
        this.loadSourceType()
      }
    },
    changeType(index) {
      this.selectType = this.sourceTypeList[index]
      this.form.sourceId = this.selectType.id
    },
    loadSourceType() {
      const that = this
      that.listTypeLoading = true
      listSysOriginTypeList(that.sysOrigin, 'RIDE').then(res => {
        that.listTypeLoading = false
        that.isLoadSourceTypeList = false
        that.sourceTypeList = res.body || []
      }).catch(er => {
        that.listTypeLoading = false
        console.error(er)
      })
    },
    handleCoverFileRemove(file, fileList) {
      this.form.cover = ''
      this.coverUploadLoading = false
    },
    sourceUpload(file) {
      const that = this
      that.sourceUploadLoading = true
      that.$simpleUploadFlie(file).then(res => {
        that.sourceUploadLoading = false
        that.form.sourceUrl = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.sourceUploadLoading = false
      })
    },
    handleSourceFileRemove(file, fileList) {
      this.form.sourceUrl = ''
      this.sourceUploadLoading = false
    },
    handleClose() {
      this.$emit('close')
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        if (!that.form.rewardConfigList || that.form.rewardConfigList.length < 1) {
          that.$opsMessage.fail(that.$t('pages.gameLotteryConfigForm.message.configRequired'))
          return
        }
        that.submitLoading = true
        const form = deepClone(that.form)
        form.rewardConfigList = []
        // The combined probability must equal 1 before submit.
        that.sumProbability = 0.000
        that.form.rewardConfigList.forEach((item, index) => {
          form.rewardConfigList.push({
            type: item.type,
            detailType: item.detailType,
            content: item.content,
            quantity: item.quantity,
            sort: index + 1,
            probability: item.probability,
            inventory: item.inventory,
            dataHelp: item.dataHelp
          })
          that.sumProbability += parseFloat(item.probability === '' ? 0 : item.probability)
        })
        if (that.sumProbability.toFixed(3) > 1 || that.sumProbability.toFixed(3) < 1) {
          that.submitLoading = false
          that.$opsMessage.fail(that.$t('pages.gameLotteryConfigForm.message.totalProbabilityInvalid'))
          return
        }
        saveOrUpdateGameLotteryGroup(form).then(res => {
          that.submitLoading = false
          that.$emit('success', res)
        }).catch(er => {
          that.submitLoading = false
          that.$emit('fail')
          console.error(er)
        })
      })
    },
    clickSvgaplayer() {
      this.svgaplayerVisable = true
    }
  }
}
</script>
<style scoped lang="scss">
.props-activity-reward-config-edit {
  .form-edit {
    max-height: 600px;
    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;
    }
  }
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
