import ImageCropper from '@/components/ImageCropper'

export default {
  beforeCreate () {
    this.form = this.$form.createForm(this)
    // this.form.getFieldDecorator('worktimes', {
    //   initialValue: []
    // })
  },
  data () {
    return {
      content: '',
      fileInfo: null,
      previewImage: '',
      imageList: [],
      previewVideo: '',
      videoList: [],
      addWorkTimesVisible: false,
      editWorkTimesVisible: false,
      previewImageVisible: false,
      previewVideoVisible: false,
      currentWorkTime: null,
      currentWorkTimeIndex: null,
      worktimes: [],
      workTimesItem: {
        validateStatus: '',
        help: ''
      },
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      config: {
        language: 'zh_cn',
        heightMin: 300,
        theme: 'green',
        toolbarSticky: false,
        imageUploadURL: this.uploadUrl,
        videoUploadURL: this.uploadUrl,
        events: {
          'froalaEditor.initialized': function () {
            // console.log('initialized')
          },
          'froalaEditor.image.uploaded': (e, editor, response) => {
            // console.log(e, editor, response)
          },
          'froalaEditor.contentChanged': (e, editor) => {
            this.form.setFieldsValue({ introduction_content: editor.html.get() })
            this.form.validateFields(['introduction_content'], (err, values) => {
              if (!err) {
                // console.log(values)
              }
            })
          }
        }
      }
    }
  },
  components: {
    ImageCropper
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    tags: {
      type: Array,
      default: () => []
    }
  },
  filters: {
    workTimesType (value) {
      const type = {
        SPECIAL_DAY: '日期范围',
        LEGAL_HOLIDAY: '法定日',
        SPECIAL_WEEKDAY: '每周',
        SPECIAL_MONTHDAY: '每月'
      }
      return type[value]
    },
    weekDays (value) {
      const type = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      const days = Array.isArray(value) ? value.map(i => {
        return type[i]
      }).join(' ,') : type[value]
      return days
    },
    monthDays (val) {
      const value = JSON.parse(JSON.stringify(val))
      const days = Array.isArray(value) ? value.sort((a, b) => {
        return a - b
      }).join(' , ') : value
      return days
    },
    legalType (value) {
      const type = {
        EVERYDAY: '每天',
        HOLIDAY: '节假日',
        REST: '休息日',
        WORKING: '工作日',
        value: 'WORKING'
      }
      return type[value]
    }
  },
  methods: {
    addWorkTime (data) {
      const worktimes = JSON.parse(JSON.stringify(this.worktimes))
      worktimes.push(data)
      this.worktimes = worktimes
      this.validateWorkTimes()
    },
    updateWorkTime (data) {
      this.worktimes.splice(this.currentWorkTimeIndex, 1, data)
    },
    eidtWorkTime (data, index) {
      this.currentWorkTime = Object.assign({}, data)
      this.currentWorkTimeIndex = index
      this.editWorkTimesVisible = true
    },
    deleteWorkTime (index) {
      const worktimes = this.worktimes
      worktimes.splice(index, 1)

      this.worktimes = worktimes
    },
    formatWorksTimes (worktimes) {
      const allWorktimes = []
      worktimes.forEach(item => {
        // 拆分数组
        if (Array.isArray(item.day)) {
          item.day.forEach(i => {
            allWorktimes.push(Object.assign({}, item, { day: i }))
          })
        } else {
          allWorktimes.push(item)
        }
      })
      return allWorktimes
    },
    validateWorkTimes () {
      if (this.worktimes.length === 0) {
        this.workTimesItem = {
          help: '请至少添加一项',
          validateStatus: 'error'
        }
        return false
      } else {
        this.workTimesItem = {
          help: ''
        }
        return true
      }
    },
    handleCancel () {
      this.$emit('input', false)
      this.form.resetFields()
      this.imageList = []
      this.introduction_content && (this.introduction_content = '')
    },
    handleImageCancel () {
      this.previewImageVisible = false
    },
    handleVideoCancel () {
      this.previewVideoVisible = false
    },
    handleImagePreview (file) {
      // console.log(file)
      this.previewImage = file.url || file.thumbUrl
      this.previewImageVisible = true
    },
    handleCropper (i) {
      const index = this.imageList.length
      this.imageList = this.imageList.concat({
        uid: index + '',
        name: '图' + index,
        url: i.link,
        thumbUrl: i.link,
        size: i.size,
        percent: 100
      })
      console.log(this.imageList)
    },
    handleImageChange (info) {
      const fileList = info.fileList

      if (info.file.status === 'uploading') {
        var reader = new FileReader() // 实例化文件读取对象
        reader.readAsDataURL(info.file.originFileObj) // 将文件读取为 DataURL,也就是base64编码
        reader.onload = (ev) => { // 文件读取成功完成时触发
          var dataURL = ev.target.result // 获得文件读取成功后的DataURL,也就是base64编码

          this.$refs.cropper.show({
            img: dataURL
          })
        }
        return
      }

      if (!info.file.status) {
        const index = fileList.findIndex(item => {
          return item.uid === info.file.uid
        })
        fileList.splice(index, 1)
      }
      this.imageList = fileList
    },
    beforeImageUpload (file) {
      const isImage = file.type.indexOf('image/png') > -1 || file.type.indexOf('image/jpeg') > -1

      if (!isImage) {
        this.$message.error('请上传JPG或PNG格式的图片')
      }

      let isLt = false
      const fileSize = file.size / 1024 / 1024

      if (isImage) {
        if (fileSize > 1) {
          this.$message.error('图片必须小于1M!')
        } else {
          isLt = true
        }
      }

      return isImage && isLt
    },
    handleVideoPreview (file) {
      // console.log(file)
      this.previewVideo = file.response.link
      this.previewVideoVisible = true
    },
    handleVideoChange (info) {
      let fileList = info.fileList

      if (info.file.status === 'done') {
        fileList = fileList.filter(item => {
          return item.percent === 100
        })
      }

      if (!info.file.status) {
        const index = fileList.findIndex(item => {
          return item.uid === info.file.uid
        })
        fileList.splice(index, 1)
      }

      this.videoList = fileList
    },
    beforeVideoUpload (file) {
      console.log(file.type)
      const isVideo = file.type.indexOf('video/mp4') > -1

      if (!isVideo) {
        this.$message.error('请上传MP4格式的视频')
      }

      let isLt = false
      const fileSize = file.size / 1024 / 1024

      if (isVideo) {
        if (fileSize > 100) {
          this.$message.error('视频大小必须小于100M!')
        } else {
          isLt = true
        }
      }

      return isVideo && isLt
    }
  },
  watch: {
    introduction_content (val) {
      this.form.setFieldsValue({ introduction_content: val })
    }
  }
}
