<template>
  <div>

    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in permissionsSysOriginPlatforms"
          :key="index"
          :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-button
        :loading="searchLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" label="系统" align="center">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column prop="levelKey" label="等级" align="center">
        <template scope="scope">
          <span v-for="(levelKey, index) in familyLevelKeys" :key="index">
            <span v-if="levelKey.value == scope.row.levelKey">{{ levelKey.name }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="levelExp" label="等级经验值" align="center" />
      <el-table-column prop="maxMember" label="最大成员数" align="center" />
      <el-table-column prop="maxManager" label="最大管理员数" align="center" />
      <el-table-column prop="sort" label="顺序" align="center" />
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="text" @click.native="handlUpdate(scope.row)">修改</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="450px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" label-width="110px" :rules="rules">
          <el-form-item
            label="系统"
            prop="sysOrigin"
          >
            <el-select
              v-model="form.sysOrigin"
              placeholder="系统"
              style="width:100%;"
              class="filter-item"
              @change="changeSysOrigin"
            >
              <el-option
                v-for="(item, index) in permissionsSysOriginPlatforms"
                :key="index"
                :label="item.label"
                :value="item.value"
                class="filter-item"
              >
                <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
            v-if="!form.id"
            label="等级Key"
            prop="levelKey"
          >
            <el-select
              v-model="form.levelKey"
              placeholder="等级Key"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in familyLevelKeys"
                :key="index"
                :label="item.name"
                :value="item.value"
                class="filter-item"
              >
                <span style="float: left;margin-left:10px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="avatarFrameId" label="头像框">
            <el-select
              v-model="form.avatarFrameId"
              placeholder="头像框"
              style="width:100%;"
              class="filter-item"
            >
              <el-option v-for="(item, index) in (avatarFrameList || [])" :key="index" :label="item.name" :value="item.id">
                <div style="float: left;">
                  <img :src="item.cover" width="40px" height="40px">
                </div>
                <div style="float: left;margin-left:10px">
                  {{ item.name }}
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="badgeId" label="徽章">
            <el-select
              v-model="form.badgeId"
              placeholder="徽章"
              style="width:100%;"
              class="filter-item"
            >
              <el-option v-for="(item, index) in (badgeList || [])" :key="index" :label="item.name" :value="item.id">
                <div style="float: left;margin-left:10px">
                  {{ item.name }}
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="giftId" label="礼物">
            <el-select
              v-model="form.giftId"
              placeholder="礼物"
              style="width:100%;"
              class="filter-item"
            >
              <el-option v-for="(item, index) in (giftList || [])" :key="index" :label="item.giftName" :value="item.id">
                <div style="float: left;">
                  <img :src="item.giftPhoto" width="40px" height="40px">
                </div>
                <div style="float: left;margin-left:10px">
                  {{ item.giftCode + ' - ' + item.giftName }}
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="背景图" prop="levelBackgroundPicture">
            <el-upload
              :disabled="coverUploadLoading"
              :class="{'upload-but-hide': !isShowCoverUpload}"
              action=""
              :file-list="coverFileList"
              list-type="picture-card"
              :http-request="uploadCover"
              :show-file-list="!isShowCoverUpload"
              :on-remove="handleCoverFileRemove"
              accept="image/*"
            >
              <i slot="default" v-loading="coverUploadLoading" class="el-icon-plus" />
            </el-upload>
          </el-form-item>

          <el-form-item label="贡献值" prop="levelExp">
            <el-input v-model.trim="form.levelExp" type="number" />
          </el-form-item>
          <el-form-item label="管理员数" prop="maxManager">
            <el-input v-model.trim="form.maxManager" type="number" />
          </el-form-item>
          <el-form-item label="成员数" prop="maxMember">
            <el-input v-model.trim="form.maxMember" type="number" />
          </el-form-item>
          <el-form-item label="顺序(慎重)" prop="sort">
            <el-input v-model.trim="form.sort" type="number" :placeholder="'等级越低数字越小,顺序务必正确'" />
          </el-form-item>
          <el-form-item
            label="等级类型"
            prop="levelType"
          >
            <el-select
              v-model="form.levelType"
              placeholder="等级类型"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in familyTypes"
                :key="index"
                :label="item.name"
                :value="item.value"
                class="filter-item"
              >
                <span style="float: left;margin-left:10px">{{ item.name }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="handleClose()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { listSysOriginTypeList } from '@/api/props'
import { listBadgeByType } from '@/api/badge'
import { listByTab } from '@/api/gift'
import { pageLevel, addOrUpdateLevel } from '@/api/family'
import { familyLevelKeys, familyTypes } from '@/constant/family'
import { getElementUiUploadFile } from '@/utils'
import { mapGetters } from 'vuex'

function getFormData() {
  return {
    levelKey: '',
    sysOrigin: '',
    avatarFrameId: '',
    badgeId: '',
    giftId: '',
    levelBackgroundPicture: '',
    levelExp: '',
    maxMember: '',
    maxManager: '',
    sort: '',
    id: '',
    levelType: ''
  }
}
export default {
  name: 'ConfigLevel',
  components: {
    Pagination
  },
  data() {
    return {
      familyTypes,
      familyLevelKeys,
      thisRow: {},
      coverFileList: [],
      level: 0,
      coverUploadLoading: false,
      formVisible: false,
      textOptTitle: '',
      form: getFormData(),
      submitLoading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        sysOrigin: ''
      },
      listLoading: true,
      searchLoading: false,
      rules: {
        sysOrigin: [
          { required: true, message: '请选择系统', trigger: 'blur' }
        ],
        levelKey: [
          { required: true, message: '请选择等级Key', trigger: 'blur' }
        ],
        badgeId: [
          { required: true, message: '请选择等级徽章', trigger: 'blur' }
        ],
        levelExp: [
          { required: true, message: '贡献值必须填写', trigger: 'blur' }
        ],
        maxMember: [
          { required: true, message: '最大成员数必须填写', trigger: 'blur' }
        ],
        maxManager: [
          { required: true, message: '最大管理员数必须填写', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '序号必须填写', trigger: 'blur' }
        ],
        levelType: [
          { required: true, message: '请选择等级类型', trigger: 'blur' }
        ]
      },
      avatarFrameList: [],
      badgeList: [],
      giftList: []
    }
  },
  computed: {
    isShowCoverUpload() {
      return !this.form.levelBackgroundPicture
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
    this.getBadgeList()
  },
  methods: {
    renderData(isReset) {
      const that = this
      if (isReset === true) {
        that.listQuery.cursor = 1
      }
      that.listLoading = true
      pageLevel(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.searchLoading = that.listLoading = false
      }).catch(er => {
        that.searchLoading = that.listLoading = false
      })
    },
    uploadCover(file) {
      const that = this
      that.coverUploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.svgaCover).then(res => {
        that.coverUploadLoading = false
        that.form.levelBackgroundPicture = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        that.coverUploadLoading = false
        that.coverFileList = []
      })
    },
    handleCoverFileRemove(file, fileList) {
      this.form.levelBackgroundPicture = ''
      this.coverFileList = []
      this.coverUploadLoading = false
    },
    handleSearch() {
      this.searchLoading = true
      this.renderData(true)
    },
    handleCreate() {
      this.textOptTitle = '新增家族等级'
      this.formVisible = true
      this.form = getFormData()
      this.coverFileList = []
      this.getBadgeList()
    },
    handlUpdate(row) {
      this.textOptTitle = '修改家族等级'
      this.formVisible = true
      this.form = Object.assign(this.form, row)
      this.coverFileList = getElementUiUploadFile(this.form.levelBackgroundPicture)
      this.getAvatarFrameList()
      this.getBadgeList()
      this.getGiftList()
    },
    changeSysOrigin() {
      this.getGiftList()
      this.getAvatarFrameList()
    },
    handleClose() {
      this.formVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
    },
    querySearch(queryString, cb) {
      var results = queryString ? this.restaurants.filter(this.createFilter(queryString)) : this.restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0) || (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          addOrUpdateLevel(that.form).then(res => {
            that.$opsMessage.success()
            that.submitLoading = false
            that.formVisible = false
            that.resetForm()
            that.renderData(true)
          }).catch(er => {
            that.submitLoading = false
            console.error(er)
            this.$emit('fail')
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    getAvatarFrameList() {
      const that = this
      that.avatarFrameList = []
      listSysOriginTypeList(that.form.sysOrigin, 'AVATAR_FRAME').then(res => {
        that.avatarFrameList = res.body || []
        console.log('avatarFrameList', that.avatarFrameList)
      }).catch(er => {
        console.error(er)
      })
    },
    getBadgeList() {
      const that = this
      that.badgeList = []
      listBadgeByType('FAMILY').then(res => {
        that.badgeList = res.body || []
      }).catch(er => {
        console.error(er)
      })
    },
    getGiftList() {
      const that = this
      that.giftList = []
      listByTab(that.form.sysOrigin, 'FAMILY').then(res => {
        that.giftList = res.body || []
      }).catch(er => {
        console.error(er)
      })
    },
    renderDataSuccess() {
      this.$message({
        message: 'Successful',
        type: 'success'
      })
      this.renderData()
    }
  }
}
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}

</style>
