<template>
  <div class="app-container-source">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width: 120px"
        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-select
        v-model="listQuery.groupId"
        v-loading="groupListLoading"
        placeholder="分组"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in groupList"
          :key="index"
          :label="item.groupName"
          :value="item.id"
          class="filter-item"
        />
      </el-select>
      <el-select
        v-model="listQuery.type"
        placeholder="类型"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="item in emojiType"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.shelfStatus"
        placeholder="状态"
        style="width: 120px"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="item in productConfigShowcase"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @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" width="100">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column label="资源类型" align="center" width="100">
        <template slot-scope="scope">
          <span v-for="(item, index) in emojiSourceType " :key="index">
            <span v-if="item.value == scope.row.sourceType">{{ item.name }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="封面" align="center" width="100">
        <template slot-scope="scope">
          <avatar :url="scope.row.coverUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="group.groupName" label="分组" align="center" />
      <el-table-column label="表情类型" align="center">
        <template slot-scope="scope">
          <span v-for="(item, index) in emojiType " :key="index">
            <span v-if="item.value == scope.row.type">{{ item.name }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="200" label="上/下架" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shelfStatus"
            :active-value="true"
            :inactive-value="false"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="100">
        <template slot-scope="scope">
          <div>
            <el-button type="text" @click.native="handlUpdate(scope.row)">修改</el-button>
          </div>
        </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"
      :modal-append-to-body="true"
      :append-to-body="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="450px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" label-width="110px" :rules="formRules">
          <el-form-item
            label="分组"
            prop="groupId"
          >
            <el-select
              v-model="form.groupId"
              v-loading="groupListLoading"
              placeholder="类型"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in groupList"
                :key="index"
                :label="item.groupName"
                :value="item.id"
                class="filter-item"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="类型"
            prop="type"
          >
            <el-select
              v-model="form.sourceType"
              placeholder="资源类型"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in emojiSourceType"
                :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 v-model="form.coverUrl" label="封面" prop="coverUrl">
            <el-upload
              :disabled="coverUploadLoading"
              :file-list="coverFileList"
              :class="{'upload-but-hide': !isShowCoverUpload}"
              action=""
              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 v-model="form.sourceUrl" label="svga/gif" prop="sourceUrl">
            <el-upload
              :disabled="sourceUploadLoading"
              :class="{'upload-but-hide': !isShowSourceUpload}"
              action=""
              :http-request="sourceUpload"
              :on-remove="handleSourceFileRemove"
              :show-file-list="!isShowSourceUpload"
              :file-list="sourceUrlFileList"
              accept=".svga,.gif,.pag"
            >
              <div class="upload-but">
                <el-button :loading="sourceUploadLoading" size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传svga/gif/pag文件</div>
              </div>
            </el-upload>
            <svgaplayer v-if="!isShowSourceUpload" :url="form.sourceUrl" />
          </el-form-item>

          <el-form-item
            label="类型"
            prop="type"
          >
            <el-select
              v-model="form.type"
              placeholder="类型"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in emojiType"
                :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
            label="上架"
            prop="type"
          >
            <el-select
              v-model="form.shelfStatus"
              placeholder="上架"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in productConfigShowcase"
                :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 label="顺序" prop="sort">
            <el-input v-model.trim="form.sort" type="number" :placeholder="'数字越小越靠前'" />
          </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 { getElementUiUploadFile } from '@/utils'
import { emojiType, productConfigShowcase, emojiSourceType } from '@/constant/type'
import { pageTable, addOrUpdate, offShelfById, listGroupBySysOrigin } from '@/api/sys-emoji'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'

function getFormData() {
  return {
    id: '',
    sourceType: '',
    sysOrigin: '',
    sourceUrl: '',
    coverUrl: '',
    type: '',
    shelfStatus: '',
    sort: '',
    groupId: '',
    amount: ''
  }
}
export default {
  name: 'EmojiConfig',
  components: { Pagination },
  data() {
    const commonRules = [
      { required: true, message: '必填字段不可为空', trigger: 'blur' }
    ]
    return {
      svgaplayerVisable: false,
      coverUploadLoading: false,
      coverFileList: [],
      sourceUploadLoading: false,
      sourceUrlFileList: [],
      searchDisabled: false,
      productConfigShowcase,
      emojiType,
      emojiSourceType,
      submitLoading: false,
      formVisible: false,
      form: getFormData(),
      formRules: {
        coverUrl: commonRules,
        type: commonRules,
        sysOrigin: commonRules,
        shelfStatus: commonRules,
        groupId: commonRules
      },
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        type: '',
        sysOrigin: '',
        shelfStatus: '',
        groupId: ''
      },
      listLoading: true,
      groupList: [],
      groupListLoading: false
    }
  },
  computed: {
    isShowCoverUpload() {
      return !this.form.coverUrl
    },
    isShowSourceUpload() {
      return !this.form.sourceUrl
    },
    textOptTitle() {
      return (this.row && this.row.id ? '修改' : '添加') + `(${this.$sysOriginMap[this.listQuery.sysOrigin]})`
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.renderData()
    that.loadGroupList()
  },
  methods: {
    changeSysOrigin() {
      this.loadGroupList(true)
      this.renderData(true)
    },
    loadGroupList(isClean) {
      const that = this
      if (isClean === true) {
        that.groupList = []
        that.form.groupId = ''
        that.listQuery.groupId = ''
      }
      that.groupListLoading = true
      listGroupBySysOrigin(that.listQuery.sysOrigin).then(res => {
        that.groupListLoading = false
        that.groupList = res.body || []
      }).catch(er => {
        that.groupListLoading = false
        console.error(er)
      })
    },
    uploadCover(file) {
      const that = this
      that.coverUploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.svgasource).then(res => {
        that.coverUploadLoading = false
        that.form.coverUrl = that.$getAccessImgUrl(res.name)
        if (this.form.coverUrl) {
          this.coverFileList = getElementUiUploadFile(this.form.coverUrl)
        }
      }).catch(er => {
        that.coverUploadLoading = false
      })
    },
    handleCoverFileRemove(file, fileList) {
      this.form.coverUrl = ''
      this.coverUploadLoading = false
      this.coverFileList = []
    },
    sourceUpload(file) {
      const that = this
      that.sourceUploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.svgasource).then(res => {
        that.sourceUploadLoading = false
        that.form.sourceUrl = that.$getAccessImgUrl(res.name)
        if (this.form.sourceUrl) {
          this.sourceUrlFileList = getElementUiUploadFile(this.form.sourceUrl)
        }
      }).catch(er => {
        that.sourceUploadLoading = false
      })
    },
    handleSourceFileRemove(file, fileList) {
      this.form.sourceUrl = ''
      this.sourceUploadLoading = false
      this.sourceUrlFileList = []
    },
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
        that.listQuery.cursor = 1
      }
      that.listLoading = true
      pageTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleSwitchChange(row) {
      const that = this
      var text = row.shelfStatus ? '上架成功' : '下架成功'
      offShelfById(row.id).then(res => {
        that.$emit('success', text)
        that.renderData(true)
      }).catch(er => {
        that.$emit('fail')
        console.error(er)
      })
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        that.submitLoading = true
        that.form.sysOrigin = that.listQuery.sysOrigin
        addOrUpdate(that.form).then(res => {
          that.submitLoading = false
          that.$emit('success', res)
          that.handleClose()
          that.renderData(true)
        }).catch(er => {
          that.submitLoading = false
          that.$emit('fail')
          console.error(er)
        })
      })
    },
    handleSearch() {
      this.searchLoading = true
      this.renderData(true)
    },
    handleCreate() {
      this.formVisible = true
      this.form = getFormData()
      this.coverFileList = []
    },
    handlUpdate(row) {
      this.formVisible = true
      this.form = Object.assign(this.form, row)
      if (this.form.sourceUrl) {
        this.sourceUrlFileList = getElementUiUploadFile(this.form.sourceUrl)
      }
      if (this.form.coverUrl) {
        this.coverFileList = getElementUiUploadFile(this.form.coverUrl)
      }
    },
    handleClose() {
      this.formVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
    },
    clickSvgaplayer() {
      this.svgaplayerVisable = true
    }
  }
}
</script>
<style scoped lang="scss">
 .store-table-expand {
    font-size: 0;
    label {
    width: 90px;
    color: #99a9bf;
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 50%;
    }
   }
 }
</style>
