<template>
  <div id="vip-setting">
    <el-form
      v-if="ruleForm"
      label-position="right"
      label-width="80px"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
    >
      <h3>认证产品编辑</h3>
      <br />
      <el-form-item label="中文名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="英文名称" prop="english_name">
        <el-input v-model="ruleForm.english_name"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="ruleForm.status_name" placeholder="请选择" @change="changeSelect">
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input v-model="ruleForm.order"></el-input>
      </el-form-item>
      <section class="prices">
        <el-form-item label="原价" prop="origin_price">
          <el-input v-model="ruleForm.origin_price"></el-input>
        </el-form-item>
        <el-form-item label="现价" prop="real_price">
          <el-input v-model="ruleForm.real_price"></el-input>
        </el-form-item>
        <el-form-item label="会员价" prop="vip_price">
          <el-input v-model="ruleForm.vip_price"></el-input>
        </el-form-item>
      </section>
      <el-form-item label="配图" prop="img">
        <el-upload
          class="img-uploader"
          action="/api/admin/cert/uploadImg"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="ruleForm.img" :src="ruleForm.img" class="img" />
          <i v-else class="el-icon-plus img-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="简介" prop="introduction">
        <el-input type="textarea" v-model="ruleForm.introduction"></el-input>
      </el-form-item>
      <el-form-item label="证书" prop="content">
        <el-input type="textarea" v-model="ruleForm.content"></el-input>
      </el-form-item>
      <el-form-item label="问卷" prop="questionnaire">
        <el-input v-model="ruleForm.questionnaire"></el-input>
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <quill-editor
          v-model="ruleForm.description"
          ref="quillEditor"
          class="editer"
          :options="editorOption"
          @ready="onEditorReady($event)"
        ></quill-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" @click="clickCancel">取消</el-button>
      </el-form-item>
    </el-form>
    <el-upload
      style="display: none;"
      action="/api/admin/cert/uploadImg"
      :show-file-list="false"
      :on-success="handleEditorImgSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <el-button ref="chooseEditorImg" slot="trigger" size="small" type="primary">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script>
const ruleForm = 'ruleForm'
// 插入图片或其他元素到编辑器的位置
let addRange = { index: 0 }

export default {
  data() {
    return {
      options: [],
      imageUrl: '',
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],               // custom button values
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
            [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
            [{ 'direction': 'rtl' }],                         // text direction
            [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'font': [] }],
            ['clean'],                                         // remove formatting button
            ['link', 'image'],
          ],
          imageResize: {}
        }
      },
      ruleForm: null,
      rules: {
        name: [
          { required: true, message: '请输入中文', trigger: 'blur' },
        ],
        english_name: [
          { required: true, message: '请输入英文', trigger: 'blur' },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' },
        ],
        order: [
          { required: true, message: '请输入数字', trigger: 'blur' },
        ],
        id: [
          { required: true, message: '请输入数字', trigger: 'blur' },
        ],
        origin_price: [
          { required: true, message: '请输入数字', trigger: 'blur' },
        ],
        real_price: [
          { required: true, message: '请输入数字', trigger: 'blur' },
        ],
        vip_price: [
          { required: true, message: '请输入数字', trigger: 'blur' },
        ],
        img: [
          { required: true, message: '请上传图片', trigger: 'blur' },
        ],
        introduction: [
          { required: true, message: '请输入简介', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
        ],
      },
      // vip 列表
      list: [],
    }
  },
  computed: {
    editor() {
      return this.$refs.quillEditor.quill
    }
  },
  mounted() {
    this.getDetail()
    this.getStatus()
    setTimeout(() => {
      this.editor.getModule('toolbar').addHandler('image', this.imageHandle)
    }, 1000)
  },
  methods: {
    /**
     * 编辑图图片上传成功
     */
    handleEditorImgSuccess(res, file) {
      let url = res.data.file_url_abs
      this.editor.insertEmbed(addRange.index, 'image', url)
    },
    /**
     * 点击编辑器图片按钮事件
     * @param {boolean} state 一个不知道什么的状态
     */
    imageHandle(state) {
      if (state) {
        addRange = this.editor.getSelection()
        console.log({ addRange })
        this.$refs.chooseEditorImg.$el.click()
      }
    },
    /**
     * 状态选择变化
     */
    changeSelect(val) {
      this.ruleForm.status = val
      this.ruleForm.status_name = this.options.find(i => i.id === val).name
    },
    handleAvatarSuccess(res, file) {
      this.ruleForm.img = res.data.file_url_abs
    },
    beforeAvatarUpload(file) {
      return true
    },
    onEditorReady(editor) {

    },
    clickCancel() {
      this.$confirm('确认不保存已修改内容吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => { })
    },
    /**
     * 重置
     */
    resetForm() {
      this.$refs[ruleForm].resetFields()
    },
    /**
     * 提交
     */
    submitForm() {
      this.$refs[ruleForm].validate(async (valid) => {
        if (valid) {
          let res = await this.$post('/api/admin/cert/updateInfo', this.ruleForm)
          if (res.status < 0) {
            this.$message({
              message: res.info,
              type: 'error'
            })
          } else {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            setTimeout(() => {
              this.$router.go(-1)
            }, 1000)
          }
        } else {
          console.log('error submit!!');
          return false
        }
      })
    },
    async getStatus() {
      const id = this.$route.query.id
        , res = await this.$get("/api/admin/cert/getEnum", { id })
        , data = res.data
      this.options = data.status_name_list
    },
    /**
     * 获取详情数据
     */
    async getDetail() {
      const id = this.$route.query.id
        , res = await this.$post("/api/admin/cert/getDetail", { id })
        , data = res.data
      this.ruleForm = data
    },
  }
}
</script>

<style>
#vip-setting {
  padding: 20px;
}
.table {
  height: 100%;
  height: calc(100% - 80px);
}
.el-input {
  width: auto;
}
.prices {
  display: flex;
}
.editer {
  width: 940px;
  height: 600px;
  padding: 0 0 100px;
}
/* .img-uploader {
  width: 270px;
  height: 190px;
} */
.img-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.img-uploader .el-upload:hover {
  border-color: #409eff;
}
.img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.img {
  width: 270px;
  height: 190px;
  display: block;
}
</style>
