<template>
  <div class="app-container">
    <el-button
      type="primary"
      size="small"
      icon="el-icon-plus"
      style="margin-bottom: 10px"
      @click="visible.type === 'add';visible.banner = true;"
    >
      添加轮播图
    </el-button>
    <!-- 表格 -->
    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        type="index"
        :index="indexMethod"
        width="70"
        label="编号"
        align="center"
      />
      <el-table-column
        prop="imgurl"
        label="图片"
        width="70"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-image
            :src="row.imgurl"
            fit="scale-down"
            class="hoverImg"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="描述"
        align="center"
      >
        <template slot-scope="{ row }">
          {{ row.name ? row.name : '暂无描述' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="is_jump"
        label="是否跳转"
        align="center"
      >
        <template slot-scope="{ row }">
          <span v-if="!row.is_jump || row.is_jump === 0">不可跳转</span>
          <el-button v-else type="text">{{ row.url }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-button
            type="text"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button
            type="text"
            @click="handleEdit(row)"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      :total="tableTotal"
      :limit="searchParams.page_size"
      :page="searchParams.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
    <!-- 添加轮播图 -->
    <el-dialog
      :title="visible.type === 'add' ? '添加轮播图' : '修改轮播图'"
      :visible.sync="visible.banner"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="bannerForm" :model="bannerForm" :rules="bannerRule" label-width="80px">
        <el-form-item label="上传图片:">
          <el-upload
            :action="upload_url"
            :show-file-list="false"
            :http-request="thumbPictureUpload"
          >
            <el-button
              size="mini"
            >
              点击上传
            </el-button>
          </el-upload>
          <div v-if="bannerForm.imgurl">
            <el-image
              style="width: 750px; height: 250px"
              :src="bannerForm.imgurl"
              fit="contain"
            />
          </div>
        </el-form-item>
        <el-form-item label="描述:">
          <el-input
            v-model="bannerForm.name"
            placeholder="轮播图描述"
          />
        </el-form-item>
        <el-form-item label="是否跳转:" prop="isLink">
          <el-radio-group v-model="bannerForm.isLink">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="bannerForm.isLink === 1" label="跳转链接:" prop="link">
          <el-input
            v-model="bannerForm.link"
            placeholder="跳转链接"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="handleCancel"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleSubmit"
          >
            添加
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// api
import {
  getBannerList,
  uploadBanner,
  deleteBanner,
  submitBanner,
  editBanner
} from '@/api/picture/banner'
export default {
  data() {
    const validateLink = (rule, value, callback) => {
      if (this.bannerForm.isLink === 1) {
        if (value === '') {
          callback(new Error('请添加跳转链接'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      searchParams: {
        page_index: 1,
        page_size: 20
      },
      visible: {
        banner: false,
        type: 'add'
      },
      upload_url: 'http://192.168.0.15:8011/api/picture/uploadbannerimageinfo',
      bannerForm: {
        imgurl: '',
        isLink: 0,
        link: '',
        name: '',
        id: ''
      },
      bannerRule: {
        isLink: [
          { required: true, message: '请选择是否需要跳转', trigger: 'change' }
        ],
        link: [
          { validator: validateLink, trigger: 'blur' }
        ]
      },
      table: [],
      tableTotal: 0
    }
  },
  created() {
    this.getBannerList()
  },
  methods: {
    // 获取列表
    async getBannerList() {
      const res = await getBannerList(this.searchParams)
      try {
        const { message, code } = res
        if (code === 200) {
          const { list, total } = res.data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取轮播图列表失败:${e}`)
      }
    },
    // 上传主图(缩略图)
    thumbPictureUpload(params) {
      this.thumbLoad = true
      const file = params.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 1)
      uploadBanner(formData).then(res => {
        this.thumbLoad = false
        try {
          const { message, code, data } = res
          if (code === 200) {
            this.bannerForm.imgurl = data
          } else {
            this.bannerForm.imgurl = ''
            this.$message.error(message)
          }
        } catch (e) {
          console.log(`轮播图上传失败:${e}`)
        }
      }).catch(() => {
        this.thumbLoad = false
      })
    },
    // 添加轮播图
    handleSubmit() {
      this.$refs.bannerForm.validate((valid) => {
        if (valid) {
          if (this.visible.type === 'add') {
            const { name, imgurl, isLink, link } = this.bannerForm
            this.submitBanner({
              name, imgurl, isLink, link
            })
          } else {
            this.editBanner(this.bannerForm)
          }
        } else {
          return false
        }
      })
    },
    // 添加轮播图
    async submitBanner(data) {
      const res = await submitBanner(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleCancel()
          this.getBannerList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`提交添加轮播图失败:${e}`)
      }
    },
    // 取消
    handleCancel() {
      this.visible.banner = false
      this.$refs.bannerForm.resetFields()
      this.bannerForm.imgurl = ''
      this.bannerForm.link = ''
      this.bannerForm.name = ''
      this.bannerForm.id = ''
    },
    // 删除轮播图
    handleDelete(row) {
      this.$confirm('确认删除这个图片?', '删除轮播图', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = row
        this.deleteBanner(id)
      })
    },
    // 删除轮播图
    async deleteBanner(id) {
      const res = await deleteBanner({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleCancel()
          this.getBannerList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`删除轮播图失败:${e}`)
      }
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getBannerList()
    },
    // 修改
    handleEdit(row) {
      this.bannerForm.link = row.url ? row.url : ''
      this.bannerForm.name = row.name ? row.name : ''
      this.bannerForm.isLink = row.is_jump ? row.is_jump : 0
      this.bannerForm.imgurl = row.imgurl
      this.bannerForm.id = row.id
      this.visible.type = 'edit'
      this.visible.banner = true
    },
    // 修改
    async editBanner(data) {
      const res = await editBanner(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.handleCancel()
          this.getBannerList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`提交修改轮播图失败:${e}`)
      }
    },
    // 编号
    indexMethod(index) {
      const { page_index, page_size } = this.searchParams
      index += (page_index - 1) * page_size + 1
      return index
    }
  }
}
</script>
