<template>
  <div class="app-container">
    <el-dialog
      :title="$t('pages.luckyBoxBountyConfig.dialog.detailsListTitle')"
      :visible.sync="isDialog"
      :modal-append-to-body="true"
      :append-to-body="true"
      :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"
          @click="handleAdd"
        >
          {{ $t('pages.luckyBoxBountyConfig.action.add') }}
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="dataList"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column prop="sysOrigin" :label="$t('pages.luckyBoxBountyConfig.table.platform')" align="center" width="280" />
        <el-table-column :label="$t('pages.luckyBoxBountyConfig.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="targetQuantity" :label="$t('pages.luckyBoxBountyConfig.table.targetQuantity')" align="center" width="280" />
        <el-table-column prop="validDays" :label="$t('pages.luckyBoxBountyConfig.table.validDays')" align="center" width="280" />
        <el-table-column prop="createTime" :label="$t('pages.luckyBoxBountyConfig.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.luckyBoxBountyConfig.table.actions')" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click.native="hanldeDelete(scope.row)">{{ $t('pages.luckyBoxBountyConfig.action.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div>
        <el-dialog
          :title="$t('pages.luckyBoxBountyConfig.dialog.detailsFormTitle')"
          :visible.sync="innerEditVisible"
          :modal-append-to-body="true"
          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.luckyBoxBountyConfig.form.system')" prop="sysOrigin">
                <el-select
                  v-model="formData.sysOrigin"
                  :placeholder="$t('pages.luckyBoxBountyConfig.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.luckyBoxBountyConfig.form.propsType')" prop="propsType">
                <el-select
                  v-model="formData.propsType"
                  :placeholder="$t('pages.luckyBoxBountyConfig.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.luckyBoxBountyConfig.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.luckyBoxBountyConfig.form.targetQuantity')" prop="targetQuantity">
                <el-input v-model="formData.targetQuantity" v-number :placeholder="$t('pages.luckyBoxBountyConfig.placeholder.targetQuantity')" />
              </el-form-item>
              <el-form-item :label="$t('pages.luckyBoxBountyConfig.form.validDays')" prop="validDays">
                <el-input v-model="formData.validDays" v-number :placeholder="$t('pages.luckyBoxBountyConfig.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 { getBountyDetialsConfigTable, addOrUpdateBountyDetialsConfig, deleteBountyDetailsConfig } 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: {
    bountyId: {
      type: String,
      required: true
    }
  },
  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: {
        bountyId: '',
        sysOrigin: 'HALAR'
      },
      formData: {
        id: '',
        bountyId: '',
        propsType: '',
        propsId: '',
        targetQuantity: '',
        validDays: '',
        sysOrigin: 'HALAR'
      },
      submitLoading: false,
      listLoading: true
    }
  },
  computed: {
    dialogFormRules() {
      const requiredMessage = this.$t('pages.luckyBoxBountyConfig.validation.requiredField')
      const commonRules = [{ required: true, message: requiredMessage, trigger: 'blur' }]
      return {
        propsType: commonRules,
        propsId: commonRules,
        targetQuantity: commonRules,
        validDays: commonRules,
        sysOrigin: commonRules
      }
    },
    localizedPropsTypes() {
      return this.propsTypes.map(item => ({
        ...item,
        name: this.getPropsTypeLabel(item.value)
      }))
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  watch: {
    bountyId: {
      handler(newVal) {
        this.listQuery.bountyId = newVal
        this.renderData()
      },
      immediate: true
    }
  },
  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.luckyBoxBountyConfig.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
      getBountyDetialsConfigTable(that.listQuery).then(res => {
        const { body } = res
        that.dataList = body
        that.listLoading = false
      }).catch(er => {
        that.listLoading = false
      })
    },
    handleAdd() {
      this.innerEditVisible = true
      this.formData = {}
      this.selectProps = {}
    },
    hanldeDelete(row) {
      this.$confirm(this.$t('pages.luckyBoxBountyConfig.confirm.deleteMessage'), this.$t('pages.luckyBoxBountyConfig.confirm.title'), {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteBountyDetailsConfig(row.id).then((res) => {
          this.listLoading = false
          this.$message({
            message: this.$t('pages.luckyBoxBountyConfig.message.deleteSuccess'),
            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.bountyId = that.listQuery.bountyId
          addOrUpdateBountyDetialsConfig(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>
