<template>
  <div class="app-container">
    <el-dialog
      :title="$t('pages.luckyBoxAwardConfig.dialog.detailsListTitle')"
      :visible.sync="isDialog"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :fullscreen="true"
      top="20px"
    >
      <div class="filter-container">
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-edit"
          :disabled="isAdd"
          @click="handleAdd"
        >
          {{ $t('pages.luckyBoxAwardConfig.action.add') }}
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="dataList"
        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.luckyBoxAwardConfig.table.platform')" align="center" width="280" />
        <el-table-column width="280" :label="$t('pages.luckyBoxAwardConfig.table.type')" align="center">
          <template slot-scope="scope">
            {{ getPropsTypeLabel(scope.row.propsType) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('pages.luckyBoxAwardConfig.table.resource')" width="280" align="center">
          <template slot-scope="scope">
            <div class="preview-img">
              <el-image
                style="width: 100%; height: 100%"
                :src="scope.row.cover"
                :preview-src-list="[scope.row.cover]"
              />
              <div :v-if="scope.row.type != 'THMEM'" class="preview-svga">
                <svgaplayer
                  type="popover"
                  :url="scope.row.sourceUrl"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="lotteryNumber" :label="$t('pages.luckyBoxAwardConfig.table.targetCount')" align="center" width="280" />
        <el-table-column prop="validDays" :label="$t('pages.luckyBoxAwardConfig.table.validDays')" align="center" width="280" />
        <el-table-column prop="createTime" :label="$t('pages.luckyBoxAwardConfig.table.createdAt')" align="center" width="300">
          <template slot-scope="scope">
            {{ scope.row.createTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('pages.luckyBoxAwardConfig.table.actions')" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click.native="hanldeEidt(scope.row)">{{ $t('pages.luckyBoxAwardConfig.action.edit') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <el-dialog
          :title="$t('pages.luckyBoxAwardConfig.dialog.detailsFormTitle')"
          :visible.sync="innerEditVisible"
          width="550px"
          top="50px"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
          append-to-body
        >
          <div style="height: 500px;overflow: auto;">
            <el-form
              ref="dataForm"
              :rules="dialogFormRules"
              :model="formData"
              style="width: 400px; margin-left:50px;"
            >
              <el-form-item :label="$t('pages.luckyBoxAwardConfig.form.system')" prop="sysOrigin">
                <el-select
                  v-model="formData.sysOrigin"
                  :placeholder="$t('pages.luckyBoxAwardConfig.placeholder.selectSystem')"
                  style="width:100%;"
                  class="filter-item"
                  @change="changeSysOrigin"
                >
                  <el-option
                    v-for="item in permissionsSysOriginPlatforms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
                    <span style="float: left;margin-left:10px">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('pages.luckyBoxAwardConfig.form.propsType')" prop="propsType">
                <el-select
                  v-model="formData.propsType"
                  :placeholder="$t('pages.luckyBoxAwardConfig.placeholder.propsType')"
                  style="width:100%;"
                  class="filter-item"
                  @change="changePropsType"
                >
                  <el-option
                    v-for="item in localizedPropsTypes"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('pages.luckyBoxAwardConfig.form.propsId')" prop="propsId">
                <div v-if="selectProps.cover" class="payer-source">
                  <div class="paler-icon">
                    <svgaplayer
                      type="popover"
                      :url="selectProps.sourceUrl || ''"
                    />
                  </div>
                  <img :src="selectProps.cover" alt="cover">
                </div>
                <props-source-select-popover
                  v-loading="propsTypeMap[formData.propsType] ? propsTypeMap[formData.propsType].loading : false"
                  :data="propsTypeMap[formData.propsType] ? propsTypeMap[formData.propsType].list : []"
                  :property="selectPopoverProperty"
                  :visible="visiblePopover"
                  :show-filter="true"
                  @select="selectPropsSourcePopover"
                />
              </el-form-item>
              <el-form-item :label="$t('pages.luckyBoxAwardConfig.form.targetCount')" prop="lotteryNumber">
                <el-input v-model="formData.lotteryNumber" v-number :placeholder="$t('pages.luckyBoxAwardConfig.placeholder.targetCount')" />
              </el-form-item>
              <el-form-item :label="$t('pages.luckyBoxAwardConfig.form.validDays')" prop="validDays">
                <el-input v-model="formData.validDays" v-number :placeholder="$t('pages.luckyBoxAwardConfig.placeholder.validDays')" />
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="innerEditVisible = false">
              {{ $t('common.cancel') }}
            </el-button>
            <el-button
              :loading="submitLoading"
              type="primary"
              @click="handleSubmit"
            >
              {{ $t('common.submit') }}
            </el-button>
          </div>
        </el-dialog>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGameLuckyBoxAwardDetailsConfig, addGameLuckyBoxAwardDetailsConfig } from '@/api/game-lucky-box-config'
import { mapGetters } from 'vuex'
import { propsTypes } from '@/constant/type'
import { listNotFamilyBySysOriginType } from '@/api/props'
import PropsSourceSelectPopover from '@/components/data/PropsSourceSelectPopover'
export default {
  name: 'BountyDetailsConfigTable',
  components: { PropsSourceSelectPopover },
  props: {
    awardId: {
      type: String,
      required: true
    },
    updatePropsData: {
      type: Object,
      default: null
    }
  },
  data() {
    const propsTypeMap = {}
    propsTypes.forEach(item => {
      propsTypeMap[item.value] = {
        list: [],
        loading: false,
        loadData: false
      }
    })
    return {
      propsTypes,
      visiblePopover: false,
      propsTypeMap,
      selectPopoverProperty: {
        label: 'name',
        cover: 'cover',
        svgaUrl: 'sourceUrl',
        value: 'id'
      },
      selectProps: {},
      updateData: null,
      dataList: [],
      isDialog: true,
      innerEditVisible: false,
      listQuery: {
        awardId: '',
        sysOrigin: 'HALAR'
      },
      formData: {
        id: '',
        awardId: '',
        propsType: '',
        propsId: '',
        lotteryNumber: '',
        validDays: '',
        sysOrigin: 'HALAR'
      },
      submitLoading: false,
      isAdd: true,
      listLoading: true
    }
  },
  computed: {
    localizedPropsTypes() {
      return this.propsTypes.map(item => ({
        ...item,
        name: this.getPropsTypeLabel(item.value)
      }))
    },
    dialogFormRules() {
      const requiredMessage = this.$t('pages.luckyBoxAwardConfig.validation.requiredField')
      const commonRules = [{ required: true, message: requiredMessage, trigger: 'blur' }]
      return {
        propsType: commonRules,
        propsId: commonRules,
        lotteryNumber: commonRules,
        validDays: commonRules,
        sysOrigin: commonRules
      }
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  watch: {
    awardId: {
      handler(newVal) {
        this.listQuery.awardId = newVal
        this.renderData()
      },
      immediate: true
    },
    updatePropsData: {
      immediate: true,
      deep: true,
      handler(newVal) {
        Object.assign(this.formData, newVal)
        this.propsData = newVal
      }
    }
  },
  created() {
    if (!this.permissionsFirstSysOrigin) {
      return
    }
    this.listQuery.sysOrigin = this.permissionsFirstSysOrigin.value
    this.renderData()
    this.propsTypes = this.propsTypes.filter(item => !(item.value === 'CUSTOMIZE' || item.value === 'FRAGMENTS'))
  },
  methods: {
    getPropsTypeLabel(type) {
      return this.$t(`pages.luckyBoxAwardConfig.propsType.${type}`)
    },
    changeSysOrigin(val) {
      const that = this
      that.formData.propsType = ''
      that.selectProps = {}
    },
    changePropsType(val) {
      const that = this
      that.formData.vipOrigin = null
      if (!that.formData.sysOrigin) {
        return
      }
      that.selectProps = {}
      that.formData.propsId = ''
      const propsTypeItem = that.propsTypeMap[val]
      propsTypeItem.list = []
      propsTypeItem.loading = true
      listNotFamilyBySysOriginType(that.formData.sysOrigin, val).then(res => {
        propsTypeItem.loading = false
        propsTypeItem.loadData = true
        propsTypeItem.list = (res.body || [])
      }).catch(er => {
        propsTypeItem.loading = false
        console.error(er)
      })
    },
    selectPropsSourcePopover(item) {
      this.selectProps = item
      this.formData.propsId = item.id
    },
    renderData() {
      const that = this
      that.listLoading = true
      getGameLuckyBoxAwardDetailsConfig(that.listQuery).then(res => {
        const { body } = res
        that.dataList = body
        that.isAdd = parseInt(that.dataList.length) === 6
        that.listLoading = false
      }).catch(er => {
        that.listLoading = false
      })
    },
    handleAdd() {
      this.innerEditVisible = true
      this.formData = {}
      this.selectProps = {}
    },
    hanldeEidt(row) {
      this.innerEditVisible = true
      this.propsData = row
      this.formData = this.propsData
      this.selectProps.cover = this.propsData.cover
      this.selectProps.sourceUrl = this.propsData.sourceUrl
    },
    // 删除
    // hanldeDelete(row) {
    //   this.$confirm('确认删除吗？', '提示', {
    //     type: 'warning'
    //   }).then(() => {
    //     this.listLoading = true
    //     deleteAwardDetailsConfig(row.id).then((res) => {
    //       this.listLoading = false
    //       this.$message({
    //         message: '删除成功',
    //         type: 'success'
    //       })
    //       this.renderData()
    //     })
    //   }).catch(() => {
    //     this.listLoading = false
    //   })
    // },
    handleClose() {
      this.$emit('close')
    },
    handleSubmit() {
      const that = this
      that.$refs.dataForm.validate(valid => {
        if (valid) {
          that.submitLoading = true
          that.formData.awardId = that.listQuery.awardId
          addGameLuckyBoxAwardDetailsConfig(that.formData).then(res => {
            that.submitLoading = false
            that.innerEditVisible = false
            that.renderData()
            this.$emit('success', 'create')
          }).catch(er => {
            that.submitLoading = false
            that.innerEditVisible = false
            console.error(er)
            this.$emit('fail')
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.payer-source {
  position: relative;
  .paler-icon {
    position:absolute;
    left: 60px;
    top: -20px;
  }
  img {
    width: 100px;
    height: 100px;
  }
}
</style>
