<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search" placeholder="项目名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}"><span>{{ row.id }}</span></template>
      </el-table-column>
      <el-table-column label="项目名称" min-width="150px">
        <template slot-scope="{row}"><span>{{ row.title }}</span></template>
      </el-table-column>
      <el-table-column label="分类" width="110px" align="center">
        <template slot-scope="{row}"><span>{{ row.category_name }}</span></template>
      </el-table-column>
      <el-table-column label="封面" width="100px" align="center">
        <template slot-scope="{row}"><img :src="row.image" width="50" height="50" style="object-fit:cover"></template>
      </el-table-column>
      <el-table-column label="学习人数" width="100px" align="center">
        <template slot-scope="{row}"><span>{{ row.students }}</span></template>
      </el-table-column>
      <el-table-column label="评分" width="80px" align="center">
        <template slot-scope="{row}"><span>{{ row.rating }}</span></template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="800px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="width: 700px; margin-left:50px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="title">
              <el-input v-model="temp.title" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="temp.category" class="filter-item" placeholder="请选择">
                <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="封面图片" prop="image">
           <el-upload
            class="avatar-uploader"
            :action="upUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="upHeaders">
            <img v-if="temp.image" :src="temp.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="学习人数" prop="students">
              <el-input v-model.number="temp.students" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="评分" prop="rating">
              <el-input v-model="temp.rating" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
             <el-form-item label="时长" prop="duration">
              <el-input v-model="temp.duration" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="项目详情" prop="detail">
          <div style="margin-bottom: 10px;">
            <el-button size="mini" @click="exec('bold')">加粗</el-button>
            <el-button size="mini" @click="exec('italic')">斜体</el-button>
            <el-button size="mini" @click="insertLink">插入链接</el-button>
            <el-upload
              class="upload-demo"
              :action="upUrl"
              :on-success="handleDetailImageSuccess"
              :headers="upHeaders"
              :show-file-list="false"
              style="display: inline-block; margin-left: 10px;">
              <el-button size="small" type="primary">插入图片</el-button>
            </el-upload>
          </div>
          <div ref="editor" contenteditable="true" @input="syncDetail" style="min-height: 260px; border: 1px solid #dcdfe6; padding: 10px; border-radius: 4px;">
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  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>

<script>
import { getProjects, createProject, updateProject, deleteProject, getCategories } from '@/api/crm'
import Pagination from '@/components/Pagination'
import { upUrl, upHeaders } from "@/api/file"

export default {
  name: 'ProjectTable',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      categories: [],
      temp: {
        id: undefined,
        title: '',
        category: undefined,
        image: '',
        students: 0,
        rating: 5.0,
        duration: '4 周',
        detail: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        title: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择分类', trigger: 'change' }]
      },
      upUrl: upUrl(),
      upHeaders: upHeaders()
    }
  },
  created() {
    this.getList()
    this.getCategories()
  },
  methods: {
    getList() {
      this.listLoading = true
      getProjects(this.listQuery).then(response => {
        this.list = response.data.results
        this.total = response.data.count
        this.listLoading = false
      })
    },
    getCategories() {
      getCategories().then(response => {
        this.categories = response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        category: undefined,
        image: 'https://images.unsplash.com/photo-1526379095098-d400fd0bf935',
        students: 0,
        rating: 5.0,
        duration: '4 周',
        detail: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.setDetailHtml(this.temp.detail)
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const raw = this.$refs.editor ? this.$refs.editor.innerHTML : this.temp.detail
          this.temp.detail = this.normalizeForWechat(raw)
          createProject(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
          this.setDetailHtml(this.temp.detail)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          const raw = this.$refs.editor ? this.$refs.editor.innerHTML : tempData.detail
          tempData.detail = this.normalizeForWechat(raw)
          updateProject(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProject(row.id).then(() => {
            this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        })
    },
    handleAvatarSuccess(res, file) {
      this.temp.image = res.data.path
    },
    handleDetailImageSuccess(res, file) {
      const imageUrl = res.data.path
      const imgHtml = `<p><img src="${imageUrl}"/></p>`
      if (this.$refs.editor) {
        this.insertHtml(imgHtml)
        this.syncDetail()
      } else {
        this.temp.detail = (this.temp.detail || '') + imgHtml
      }
    },
    exec(cmd) {
      document.execCommand(cmd, false, null)
      this.syncDetail()
    },
    insertLink() {
      this.$prompt('输入链接地址', '插入链接', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(https?:\/\/).+/,
        inputErrorMessage: '请输入以 http(s) 开头的链接'
      }).then(({ value }) => {
        document.execCommand('createLink', false, value)
        this.syncDetail()
      }).catch(() => {})
    },
    insertHtml(html) {
      const sel = window.getSelection()
      if (!sel || sel.rangeCount === 0) {
        this.$refs.editor.insertAdjacentHTML('beforeend', html)
        return
      }
      const range = sel.getRangeAt(0)
      range.deleteContents()
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = html
      const frag = document.createDocumentFragment()
      while (tempDiv.firstChild) frag.appendChild(tempDiv.firstChild)
      range.insertNode(frag)
      range.collapse(false)
    },
    syncDetail() {
      this.temp.detail = this.$refs.editor ? this.$refs.editor.innerHTML : this.temp.detail
    },
    setDetailHtml(html) {
      if (this.$refs.editor) this.$refs.editor.innerHTML = html || ''
    },
    normalizeForWechat(html) {
      if (!html) return ''
      let h = html
      h = h.replace(/<div\b[^>]*>/gi, '<p>')
      h = h.replace(/<\/div>/gi, '</p>')
      h = h.replace(/<b\b[^>]*>/gi, '<strong>')
      h = h.replace(/<\/b>/gi, '</strong>')
      h = h.replace(/<i\b[^>]*>/gi, '<em>')
      h = h.replace(/<\/i>/gi, '</em>')
      h = h.replace(/ style=\"[^\"]*\"/gi, '')
      h = h.replace(/<img([^>]*)>/gi, (m, attrs) => {
        const srcMatch = attrs.match(/src=\"([^\"]+)\"/)
        const src = srcMatch ? srcMatch[1] : ''
        return src ? `<img src=\"${src}\"/>` : ''
      })
      return h
    }
  }
}
</script>
