<!-- 友情链接 -->
<template>
  <div class="content">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="search_box flexS">
      <el-input v-model="params.search" clearable placeholder="链接名称" prefix-icon="el-icon-search"
        @keyup.enter.native="toSearch()" @clear="toSearch()" />
      <el-button type="primary" icon="el-icon-search" :loading="loadingFull" @click="toSearch()">搜索</el-button>
      <el-button @click="handleEdit(0)" type="primary" style="margin-right:24px;">添加</el-button>
      <el-upload class="upload-demo" action="" :http-request="uploadFile" :multiple="false" :show-file-list="false">
        <el-button type="primary">导入</el-button>
      </el-upload>
    </div>
    <div class="table_box">
      <el-table ref="list" :data="listData" align="center" :header-cell-style="{ background: '#f8fbfc' }"
        class="tableBorder" border stripe>
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column prop="url" label="链接" align="center" />
        <!-- <el-table-column prop="introduction" label="简介" align="center" /> -->
        <el-table-column prop="sort" label="排名" align="center" />
        <el-table-column prop="created_at" label="创建时间" align="center" />
        <el-table-column label="操作" align="center" width="280">
          <template slot-scope="{row}">
            <el-button type="text" size="mini" @click="handleEdit(1, row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="type === 0 ? '添加友情链接' : '编辑友情链接'" :visible.sync="dialogVisible" width="35%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="链接：" prop="url">
          <el-input v-model="ruleForm.url" placeholder="请输入链接url" />
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model="ruleForm.sort" type="number" placeholder="请输入链接排序，数字越大越靠前" />
        </el-form-item>
        <el-form-item label="简介:" prop="introduction">
          <textarea name="" id="" cols="30" rows="10" v-model="ruleForm.introduction" placeholder="请输入链接简介" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{ type === 0 ? '确 定' : '保存' }}</el-button>
      </span>
    </el-dialog>
    <div class="paging_box">
      <pagination :total="listDataTotal" :limit="params.page_size" :page="params.page_index"
        @pagination="changePagination" @update:limit="changePagination" />
    </div>
  </div>
</template>
<script>
import { linkList, addLink, editLink, deleteLink, importLink } from '@/api/friendlyLinks'
export default {
  data() {
    return {
      dialogVisible: false,
      loadingFull:false,
      listData: [],
      listDataTotal: 0,
      type: '',
      id: '',
      ruleForm: {
        name: '',
        introduction: '',
        url: '',
        sort: ''
      },
      params: {
        page_index: 1,
        page_size: 10,
        search: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入url', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排名', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 搜索
    toSearch() {
      this.params.page_index = 1
      this.getList()
    },
    // 导入
    uploadFile(params) {
      const file = params.file
      var formData = new FormData()
      formData.append('file', file)
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
      console.log(file.name, 'file')
      if (!isExcel) {
        this.$message.error('仅支持上传 .xlsx 或 .xls 格式的文件!')
        return
      }
      importLink(formData).then(res => {
        if (res.code === 200) {
          this.$message.success('导入成功！')
          this.getList()
        } else {
          this.$message.error(res.message || '导入失败！')
        }
      })
    },
    reset() {
      this.ruleForm = {
        name: '',
        introduction: '',
        url: '',
        sort: ''
      }
    },
    // 编辑或者添加友情链接
    handleEdit(type, row) {
      this.dialogVisible = true
      this.type = type
      if (type === 0) {
        this.reset()
      } else {
        const { name, introduction, url, sort, id } = row
        this.ruleForm = { name, introduction, url, sort }
        this.id = id
      }
    },
    // 获取列表
    async getList() {
      this.loadingFull = true
      try {
        const res = await linkList(this.params)
        const { message, code, data } = res
        if (code === 200) {
          const { list, total } = data
          this.listData = list
          this.listDataTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取列表失败:${e}`)
        this.loadingFull = false
      }
      this.loadingFull = false
    },
    // 添加/编辑事件
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const http = this.type === 0 ? addLink : editLink
          const { name, introduction, url, sort } = this.ruleForm
          const data = this.type === 0 ? this.ruleForm : { name, introduction, url, sort, id: this.id }
          http(data).then(res => {
            if (res.code === 200) {
              this.$message.success(this.type === 0 ? '添加成功!' : '修改成功！')
              this.dialogVisible = false
            } else {
              this.$message.error(this.type === 0 ? '添加失败!' : '修改失败！')
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除确认
    handleDelete(row) {
      const { id } = row
      this.$confirm('确认要删除该链接吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteEvent(id)
      })
    },
    // 删除事件
    async deleteEvent(id) {
      const res = await deleteLink({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success('删除成功！')
          this.getList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.params.page_size = limit
      this.params.page_index = page
      this.getList()
    }
  }

}
</script>
<style lang="scss" scoped>
.el-input,
textarea {
  width: 350px;
}
</style>