<template>
  <el-dialog :title="!dataForm.productId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible"
    @close="handlereset" lock-scroll width="750px">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px">
      <!-- <el-form-item label="所属分类" prop="poids">
        <el-cascader v-model="dataForm.poids" :options="categorys" :props="props" clearable></el-cascader>
      </el-form-item> -->
      <!-- <el-form-item label="商品类型" prop="goodsType">
        <el-select v-model="dataForm.goodsType" placeholder="请选择">
          <el-option v-for="item in goodsTypeList" :key="item.dictType" :label="item.dictValue" :value="item.dictType">
          </el-option>
        </el-select>
      </el-form-item> -->
      <!-- 关联的图书ids --> 
      <el-form-item label="主题" prop="title">
        <el-input v-model="dataForm.title" placeholder="请输入打卡主题"></el-input>
      </el-form-item>
      <el-form-item label="打卡索引" prop="days">
        <el-input v-model="dataForm.days" placeholder="打卡第N天，例如：1,2,3"></el-input>
      </el-form-item>
      <el-form-item label="卡片" >
        <el-upload :limit="1" class="el-uploadfeng "
          :class="{ uoloadSty: dataForm.showBtnDealImg, disUoloadSty: dataForm.noneBtnImg }"
          :action="baseUrl + '/oss/fileoss'" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :file-list="fileList" :on-success="handlePicSuccess" accept=".jpeg,.jpg,.gif,.png" :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dataForm.productImages" alt="">
        </el-dialog>
      </el-form-item>     
      <!-- <el-form-item label="音频" prop="productImages">
        <el-upload :limit="1" class="el-uploadfeng "
          :class="{ uoloadSty: dataForm.showBtnDealImg, disUoloadSty: dataForm.noneBtnImg }"
          :action="baseUrl + '/oss/fileoss'" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :file-list="fileList" :on-success="handlePicSuccess" accept=".jpeg,.jpg,.gif,.png" :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <audio id="resource" :src="dataForm.voices" controls  v-show='true'></audio>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dataForm.productImages" alt="">
        </el-dialog>
      </el-form-item> -->

      <el-form-item label="视频" >
        <el-upload :limit="1" class="el-uploadvideo "
          :class="{ uoloadSty: dataForm.showBtnDealImg, disUoloadSty: dataForm.noneBtnImg }"          
          :action="baseUrl + '/oss/fileoss'"
          :file-list="videoList" :on-success="videohandlePicSuccess" accept=".mp4" :on-remove="videohandleRemove">
          <!-- <i class="el-icon-plus"></i> -->
          <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
        </el-upload>
        <div>          
          <video controls width="250" v-if="dataForm.video != ''">   
            <source :src="dataForm.video" type="video/mp4" />
            
          </video>
        </div>
      </el-form-item>

      <el-form-item label="打卡描述" prop="productDetails">
        <quill-editor v-model="dataForm.productDetails" ref="myQuillEditor" :options="editorOption"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" 
          @ready="onEditorReady($event)" class="shangpin_editor">
        </quill-editor>        
      </el-form-item>
      <!-- <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handlereset">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>  
</template>

