<template>
  <div class="add-help-page">
    <Card v-if="loading" class="loading-card">
      <Spin fix size="large" />
    </Card>
    <Card v-else class="main_card">
      <div class="main_info">
        <div class="head">
          <Icon type="md-bookmark" color="#2d8cf0" :size="28" />
          <label>{{ title }}</label>
        </div>
        <div class="item">
          <label class="label">类目：</label>
          <Select
            placeholder="请选择类目"
            v-model="saveDTO.helpCategoryId"
            style="width: 400px;"
          >
            <Option v-for="item in categoryList" :value="item.helpCategoryId" :key="item.helpCategoryId">{{item.name}}</Option>
          </Select>
          <Button
            type="primary"
            @click="btnSelect"
            style="margin-left:20px;"
          >添加</Button
          >
        </div>
        <div class="item">
          <label class="label">标题：</label>
          <Input
            placeholder="请填写帮助标题，20字以内"
            v-model="saveDTO.title"
            :maxlength="20"
            style="width: 400px"
          />
        </div>
        <div class="item">
          <label class="label">详情描述：</label>
          <div class="editor-con">
            <Spin fix v-if="editorLoading">
              <Icon type="ios-loading" size="30" color="#2d8cf0" class="spin-icon-load"></Icon>
              <div>上传中( {{editorUploadPercent}}% )...</div>
            </Spin>
            <quill-editor
              v-model="saveDTO.detail"
              ref="myQuillEditor"
              :options="editorOption"
              class="detail-editor"
            ></quill-editor>
          </div>
        </div>

        <Upload
          :action="uploadImgUrl"
          ref="uploadImg"
          v-show="false"
          :headers="{token: $store.state.admin.token, adminId: $store.state.admin.uid}"
          :before-upload="imgBoforeUpload"
          :on-progress="uploadOnProgress"
          :on-success="imgUploadSuccess"
          :on-error="imgUploadErr"
          accept=".jpg, .jpeg, .png, .gif"
        />
        <Upload
          :action="uploadVideoUrl"
          ref="uploadVideo"
          v-show="false"
          :headers="{token: $store.state.admin.token, adminId: $store.state.admin.uid}"
          :before-upload="videoBoforeUpload"
          :on-progress="uploadOnProgress"
          :on-success="videoUploadSuccess"
          :on-error="videoUploadErr"
          accept=".mp4, .mkv"
        />
        <div class="footer-con">
          <Button
            type="default"
            @click="handleCancel"
            style="margin-right: 30px"
          >取消</Button
          >
          <Button
            type="primary"
            @click="handleSubmit"
          >确定</Button
          >
        </div>
      </div>
    </Card>
    <Modal
      title="添加类目"
      v-model="isAddCategory"
      @on-cancel="cancelCategory"
    >
      <div class="model-item">
        <Input v-model="name" placeholder="请输入类目名称"/>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          @click="handleCategory"
        >
          确定
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { mapMutations } from 'vuex'
import { formatTime, getPosterFromVideoUrl } from '@/libs/tools'
import { uploadImgUrl, uploadVideoUrl } from '@/api/apiConfig'
import { apiVerify } from '@/api/apiVerify'

