<template>
  <el-container>
    <el-header height="220">
      <h3>文章列表</h3>
      <el-row style="margin-top: 10px">
        <el-select
          v-model="queryInfo.categoryId"
          clearable
          style="margin-left: 5px"
          @change="onSelectChange"
        >
          <el-option
            v-for="(item, index) in categoryList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="success" icon="el-icon-plus" style="margin-left: 5px" @click="handleAdd">添加</el-button>
        <el-button type="warning" icon="el-icon-delete" style="margin-left: 5px" @click="handleResetIndex">重置索引</el-button>
      </el-row>
    </el-header>
    <el-main>
      <el-table
        :data="dataList"
        border
        height="480"
        style="width: 100%"
      >
        <el-table-column
          fixed="left"
          label="No"
          type="index"
        />
        <el-table-column
          prop="title"
          label="标题"
        >
          <template slot-scope="scope">
            <router-link style="text-decoration-line: none" target="_blank" :to="`/blog/post/${scope.row.articleId}`">
              <span>{{ scope.row.title }}</span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="category"
          label="分类"
        >
          <template slot-scope="scope">
            <el-tag>
              <span>{{ scope.row.category }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="tags"
          label="标签"
        >
          <template slot-scope="scope">
            <el-tag v-for="(tag, index) in scope.row.tags" :key="index" style="margin: 5px" type="warning">
              <span>{{ tag }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="editor"
          label="编辑器"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.editor === 'markdown'" type="info"><span>{{ scope.row.editor }}</span></el-tag>
            <el-tag v-else type="info"><span>{{ scope.row.editor }}</span></el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="published"
          label="是否发布"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.published" type="success">
              <span>已发布</span>
            </el-tag>
            <el-tag v-else type="warning">
              <span>未发布</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="280"
        >
          <template slot-scope="scope">
            <el-button
              style="margin-top: 5px; margin-left: 5px"
              size="mini"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)"
            >修改</el-button>
            <el-button
              style="margin-top: 5px; margin-left: 5px"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :small="screenWidth <= 768"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="currentPage"
        :total="totalSize"
        @current-change="handleCurrentChange"
        @prev-click="handleCurrentChange"
        @next-click="handleCurrentChange"
      />

      <el-dialog
        title="编辑文章"
        append-to-body
        :visible.sync="addDialog"
        width="100%"
        center
      >
        <template>
          <div id="editor">
            <mavon-editor
              ref="md"
              style="height: 100%"
              :ishljs="true"
              :value="addForm.content"
              @change="onEditorChange"
            />
          </div>
          <el-form :model="addForm" label-width="80px" style="margin: 5px">
            <el-form-item label="标题">
              <el-input v-model="addForm.title" style="width: 30%; padding-right: 1px" />
            </el-form-item>
            <el-form-item label="分类">
              <el-select
                v-model="addForm.categoryId"
                style="padding-right: 1px"
              >
                <el-option
                  v-for="(item, index) in categoryList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标签">
              <el-select
                v-model="addForm.tags"
                style="padding-right: 1px"
                placeholder="输入标签，用回车添加"
                clearable
                multiple
                filterable
                allow-create
                default-first-option
              >
                <el-option v-for="item in addForm.tags" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否发布">
              <el-select
                v-model="addForm.published"
                style="padding-right: 1px"
              >
                <el-option label="发布" value="1" />
                <el-option label="草稿" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="文章类型">
              <el-select
                v-model="addForm.postType"
                style="padding-right: 1px"
              >
                <el-option label="文章" value="1" />
                <el-option label="问题" value="2" />
              </el-select>
            </el-form-item>
          </el-form>
          <el-button type="success" style="margin: 5px" @click="onAdd">确定</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import {
  editBlogPost,
  deleteBlogPost,
  getBlogCategoryList,
  getBlogEditPost,
  getBlogPostList,
  resetBlogPostIndex
} from '@/api/blog'

export default {
  name: 'BlogPost',
  components: {
    'mavon-editor': mavonEditor.mavonEditor
  },
  props: {
    mdData: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      categoryList: [],
      queryInfo: {
        pn: 1,
        categoryId: null,
        title: '',
        published: 0
      },
      // 屏幕宽度, 为了控制分页条的大小
      screenWidth: document.body.clientWidth,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      dataList: [],
      addDialog: false,
      addForm: {
        articleId: null,
        editor: 'markdown',
        title: null,
        content: '',
        categoryId: '',
        tags: [],
        published: '1',
        postType: '1'
      }
    }
  },
  created() {
    const pageNumber = this.$route.query.pn
    if (pageNumber !== undefined && pageNumber !== null) {
      this.currentPage = parseInt(pageNumber)
      this.queryInfo.pn = parseInt(pageNumber)
    }
    const categoryId = this.$route.query.categoryId
    if (categoryId !== undefined && categoryId !== null) {
      this.queryInfo.categoryId = parseInt(categoryId)
    }
    const title = this.$route.query.title
    if (title !== undefined && title !== null) {
      this.queryInfo.title = title
    }
    const published = this.$route.query.published
    if (published !== undefined && published !== null) {
      this.queryInfo.published = published
    }
    const queryInfo = {}
    queryInfo.type = 'category'
    getBlogCategoryList(queryInfo).then(resp => {
      if (resp.code === 0) {
        this.categoryList = resp.data
      } else {
        this.$message.error(resp.msg)
      }
    }).catch(error => {
      this.$message.error(error.message)
    })

    document.title = '文章列表'
    this.getData()
  },
  methods: {
    handleCurrentChange(pageNumber) {
      this.queryInfo.pn = pageNumber
      this.$router.push({
        path: '/bg/blog/post',
        query: this.queryInfo
      })
      this.getData()
      // 回到顶部
      scrollTo(0, 0)
    },
    getData() {
      getBlogPostList(this.queryInfo).then(resp => {
        if (resp.code === 0) {
          const respData = resp.data
          this.dataList = respData.list
          this.totalSize = respData.totalSize
        } else {
          this.$message.error(resp.msg)
        }
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    handleAdd() {
      this.addDialog = true
    },
    handleEdit(index, row) {
      const queryInfo = {}
      queryInfo.articleId = row.articleId
      getBlogEditPost(queryInfo).then(resp => {
        if (resp.code === 0) {
          this.addForm = resp.data
          this.addDialog = true
        } else {
          this.$message.error(resp.msg)
        }
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    onAdd() {
      const formData = new FormData()
      if (this.addForm.articleId !== null) {
        formData.append('articleId', this.addForm.articleId)
      }

      formData.append('editor', this.addForm.editor)
      formData.append('title', this.addForm.title)
      formData.append('content', this.addForm.content)
      formData.append('categoryId', this.addForm.categoryId)
      formData.append('tags', this.addForm.tags)
      formData.append('published', this.addForm.published)
      formData.append('postType', this.addForm.postType)
      editBlogPost(formData).then(resp => {
        this.addDialog = false
        this.$message.info(resp.msg)
        this.getData()
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    handleDelete(index, row) {
      this.$confirm('确定要删除 ' + row.title + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const formData = new FormData()
        formData.append('articleId', row.articleId)
        deleteBlogPost(formData).then(resp => {
          this.$message.info(resp.msg)
          this.getData()
        }).catch(error => {
          this.$message.error(error.message)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    onSelectChange() {
      this.currentPage = 1
      this.queryInfo.pn = 1
      this.$router.push({
        path: '/bg/blog/post',
        query: this.queryInfo
      })
      this.getData()
    },
    onEditorChange() { // 也可以接收 value 和 render参数 获取内容
      // this.$emit('update:mdData', this.$refs.md.d_value)
      // 带有标签的内容
      // console.log(this.$refs.md.d_render)
      // markdown文本格式
      this.addForm.content = this.$refs.md.d_value
    },
    handleResetIndex() {
      this.$confirm('确定要重置文章索引?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetBlogPostIndex().then(resp => {
          this.$message.info(resp.msg)
        }).catch(error => {
          this.$message.error(error.message)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    }
  }
}
</script>

<style scoped>
#editor {
  margin: auto;
  width: 100%;
  height: 480px;
}
</style>
