<template>
  <div class="app-container">

    <el-form :inline="true">

      <el-form-item label="标题">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否发布">
        <el-select v-model="queryParams.status" clearable placeholder="选择下拉" size="small">
          <el-option
            v-for="item in status"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="queryParams.type" clearable placeholder="选择下拉" size="small">
          <el-option
            v-for="dict in options"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="el-icon-refresh-right" size="mini" @click="reList">清空</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['blog:blog:add']">新增      </el-button>

        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTi" v-hasPermi="['blog:blog:remove']">删除        </el-button>



      </el-form-item>
    </el-form>
    <el-table v-loading="loading" ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum-1) * queryParams.pageSize + (scope.$index + 1) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title"/>
      <el-table-column label="标题图片">
        <template slot-scope="scope">
          <el-image :src="scope.row.titleImg" :preview-src-list="srcList"
                    style="width: 100px; height: 50px"/>
        </template>
      </el-table-column>

      <el-table-column label="作者" prop="user" :show-overflow-tooltip="true"/>
      <el-table-column label="分类" prop="type"/>
      <el-table-column label="标签" prop="label">
        <template slot-scope="scope">
          <el-tag
            v-for="item in scope.row.label"
            :key="item"
            type="success"
            effect="dark">
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createTime"/>
      <el-table-column label="发布">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     :inactive-value="0"
                     :active-value="1"
                     inactive-color="#ff4949"
                     active-color="#13ce66" @change="handleStatusChange(scope.row)" v-hasPermi="['blog:blog:push']"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['blog:blog:edit']"
          >修改
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px">
      <el-form ref="form" :model="form" :rules="rules" :label-position="labelPosition" label-width="80px">
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题"/>
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="form.type">
            <el-option
              v-for="dict in options"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
        </el-form-item>

        <el-form-item label="作者" prop="user">
          <el-input v-model="form.user" placeholder="作者"/>
        </el-form-item>

        <el-form-item label="是否发布">
          <el-switch v-model="form.status"
                     :inactive-value="0"
                     :active-value="1"
                     inactive-color="#ff4949"
                     active-color="#13ce66"/>
        </el-form-item>

        <el-form-item label="内容">
          <Editor v-model="form.content"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  /*图片上传样式*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: inline-block;
  }

  .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;
  }

  /*标签样式*/
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
<script>
  import { list, add, get, getType, update, status, delTitle } from '@/api/blog/blog'
  import Editor from '@/components/Editor'

  export default {
    //富文本编辑器
    components: {
      Editor
    },
    data: function() {
      return {
        /*标签data*/
        dynamicTags: [],
        inputVisible: false,
        inputValue: '',
        action: process.env.VUE_APP_BASE_API + '/blog/titleImg',
        status: [{
          value: '0',
          label: ' 取消'
        }, {
          value: '1',
          label: ' 发布'
        }],
        labelPosition: 'right',

        imageUrl: '',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          status: undefined,
          type: undefined
        },
        // 分页参数
        total: 0,
        pageNum: 1,
        pageSize: 10,
        tableData: [],
        // 表单参数
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 分类下拉
        options: [],
        rules: {
          title: [
            { required: true, message: '请输入活动标题', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择分类', trigger: 'blur' }
          ],
          label: [
            { required: true, message: '请添加最少一个标签', trigger: 'blur' }
          ],
          user: [
            { required: true, message: '请输入作者', trigger: 'blur' }
          ]

        },
        // 文件
        form: {},

        srcList: [
          'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
          'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
        ],
        multipleSelection: []

      }
    },

    // 初始化方法
    created() {
      //表格初始化
      this.getList()
      //表单初始化
      this.reset()
      //下拉初始化
      getType('system').then(response => {
        this.options = response.data
      })
    },
    methods: {

      handleSelectionChange(val) {
        this.multipleSelection = []
        for (let i = 0; i < val.length; i++) {
          this.multipleSelection[i] = val[i].bId
        }
      },
      // 发布或取消文章
      handleStatusChange(row) {
        let text = row.status === 1 ? '发布' : '取消'
        try {
          status(row.bId, row.status)
        } catch (e) {
          this.msgError(e)
        }
        this.msgSuccess(text + '成功')
      },
      deleteTi() {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定 ',
          cancelButtonText: '取消 ',
          type: 'warning',
          center: true
        }).then(() => {
          let ids = this.multipleSelection
          if (ids.length === 0) {
            this.msgError('你没有选择文章')
            return
          }
          delTitle(ids)
          this.msgSuccess('成功')
          this.reIds()
          this.getList()
        }).catch(() => {
          this.msgSuccess('已取消删除')
        })
      }
      ,
      reIds() {
        this.multipleSelection = []
      }
      ,
      /** 查询角色列表 */
      getList() {
        this.loading = true
        list(this.addDateRange(this.queryParams)).then(
          response => {
            this.tableData = response.rows
            let tableData = this.tableData
            for (let i = 0; i < tableData.length; i++) {
              let imgSrc = process.env.VUE_APP_BASE_URL + tableData[i].titleImg
              tableData[i].titleImg = imgSrc
              this.srcList[i] = imgSrc
              tableData[i].label = tableData[i].label.split(',')
            }
            this.total = response.total
            this.loading = false
          }
        )
      }
      ,
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      }
      ,
      reList() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          status: undefined,
          type: undefined
        }
        this.getList()
      }
      ,
      // 重置表单新增使用
      reset() {
        this.imageUrl = undefined
        this.form = {
          bId: undefined,
          title: undefined,
          titleImg: undefined,
          type: undefined,
          user: undefined,
          label: undefined,
          content: undefined,
          status: 0
        }
        this.resetForm('form')
      }
      ,
      /**
       * 头像上传
       * */
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        let msg = res.msg
        let code = res.code
        if (code === 200) {
          this.form.titleImg = res.imgUrl
          this.msgSuccess('新增成功')
        } else {
          this.msgError(msg)
        }

      }
      ,
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (isLt2M) {
        } else {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加文章'
      }
      ,
      /**
       * 关闭按钮
       */
      cancel() {
        this.open = false
        this.reset()
      }
      ,
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        get(row.bId).then(response => {
          this.form = response.data
          let titleImg = process.env.VUE_APP_BASE_URL + this.form.titleImg
          this.imageUrl = titleImg
          this.dynamicTags = this.form.label.split(',')
          this.open = true
          this.title = '修改文章'
        })
      }
      ,
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.bId !== undefined) {
              update(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            } else {
              add(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                } else {
                  this.msgError(response.msg)
                }
              })
            }
          }
        })
      },
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
        this.form.label = this.dynamicTags.join(',')

      },

      showInput() {

        this.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },

      handleInputConfirm() {
        let inputValue = this.inputValue
        let dynamicTags = this.dynamicTags
        for (const obj of dynamicTags) {
          if (obj === inputValue) {
            this.msgError('已添加过该标签!')
            return
          }
        }
        if (inputValue) {
          this.dynamicTags.push(inputValue)
          this.form.label = this.dynamicTags.join(',')
        }
        this.inputVisible = false
        this.inputValue = ''
      }
    }

  }
</script>