export default {
  name: 'add-coupon',
  components: {
    Tables
  },
  computed: {
    title () {
      if (this.routeName === 'edit_help') {
        return '编辑帮助'
      } else {
        return '新建帮助'
      }
    },
    isAdd () {
      return this.routeName === 'add_help'
    },
    isEdit () {
      return this.routeName === 'edit_help'
    },
    platform () {
      return this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
    },
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  },
  data () {
    return {
      routeName: '',
      loading: false,
      isAddCategory: false,
      skuList: [],
      saveDTO: {
        detail: '', // 详细
        helpCategoryId: '', // 类目编号
        title: '' // 帮助标题
      },
      name: '', // 类目名称
      categoryList: [],
      uploadImgUrl,
      uploadVideoUrl,
      editorOption: {
        placeholder: '请输入内容...',
        modules: {
          toolbar: [
            [
              'bold',
              'italic',
              { header: 2 },
              'blockquote',
              { list: 'ordered' },
              { list: 'bullet' },
              { align: [] }
            ],
            ['image', 'video']
          ]
        }
      },
      editorLoading: false,
      editorUploadPercent: 0
    }
  },
  mounted () {
    this.initData()
    this.categoryInfo()
    this.editor.getModule('toolbar').addHandler('image', this.imgHandler)
    this.editor.getModule('toolbar').addHandler('video', this.videoHandler)
  },
  methods: {
    ...mapMutations(['closeTag']),
    requestBannerDetail (infoId) {
      this.api({
        apiName: 'searchInfoId',
        postdata: infoId,
        success: (res) => {
          this.saveDTO = res.data
        }
      })
    },
    initData () {
      let routeName = this.$route.name
      console.log(routeName)
      let infoId = this.$route.query.infoId
      this.routeName = routeName
      if (routeName == 'edit_help') {
        this.requestBannerDetail(infoId)
      } else {
        this.loading = false
      }
    },
    handleCancel () {
      let title = '已取消'
      let route = this.$route
      let toRouteName = 'help_page'
      this.closeTag({ route, toRouteName })
      this.$Notice.success({ title })
    },
    handleSubmit () {
      let { saveDTO } = this
      if (saveDTO.helpCategoryId == '') {
        return this.$Notice.warning({ title: '请选择类目名称！' })
      }
      if (saveDTO.title == '') {
        return this.$Notice.warning({ title: '请输入类目标题！' })
      }
      if (saveDTO.detail == '') {
        return this.$Notice.warning({ title: '请输入详情描述！' })
      }
      let apiName = this.isAdd ? 'addHelp' : 'updateHelp'
      let title = this.isAdd ? '添加成功！' : '编辑成功！'
      this.api({
        apiName,
        postdata: saveDTO,
        success: (res) => {
          // 关闭当前标签页
          let route = this.$route
          let toRouteName = 'help_page'
          this.closeTag({ route, toRouteName })
          this.$Notice.success({ title })
        }
      })
    },

    btnSelect () {
      this.isAddCategory = true
    },
    handleCategory () {
      let { name } = this
      if (!name) {
        this.$Notice.warning({ title: '请输入类目名称！' })
        return
      }
      let saveDTO = {
        name
      }
      this.api({
        apiName: 'addCategory',
        postdata: saveDTO,
        complete: () => {
          this.isAddCategory = false
        },
        success: (res) => {
          this.categoryInfo()
          this.name = ''
          this.$Notice.success({ title: `添加成功！` })
        }
      })
    },
    cancelCategory () {
      this.name = ''
    },
    categoryInfo () {
      this.api({
        apiName: 'helpCategoryList',
        postdata: this.category,
        complete: () => {
          // this.loading = false
        },
        success: (res) => {
          this.categoryList = res.data.records
        }
      })
    },
    imgHandler (image) {
      if (image) {
        this.$refs.uploadImg.$el.querySelector('[type=file]').click()
      }
    },
    videoHandler (video) {
      if (video) {
        this.$refs.uploadVideo.$el.querySelector('[type=file]').click()
      }
    },

    uploadOnProgress (event, file, fileList) {
      this.editorUploadPercent = parseFloat(event.percent).toFixed(1)
    },
    imgBoforeUpload (file) {
      if (file.size >= 50 * 1024 * 1024) {
        this.$Notice.warning({ title: '上传图片不得超过50MB！' })
        return false
      }
      this.editorUploadPercent = 0
      this.editorLoading = true
    },
    imgUploadSuccess (res, file, fileList) {
      this.editorLoading = false
      apiVerify({
        res: { data: res },
        success: () => {
          let url = res.data
          let addImageRange = this.editor.getSelection()
          let newRange = 0 + (addImageRange !== null ? addImageRange.index : 0)
          this.editor.insertEmbed(newRange, 'simpleImg', {
            url,
            width: '60%',
            marginLeft: '50%',
            transform: 'translate(-50%)'
          })
          this.editor.setSelection(1 + newRange)
        }
      })
    },
    imgUploadErr () {
      this.editorLoading = false
      this.$Notice.error({ title: '上传失败，请稍后再试！' })
    },

    videoBoforeUpload (file) {
      if (file.size >= 50 * 1024 * 1024) {
        this.$Notice.warning({ title: '上传视频不得超过50MB！' })
        return false
      }
      this.editorUploadPercent = 0
      this.editorLoading = true
    },
    videoUploadSuccess (res, file, fileList) {
      this.editorLoading = false
      apiVerify({
        res: { data: res },
        success: () => {
          let url = res.data
          let addVideoRange = this.editor.getSelection()
          let newRange = 0 + (addVideoRange !== null ? addVideoRange.index : 0)
          this.editor.insertEmbed(newRange, 'simpleVideo', {
            url,
            controls: 'controls',
            width: '60%',
            marginLeft: '50%',
            transform: 'translate(-50%)',
            poster: getPosterFromVideoUrl(url)
          })
          this.editor.setSelection(1 + newRange)
        }
      })
    },
    videoUploadErr () {
      this.editorLoading = false
      this.$Notice.error({ title: '上传失败，请稍后再试！' })
    }

  }
}
</script>

<style scoped lang="less">
  .add-help-page {
    height: 100%;
    min-width: 1000px;
    // position: relative;

    .loading-card {
        height: 100%;
      }
    .main_card{
      overflow: hidden;
      .main_info{
      .head {
        color: #17233d;
        font-size: 18px;
        font-weight: bold;
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        i {
          margin-right: 10px;
        }
      }
      .item {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
      }
      .item .label {
        display: block;
        width: 200px;
        text-align: right;
      }
      .item .editor-con {
        position: relative;
        width: 600px;
        .spin-icon-load {
          animation: ani-demo-spin 1s linear infinite;
        }
        .ivu-spin {
          border: 1px solid #dcdee2;
          border-radius: 5px;
        }
        .describt-detail{
          width: 100%;
          height: 800px;
          overflow-y: auto;
          padding: 10px;
          border: 1px solid  #dcdee2;
          border-radius: 5px;
        }
        .detail-editor {

          /deep/ .ql-toolbar {
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
          }
          /deep/ .ql-container {
            height: 800px;
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;
          }
        }
      }

      .footer-con {
        width: 600px;
        display: flex;
        justify-content:space-around;
        // padding: 30px 200px;
        margin-left: 200px;
      }
    }
    }
  }
</style>
