<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>友情链接管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="adduser">添加友情链接</el-button>
      </div>
      <div class="main">
        <naf-grid ref="grid" @edit="edit" @delete="deletelinks" :data="linksList" :meta="meta" :total="total" @query="query"></naf-grid>
      </div>
    </el-card>
    <dialog-drawer type="dialog" :visible="visible" :title="isNew ? '修改友情链接' : '添加友情链接'" @close="close" :width="'30%'">
      <template v-slot:content>
        <naf-form v-if="visible" ref="ruleForm" @save="save" :meta="formmeta" :rules="rules" :data="is_data">
          <template v-slot:field="{ item }">
            <!-- 图片上传 -->
            <el-upload
              v-if="item.name == 'path'"
              class="avatar-uploader avatar"
              action="/api/files/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :data="{ type: 'resource' }"
              :headers="myHeaders"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </template>
        </naf-form>
      </template>
    </dialog-drawer>
  </div>
</template>

<script>
import nafGrid from '@naf/data/tables/naf-grid'
import dialogDrawer from '@naf/data/dialog -drawer'
import nafForm from '@naf/data/form'
import { createNamespacedHelpers } from 'vuex'
const token = sessionStorage.getItem('token')
const { mapState, mapActions } = createNamespacedHelpers('links')
export default {
  components: {
    nafGrid,
    dialogDrawer,
    nafForm
  },
  data () {
    return {
      imageUrl: '',
      is_data: {},
      visible: false,
      myHeaders: { Authorization: `Bearer ${token}` },
      meta: [
        { name: 'name', title: '链接名称', filter: true },
        { name: 'path', title: '图片地址' },
        { name: 'links', title: '访问地址' }
      ],
      formmeta: [
        { name: 'path', title: '链接图片', slots: 'field' },
        { name: 'name', title: '链接名称' },
        { name: 'links', title: '访问地址' }
      ],
      rules: {
        name: [
          { required: true, message: '请输入链接名称', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入链接图片', trigger: 'blur' }
        ],
        links: [
          { required: true, message: '请输入访问地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions(['linksquery', 'linkscreate', 'linksupdate', 'linksdelete']),
    // 添加
    adduser () {
      this.is_data = {}
      this.visible = true
    },
    // 删除
    async deletelinks (e) {
      this.$confirm('请确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.linksdelete(e)
        // eslint-disable-next-line eqeqeq
        if (res.errcode == 0) {
          this.$message.success('操作成功')
          this.query()
          this.$refs.grid.resetpage(-1)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改
    edit (e) {
      this.is_data = e
      this.visible = true
      if (e.path) this.imageUrl = e.path
    },
    // 查询
    async query ({ filter = {}, paging = {} } = {}) {
      await this.linksquery({ filter, paging })
    },
    // 保存按钮
    async save (e) {
      let res
      if (this.isNew) {
        // 修改
        res = await this.linksupdate(e)
      } else {
        // 添加
        res = await this.linkscreate(e)
      }
      // eslint-disable-next-line eqeqeq
      if (res.errcode == 0) {
        this.$message.success('操作成功')
        this.query()
        this.visible = false
        this.$refs.grid.resetpage(-1)
        this.imageUrl = ''
      }
    },
    // 关闭弹窗
    close () {
      this.visible = false
      this.imageUrl = ''
    },
    // 图片上传
    // 文件上传成功时的钩子
    handleAvatarSuccess (res, file) {
      this.is_data = this.$refs.ruleForm.form
      this.is_data.path = res.data.path
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传文件之前的钩子
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    }
  },
  async mounted () {
    this.query()
  },
  computed: {
    ...mapState(['total', 'linksList']),
    isNew () {
      return Boolean(this.is_data && this.is_data._id)
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
}
.box-card {
  height: 100%;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
