<template>
  <div>
    <el-card shadow="never" class="aui-card--fill">

      <!-- 按钮 -->
      <div class="btn-group">
        <el-button type="primary" @click="onAddBtnClick">新增</el-button>
        <el-button type="primary" @click="onEditBtnClick">修改</el-button>
      </div>

      <!-- 数据列表 -->
      <div>
        <el-table :data="histories" border style="width: 100%">
          <el-table-column prop="versionNo" label="版本">
          </el-table-column>
          <el-table-column label="操作" :width="80">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="onEditBtnClick(scope.row.id)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>

      <!-- 分页条-->
      <el-pagination background layout="prev, pager, next" @current-change="onCurrentPageChanged"
        :current-page="this.pageArgs.pageNo" :page-size="this.pageArgs.pageSize" :total="this.pageArgs.total">
      </el-pagination>

      <!--      <Tinymce
                v-model="createOrUpdateForm.richContent"
                :width="450"
                :height="500"
            />-->
    </el-card>

    <!-- 新增/修改 -->
    <el-dialog :visible.sync="publishVersionUpgradeShow" v-if="publishVersionUpgradeShow" :close-on-click-modal="false"
      :close-on-press-escape="false" :title="this.operation === 'create' ? '发布新版本' : '修改'">
      <el-form :model="createOrUpdateForm" ref="createOrUpdateForm">
        <el-form-item prop="versionNo" label="版本">
          <el-input v-model="createOrUpdateForm.versionNo">
          </el-input>
        </el-form-item>

        <el-form-item prop="richContent" label="内容">
          <!-- <el-input v-model="createOrUpdateForm.richContent"> -->
          <!-- <Tinymce v-model="createOrUpdateForm.richContent" :height="300" placeholder="在这里输入文字" /> -->

          <!-- :customerId="customerId" -->
          <div id="J_quillEditor"></div>
          <!-- 自定义上传图片功能 (使用element upload组件) -->
          <el-upload :headers="$getElUploadHeaders()" :action="uploadUrl" :show-file-list="false"
            :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle" style="display: none">
            <el-button ref="uploadBtn" type="primary" size="small">{{
              $t('upload.button')
              }}</el-button>
          </el-upload>
          <!-- </el-input> -->
        </el-form-item>
        <el-button @click="onSubmitBtnClick" type="primary">提交</el-button>
        <el-button @click="onCancelBtnClick" type="primary">取消</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
import Cookies from 'js-cookie'
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
export default {

  components: {},

  activated () {
    this.loadVersionUpgradeHistories();
  },
  mounted () {

  },
  data () {
    return {
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block', 'image'],
        [{ header: 1 }, { header: 2 }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ direction: 'rtl' }],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ color: [] }, { background: [] }],
        [{ font: [] }],
        [{ align: [] }],
        ['clean']
      ],
      uploadUrl: '',
      histories: [],
      queryForm: {},
      createOrUpdateForm: {
        id: null,
        versionNo: null,
        richContent: null,
      },
      publishVersionUpgradeShow: false,
      operation: 'create', // create  edit
      pageArgs: {
        pageNo: 1,
        pageSize: 20,
        total: 0,
      }
    };
  },

  methods: {
    // 图片上传前
    uploadBeforeUploadHandle (file) {
      if (
        file.type !== 'image/jpg' &&
        file.type !== 'image/jpeg' &&
        file.type !== 'image/png' &&
        file.type !== 'image/gif'
      ) {
        this.$message.error(this.$t('upload.tip', { format: 'jpg、png、gif' }))
        return false
      }
    },
    // 上传图片成功
    uploadSuccessHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.quillEditor.insertEmbed(
        this.quillEditor.getSelection().index,
        'image',
        res.data.url
      )
    },
    // 加载富文本编辑器
    initQuill () {
      console.log(document.getElementById('J_quillEditor'));
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      // 自定义上传图片功能 (使用element upload组件)
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']
        }/oss/file/upload?token=${Cookies.get('token')}`
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.createOrUpdateForm.richContent = this.quillEditor.root.innerHTML
      })
    },
    /**
     * 加载版本更新历史
     */
    loadVersionUpgradeHistories () {
      this.$http.get(`/sys/sysVersionUpgrade/page?pageNo=${this.pageArgs.pageNo}&pageSize=${this.pageArgs.pageSize}`)
        .then(({ data: result, status: httpStatus }) => {
          if (result.code === 0) {
            this.histories = result.data.list
            this.pageArgs.total = result.data.total
          } else {
            this.$message({
              type: 'error',
              message: result.msg
            })
          }
        })
    },
    // 新增按钮点击
    onAddBtnClick () {
      this.publishVersionUpgradeShow = true;
      this.operation = 'create';
      this.$nextTick(() => {
        this.initQuill()
      })
    },

    // 编辑按钮点击
    async onEditBtnClick (id) {
      this.publishVersionUpgradeShow = true;
      this.operation = 'edit';
      await this.getDetail(id);
      await this.initQuill();

    },

    onCancelBtnClick () {
      this.$refs['createOrUpdateForm'].resetFields();
      this.publishVersionUpgradeShow = false;
      this.operation = null;
      this.quillEditor = null;
    },

    /**
     * 翻页
     */
    onCurrentPageChanged (pageNo) {
      this.pageArgs.pageNo = pageNo
      this.loadVersionUpgradeHistories()
    },

    /**
     * 提交
     */
    onSubmitBtnClick () {
      let url = this.operation === 'create' ? `/sys/sysVersionUpgrade/publish` : '/sys/sysVersionUpgrade/update';
      this.$http.post(url, this.$data.createOrUpdateForm)
        .then(({ data: rst, status: httpStatus }) => {
          if (httpStatus !== 200) {
            this.$message({
              type: 'error',
              message: '请求失败'
            })
          } else if (rst.code !== 0) {
            this.$message({
              type: 'error',
              message: rst.msg
            });
          } else {
            this.$message({
              type: 'success',
              message: '提交成功'
            });

            this.$refs['createOrUpdateForm'].resetFields();
            this.publishVersionUpgradeShow = false;
            this.loadVersionUpgradeHistories();
          }
        })
    },

    /**
     * 加载详情
     * @param id
     */
    getDetail (id) {
      this.$http.get(`/sys/sysVersionUpgrade/detail/${id}`)
        .then(({ status: httpStatus, data: epmetRst }) => {
          if (httpStatus !== 200) {
            this.$message({
              type: 'error',
              message: '请求失败'
            })
          } else if (epmetRst.code != 0) {
            this.$message({
              type: 'error',
              message: epmetRst.msg
            })
          } else {
            this.createOrUpdateForm = epmetRst.data;
            this.quillEditor.root.innerHTML = this.createOrUpdateForm.richContent

          }
        })
    }
  }
}
</script>

<style scoped lang="css">
::v-deep .ql-toolbar {
  margin-top: 36px;
}
</style>