<script>
  import {
    quillEditor
  } from 'vue-quill-editor'
  import global from '../../common/common.vue' //引入共用组间

  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  export default {
    data() {
      return {        
        baseUrl: global.baseUrl,        
        visible: false,
        categorys: [],
        fileList: [], // 封面图
        swiperfileList: [],
        dialogVisible: false,
        props: {
          value: "catId",
          label: "name",
          children: "children",
          checkStrictly: true
        },
        dataForm: {         
          productId: 0,
          limitCountImg: 1, // 图片数量
          productImageList: '', // 轮播图
          showBtnDealImg: true,
          noneBtnImg: false,
          title: '',          
          productPid: '',
          productImages: '',
          shupingid: null,
          voices: '',
          video: '', // 视频地址
          days:''
                   
        },
        videoList:[],
        dataRule: {
          title: [{
            required: true,
            message: '书评标题不能为空',
            trigger: 'blur'
          }],          
         
          productImages: [{
            required: true,
            message: '商品图不能为空',
            trigger: 'blur'
          }],
          
        },
        // 富文本编辑器配置
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
              ['blockquote', 'code-block'], // 引用  代码块
              [{
                header: 1
              }, {
                header: 2
              }], // 1、2 级标题
              [{
                list: 'ordered'
              }, {
                list: 'bullet'
              }], // 有序、无序列表
              [{
                script: 'sub'
              }, {
                script: 'super'
              }], // 上标/下标
              [{
                indent: '-1'
              }, {
                indent: '+1'
              }], // 缩进
              [{
                direction: 'rtl'
              }], // 文本方向
              [{
                size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36']
              }], // 字体大小
              [{
                header: [1, 2, 3, 4, 5, 6]
              }], // 标题
              [{
                color: []
              }, {
                background: []
              }], // 字体颜色、字体背景颜色
              // [{ font: ['songti'] }], // 字体种类
              [{
                align: []
              }], // 对齐方式
              ['clean'], // 清除文本格式
              ['image', 'video'] // 链接、图片、视频
            ]
          },
          placeholder: '请输入正文'
        },
      }
    },
    created() {
      
    },
  methods: {    
    init(id,bookid) {
      this.productPid = bookid
        this.dataForm.shupingid = id || null
        console.log(id,this.productPid,'this.productPid')
        this.dataForm.productId = bookid || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.productId) {
            this.$http({
              url: this.$http.adornUrl(`/book/task/info/${id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              console.log(data,666)
              if (data && data.code === 0) {
                this.dataForm.title = data.bookTaskEntity.heading
                this.dataForm.video = data.bookTaskEntity.video
                this.dataForm.days = data.bookTaskEntity.days
                this.dataForm.productImages = data.bookTaskEntity.images 
                this.dataForm.productDetails = data.bookTaskEntity.content             
                console.log(this.dataForm.video, 'this.dataForm.video')
                this.videoList.push({
                  name: data.bookTaskEntity.heading,
                  url: data.bookTaskEntity.video
                  })
                if (data.bookTaskEntity.images != "") {
                  var img = {
                    name: '',
                    url: data.bookTaskEntity.images
                  }
                  var attr = []
                  attr.push(img)
                  this.fileList = attr
                }
               // else {                
               // console.log(data.bookBuyConfig.productImageList)
               // let arr = []
              //  let arr1 = []

              //   arr = data.bookBuyConfig.productImageList.split(',');
              //   console.log(arr)
              //   arr.forEach((item, index) => {
              //     arr1.push({
              //       name: index,
              //       url: item
              //     })
              //   });
              //   this.swiperfileList = arr1
              // }
                
              } 
            })
          }
        })
      },
   
   
      dealImgChange(file, fileList) {
        this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
      },
      // 表单提交
    dataFormSubmit() {      
     // console.log('userid', this.$store.state.user.id)        
        this.$refs['dataForm'].validate((valid) => {    
          if (valid) {
            this.$http({             
              url: this.$http.adornUrl(`/book/task/${!this.dataForm.shupingid ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'bookid': this.productPid, 
                'heading': this.dataForm.title,               
                'images': this.dataForm.productImages,                
                'content': this.dataForm.productDetails,   
                'days': this.dataForm.days, 
                'video': this.dataForm.video,
                // 'video': "https://ehh-private-01.oss-cn-beijing.aliyuncs.com…3/08/28/91fd5a4c35c34763abca5d2929637164movie.mp4",
                'id': this.dataForm.shupingid || undefined,
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.dataForm.productDetails = ''
                    this.dataForm.video = ''
                    this.videoList = []
                    this.$refs['dataForm'].resetFields()
                    // this.$refs['dataForm'].reset()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      changeTime(e) {
        console.log(e)
    },    
  
      handlePictureCardPreview(file) {
        this.dataForm.productImages = file.url;
        this.dialogVisible = true;
      },
      bannerHandlePicSuccess(res, file) {
        // 轮播图上传成功
        if (res.msg == "success") {
          this.swiperfileList.push({
            name: file.name,
            url: res.url
          })
          this.dataForm.productImages = res.url
          console.log(this.swiperfileList,this.dataForm.productImages)
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      },
      // 字符串图片地址
      getStringImgUrl() {
        let arr = this.swiperfileList.map(item => item.url)
        if (arr.length <= 0) {
          return null
        } else {
          return arr.toString()
        }
      },
      handlePicSuccess(res, file) {
        // console.log(res,'res')
        if (res.msg == "success") {
          this.dataForm.productImages = res.url;
          this.fileList.push({
            name: file.name,
            url: res.url
          })
          this.dataForm.productImages = res.url
          console.log(this.dataForm.productImages,'productImages')
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
    },

    videohandlePicSuccess(res, file) {
        console.log(res,'res')
        if (res.msg == "success") {
          // this.dataForm.productImages = res.url;
          this.videoList.push({
            name: file.name,
            url: res.url
          })
          this.dataForm.video = res.url
          // console.log(this.dataForm.productImages,'productImages')
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      },
      
      handleRemove(file, fileList) {
        this.dataForm.productImages = '';
        this.fileList = fileList
        this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
    },
    videohandleRemove(file, fileList) {
        this.dataForm.video = '';
        this.videoList = fileList
        
    },
      handlereset() {
        this.fileList = [],
          this.videoList = [] // 清空视频列表
        this.dataForm.video = ''
          this.visible = false
        this.swiperfileList = []
        this.$refs['dataForm'].resetFields()
        this.dataForm.productDetails = ''
        // this.$refs['dataForm'].reset()
      },
      // 失去焦点事件
      onEditorBlur(quill) {
       console.log('editor blur!', quill)       
      },
      // 获得焦点事件
      onEditorFocus(quill) {
        //console.log('editor focus!', quill)
      },
      // 准备富文本编辑器
      onEditorReady(quill) {
       // console.log('editor ready!', quill)
      },
      
    },
    components: {
      quillEditor
  },
  mounted() {
    this.$bus.$on("haveBookIds", (data) => {  
      // console.log('haveBookIds', data)              
        data.bookIds.length > 0 ? this.dataForm.Books = data.bookIds : this.dataForm.Books = []
      });
  },

    watch: {
      visible: {
        handler(val, oldVal) {
          // this.getGoodsTypeList()
        },
        deep: true
      },
    }
  }
</script>

<style lang="less">
/deep/ .el-uploadvideo .el-upload-list li{height: auto !important;}
  // .disUoloadSty {
  //   .el-upload--picture-card {
  //     display: none;
  //     /* 上传按钮隐藏 */
  //   }
  // }

  // .el-form-item {
  //   /deep/ .el-form-item__label {
  //     font-size: 12px;
  //   }
  // }

  .el-uploadfeng {
   .el-upload-list__item {
      width: 120px;
      height: 120px;
    }

    .el-upload--picture-card {
      width: 120px;
      height: 120px;
      line-height: 120px;
    }
  }

  .shangpin_editor .ql-editor {
    height: 150px;
  }
</style>
