<template>
  <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" :class="`form-container ${options.type}`" >
    <div class="left">
      <el-form-item label="项目：" prop="project_id">
        <el-col :span="12">
          <el-select v-model="form.project_id" placeholder="请选择项目" size="small" style="width: 100%" clearable :disabled="isDetails">
            <el-option v-for="item in projects" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="类型：" prop="type_id">
        <el-col :span="12">
          <el-select v-model="form.type_id" placeholder="请选择类型" size="small" style="width: 100%" clearable :disabled="isDetails || !form.project_id">
            <el-option v-for="item in typeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="语言：" prop="language">
        <el-col :span="12">
          <el-select v-model="form.language" placeholder="请选择语言" size="small" style="width: 100%" multiple clearable :disabled="isDetails">
            <el-option v-for="item in langOptions" :label="item.label" :value="item.value" :key="item.value"></el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="标题：" prop="title" style="margin-right:15px;">
        <el-input v-model="form.title" placeholder="请输入标题" size="small" :disabled="isDetails"/>
      </el-form-item>
      <el-form-item label="跳转链接：" style="margin-right:15px;">
        <el-input v-model="form.uri" placeholder="请输入跳转链接" size="small" :disabled="isDetails"/>
      </el-form-item>
      <el-form-item v-if="pageType !== 2" label="摘要：" prop="abstract" :rules="{required: true, message: '请输入摘要', trigger: 'blur'}" style="margin-right:15px;">
        <el-input type="textarea" v-model="form.abstract" placeholder="请输入摘要" size="small" rows="4" :disabled="isDetails"/>
      </el-form-item>
      <el-form-item label="备注：" prop="remarks" style="margin-right:15px;">
        <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注" size="small" rows="4" :disabled="isDetails"/>
      </el-form-item>
      <el-form-item ref="el-form-item-tinymce" v-if="pageType !== 2" label="正文：" style="margin-right:15px;">
        <Tinymce ref="editor" v-model="form.content" :readonly="isDetails" :height="400" @blur="tinymceBlur" />
      </el-form-item>
      <!-- <el-form-item ref="el-form-item-tinymce" v-if="pageType !== 2" label="正文：" prop="content" :rules="{required: true, message: '请输入正文', trigger: 'blur'}" style="margin-right:15px;">
        <Tinymce ref="editor" v-model="form.content" :readonly="isDetails" :height="400" @blur="tinymceBlur" />
      </el-form-item> -->
    </div>
    <div class="right">
      <el-form-item label="web端图片：" class="file-upload avatar-upload">
        <el-upload
          :disabled="isDetails"
          class="avatar-uploader" action="https://webapp-pub.oss-cn-beijing.aliyuncs.com" :show-file-list="false" :before-upload="val => beforeUpload(val, 'web_img')" :on-success="(res, file) => handleSuccess(res, file, 'web_img')" :data="uploadData">
          <img v-if="form.web_img_uri" :src="form.web_img_uri" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="avatar-upload-bar" v-if="form.web_img_uri">
          <div class="avatar-preview">
            <i class="el-icon-zoom-in"></i>
            <el-image :src="form.web_img_uri" :preview-src-list="[form.web_img_uri]" :z-index="9999"/>
          </div>
          <div>
            <i class="el-icon-download" @click="handleDownloadFile('web_img_uri')"></i>
          </div>
          <div v-if="!isDetails">
            <i class="el-icon-circle-close" @click="handleClearFile('web_img')"></i>
          </div>
        </div>
        <p class="des">请上传文件，最多上传一张/份<br>支持：PNG、JPG</p>
      </el-form-item>
      <el-form-item label="移动端图片：" class="file-upload avatar-upload">
        <el-upload :disabled="isDetails" class="avatar-uploader" action="https://webapp-pub.oss-cn-beijing.aliyuncs.com" :show-file-list="false" :before-upload="val => beforeUpload(val, 'mobile_terminal_img')" :on-success="(res, file) => handleSuccess(res, file, 'mobile_terminal_img')" :data="uploadData">
          <img v-if="form.mobile_terminal_img_uri" :src="form.mobile_terminal_img_uri" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="avatar-upload-bar" v-if="form.mobile_terminal_img_uri">
          <div class="avatar-preview">
            <i class="el-icon-zoom-in"></i>
            <el-image :src="form.mobile_terminal_img_uri" :preview-src-list="[form.mobile_terminal_img_uri]" :z-index="9999"/>
          </div>
          <div>
            <i class="el-icon-download" @click="handleDownloadFile('mobile_terminal_img_uri')"></i>
          </div>
          <div v-if="!isDetails">
            <i class="el-icon-circle-close" @click="handleClearFile('mobile_terminal_img')"></i>
          </div>
        </div>
        <p class="des">请上传文件，最多上传一张/份<br>支持：PNG、JPG</p>
      </el-form-item>
      <el-form-item label="上传附件：" class="file-upload">
        <div style="padding-top:6px;height:36px;">
          <el-upload :disabled="isDetails" class="file-uploader" ref="upload" action="https://webapp-pub.oss-cn-beijing.aliyuncs.com" :show-file-list="false" :before-upload="val => beforeUpload(val, 'enclosure')" :on-success="(res, file) => handleSuccess(res, file, 'enclosure')" :data="uploadData">
            <el-button slot="trigger" size="small" type="primary" :disabled="isDetails">上传文件</el-button>
          </el-upload>
          <p class="des">
            <i class="el-icon-loading" v-if="fileLoading === 'enclosure'"></i>
            <i class="el-icon-circle-check" v-if="!fileLoading && form.enclosure_uri"></i>
            请上传文件，最多上传一份<br>支持：word、excel、pdf
          </p>
        </div>
        <div class="upload-file-display" v-if="form.enclosure_title">
          {{form.enclosure_title}}
          <span class="upload-file-bar">
            <i :class="isFilePreview(form.enclosure_title) ? 'el-icon-view':'el-icon-download'" @click="handleDownloadFile('enclosure_uri')"></i>
            <i v-if="!isDetails" class="el-icon-circle-close" @click="handleClearFile('enclosure')"></i>
          </span>
        </div>
      </el-form-item>
      <el-form-item label="上传视频：" class="file-upload">
        <div style="padding-top:6px;height:36px;">
          <el-upload :disabled="isDetails" class="file-uploader" ref="upload" action="https://webapp-pub.oss-cn-beijing.aliyuncs.com" :show-file-list="false" :before-upload="val => beforeUpload(val, 'video')" :on-success="(res, file) => handleSuccess(res, file, 'video')" :data="uploadData">
            <el-button slot="trigger" size="small" type="primary" :disabled="isDetails">上传视频</el-button>
          </el-upload>
          <p class="des">
            <i class="el-icon-loading" v-if="fileLoading === 'video'"></i>
            <i class="el-icon-circle-check" v-if="!fileLoading && form.video_uri"></i>
            请上传文件，最多上传一份<br>支持：MP4
          </p>
        </div>
        <div class="upload-file-display" v-if="form.video_title">
          {{form.video_title}}
          <span class="upload-file-bar">
            <i class="el-icon-view" @click="handleDownloadFile('video_uri')"></i>
            <i v-if="!isDetails" class="el-icon-circle-close" @click="handleClearFile('video')"></i>
          </span>
        </div>
      </el-form-item>
      <el-form-item label="开始时间：" prop="start_time" :rules="[{required: true, message: '请选择开始时间', trigger: 'change'}]">
        <el-date-picker v-model="form.start_time" type="datetime" placeholder="选择开始时间" size="small" clearable :disabled="isDetails"/>
      </el-form-item>
      <el-form-item label="结束时间：" :required="form.hasEndDate===1" class="mb-15">
        <el-col :span="7">
          <el-switch v-model="form.hasEndDate" :active-value="1" :inactive-value="0" active-text="有" inactive-text="无" :disabled="isDetails"></el-switch>
        </el-col>
        <el-col :span="16">
          <el-form-item v-if="form.hasEndDate" prop="end_time" :rules="[{required: true, message: '请选择结束时间', trigger: 'change'}, { type: 'date', validator: endDateChecked, trigger: 'change' }]">
            <el-date-picker v-model="form.end_time" type="datetime" placeholder="选择结束时间" size="small" clearable :disabled="isDetails" :picker-options="dateOptions"/>
          </el-form-item>
        </el-col>
      </el-form-item>
      <!-- <template>
        <el-form-item label="发布状态：" class="mb-15">
          <el-switch v-model="form.is_publish" :active-value="1" :inactive-value="0" active-text="开" inactive-text="关" :disabled="isDetails"></el-switch>
        </el-form-item>
        <el-form-item label="置顶状态：" class="mb-15" v-if="pageType !== 3">
          <el-switch v-model="form.is_top" :active-value="1" :inactive-value="0" active-text="开" inactive-text="关" :disabled="isDetails"></el-switch>
          <el-select v-model="form.weight" placeholder="请选择权重" size="small" clearable :disabled="isDetails">
            <el-option v-for="item in 10" :label="item" :value="item" :key="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推荐状态：" class="mb-15"  v-if="pageType === 1">
          <el-switch v-model="form.is_recommend" :active-value="1" :inactive-value="0" active-text="开" inactive-text="关" :disabled="isDetails"></el-switch>
        </el-form-item>
      </template> -->
      <template v-if="isDetails">
        <!-- <el-form-item label="发布状态：" class="mb-15">
          {{options.details.is_publish ? '开启' : '关闭'}}
        </el-form-item>
        <el-form-item label="置顶状态：" class="mb-15">
          {{options.details.is_top ? '开启' : '关闭'}} / {{form.weight}}
        </el-form-item>
        <el-form-item label="推荐状态：" class="mb-15">
          {{options.details.is_recommend ? '开启' : '关闭'}}
        </el-form-item> -->
        <el-form-item label="审核状态：" class="mb-15">
          {{options.details.audit_status | reviewStatus}}
        </el-form-item>
        <el-form-item label="审核评审：" class="mb-15">
          {{options.details.audit_remarks}}
        </el-form-item>
      </template>
      <el-form-item v-if="!isDetails" class="mb-15">
        <el-button @click="handleClose" size="mini">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" size="mini">保存</el-button>
      </el-form-item>
      <slot name="form-item-review" v-if="isDetails && hasAudit"/>
      <!-- <el-form-item v-if="isDetails">
        <el-button type="primary" @click="handleReview" size="mini">审核</el-button>
      </el-form-item> -->
    </div>
  </el-form>
</template>
<script>
import Tinymce from '@/components/Tinymce'
import { getProjectContentTypeList } from '@/api/contentManage'
import { getSignature } from '@/api/system'
import md5 from 'blueimp-md5'
import { mapGetters } from 'vuex'
import { formatToDate } from '@/utils/utils'
const splitStrLast = function(str, split) {
  const fileNameArr = str.split(split)
  const last = fileNameArr[fileNameArr.length - 1]
  return last
}
const defaultForm = {
  project_id: '',
  type_id: '',
  title: '',
  uri: '',
  abstract: '',
  remarks: '',
  content: '',
  web_img_uri: '',
  web_img_title: '',
  web_img_size: '',
  mobile_terminal_img_uri: '',
  mobile_terminal_img_title: '',
  mobile_terminal_img_size: '',
  enclosure_uri: '',
  enclosure_title: '',
  enclosure_size: '',
  video_uri: '',
  video_title: '',
  video_size: '',
  start_time: '',
  hasEndDate: 0,
  end_time: '',
  language: ['cn']
}
export default {
  props: {
    options: {
      type: Object
    }
  },
  components: { Tinymce },
  filters: {
    reviewStatus(val) {
      let text = '待审核'
      switch (val) {
        case 2:
          text = '已通过'
          break
        case 3:
          text = '已驳回'
          break
      }
      return text
    }
  },
  data() {
    return {
      typeList: [],
      form: Object.assign({}, defaultForm),
      fileLoading: '',
      uploadData: {},
      rules: {
        project_id: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        type_id: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        language: [
          { required: true, message: '请选择语言', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ]
      },
      langOptions: [
        { label: '中文', value: 'cn' },
        { label: '英文', value: 'en' }
      ]
    }
  },
  computed: {
    ...mapGetters(['projects', 'permissions']),
    pageType() {
      return this.options.pageType
    },
    // 审核权限
    hasAudit() {
      const map = {
        1: 'content-function-acticle-audit',
        2: 'content-function-advert-audit',
        3: 'content-function-imgtext-audit'
      }
      const type = this.pageType
      return this.permissions.includes(map[type])
    },
    isDetails() {
      return this.options.type === 'details'
    },
    isCreate() {
      return this.options.type === 'create'
    },
    isEdit() {
      return this.options.type === 'edit'
    },
    startTimestamp() {
      return formatToDate(this.form.start_time).getTime()
    },
    endTimestamp() {
      return formatToDate(this.form.end_time).getTime()
    },
    dateOptions() {
      return {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  watch: {
    'form.project_id': {
      handler: function(nv) {
        if (nv) {
          this.fetchContentTypeList()
        }
      },
      immediate: true
    }
  },
  created() {
    if (this.isDetails) {
      const details = this.options.details
      Object.keys(this.form).forEach(key => {
        if (typeof details[key] !== 'undefined') {
          this.form[key] = details[key]
        }
      })
      if (this.form.language) {
        this.form.language = this.form.language.split(',')
      }
      if (this.form.end_time) {
        this.form.hasEndDate = 1
        this.form.end_time = formatToDate(this.form.end_time)
      } else {
        this.form.end_time = ''
      }
      if (this.form.start_time === 0) {
        this.form.start_time = ''
      } else {
        this.form.start_time = formatToDate(this.form.start_time)
      }
      if (this.form.enclosure_uri && !this.form.enclosure_title) {
        this.form.enclosure_title = splitStrLast(this.form.enclosure_uri, '/')
      }
      if (this.form.video_uri && !this.form.video_title) {
        this.form.video_title = splitStrLast(this.form.video_uri, '/')
      }
    }
  },
  methods: {
    endDateChecked(rule, value, callback) {
      if (value) {
        if (this.endTimestamp < Date.now()) {
          callback(new Error('结束时间必须大于当前时间'))
        } else if (this.endTimestamp < this.startTimestamp) {
          callback(new Error('结束时间必须大于开始时间'))
        } else {
          callback()
        }
      }
    },
    handleSuccess(res, file, target) {
      this.fileLoading = ''
      const _file = file.raw
      this.form[target + '_uri'] = _file.src
      this.form[target + '_title'] = _file.name
      this.form[target + '_size'] = _file.size + ''
    },
    beforeUpload(file, target) {
      let errorMsg = ''
      const suffix = splitStrLast(file.name, '.')
      if (target === 'web_img' || target === 'mobile_terminal_img') {
        if (!['image/png', 'image/jpeg'].includes(file.type)) {
          errorMsg = '上传图片格式错误，只允许png/jpg格式'
        }
      } else if (target === 'enclosure') {
        const typeList = ['doc', 'docx', 'pdf', 'xls', 'xlsx']
        if (!typeList.includes(suffix)) {
          errorMsg = '上传附件格式错误，只允许word/excel/pdf格式'
        } else if (file.size > 50 * 1024 * 1024) {
          errorMsg = '附件大小不能超过 50MB'
        }
      } else {
        if (suffix !== 'mp4') {
          errorMsg = '上传附件格式错误，只允许mp4格式'
        } else if (file.size > 1024 * 1024 * 1024) {
          errorMsg = '视频文件大小不能超过 1GB！'
        }
      }
      if (errorMsg) {
        this.$message.error(errorMsg)
        return false
      } else {
        this.fileLoading = target
        const fileName = file.name
        const key = 'upload/cms-admin/' + md5(fileName + new Date().getTime()) + fileName.substr(fileName.lastIndexOf('.'))
        return new Promise((resolve, reject) => {
          getSignature()
            .then(response => {
              const { accessid, policy, signature, host } = response
              this.uploadData = { key, OSSAccessKeyId: accessid, policy, signature, success_action_status: '200' }
              file.src = `${host}/${key}`
              resolve(true)
            })
            .catch(err => {
              console.log(err)
              reject(err)
            })
        })
      }
    },
    handleClose() {
      this.$emit('drawFormClose')
      this.form = Object.assign({}, defaultForm)
    },
    handleDownloadFile(target) {
      const url = this.form[target]
      if (this.isFilePreview(url)) {
        window.open(url, '_blank')
      } else {
        this.fileDownload(url, url)
      }
    },
    handleClearFile(target) {
      this.form[target + '_uri'] = ''
      this.form[target + '_title'] = ''
      this.form[target + '_size'] = ''
    },
    tinymceBlur() {
      this.$refs['el-form-item-tinymce'].$emit('el.form.blur')
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        const form = { ...this.form }
        if (valid) {
          form.start_time = this.toUnitTimestamp(form.start_time) || 0
          if (form.hasEndDate === 1) {
            form.end_time = this.toUnitTimestamp(form.end_time) || 0
          } else {
            form.end_time = 0
          }
          delete form.hasEndDate
          form.language = form.language.join(',')
          this.$emit('drawFormSubmit', form)
        } else {
          return false
        }
      })
    },
    isFilePreview(url) {
      const suffix = splitStrLast(url, '.')
      if (['pdf', 'mp4'].includes(suffix)) {
        return true
      } else {
        return false
      }
    },
    toUnitTimestamp(time) {
      return formatToDate(time).getTime() / 1000
    },
    async fileDownload(fileUrl, fileName) {
      const suffix = splitStrLast(fileUrl, '.')
      if (['png', 'jpg'].includes(suffix)) {
        fileUrl = await this.getBase64(fileUrl)
      }
      const elink = document.createElement('a')// 创建一个a标签
      elink.download = fileName;// 设置a标签的下载属性
      elink.style.display = 'none';// 将a标签设置为隐藏
      elink.href = fileUrl;// 把之前处理好的地址赋给a标签的href
      document.body.appendChild(elink);// 将a标签添加到body中
      elink.click();// 执行a标签的点击方法
      // URL.revokeObjectURL(elink.href) // 下载完成释放URL 对象
      document.body.removeChild(elink)// 移除a标签
    },
    getBase64(url) {
      return new Promise((resolve, reject) => {
        var Img = new window.Image()
        var dataURL = ''
        Img.setAttribute('crossOrigin', 'Anonymous')
        Img.src = url + '?v=' + Math.random()
        Img.onload = function() {
          // 要先确保图片完整获取到，这是个异步事件
          var canvas = document.createElement('canvas') // 创建canvas元素
          var width = Img.width // 确保canvas的尺寸和图片一样
          var height = Img.height
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(Img, 0, 0, width, height) // 将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg') // 转换图片为dataURL
          resolve(dataURL)
        }
      })
    },
    fetchContentTypeList() {
      if (this.form.project_id) {
        getProjectContentTypeList(this.pageType, { project_id: this.form.project_id }).then((res) => {
          if (res.code === 0 && res.message === 'SUCCESS') {
            if (Array.isArray(res.data)) {
              this.typeList = res.data
            } else {
              this.typeList = []
            }
          }
        })
      }
    }
  }
}
</script>
<style scoped>
.form-container{
  padding-top:15px;
  display:flex;
  align-items: stretch;
}
.form-container.details ::-webkit-input-placeholder{
  color:transparent;
}
.form-container.details :-ms-input-placeholder{
  color:transparent;
}
.form-container.details ::placeholder{
  color:transparent;
}
.form-container .left{
  width:60%;
}
.form-container .right{
  flex-shrink: 0;
  flex: 1;
  box-sizing:border-box;
  border-left:1px dotted #eee;
}
.form-container:after{
  clear:both;
}
.el-form-item.file-upload .des{
  display:inline-block;
  color: #c9c9c9;
  line-height:18px;
  font-size:12px;
  position:relative;
}
.el-form-item.file-upload .des>i{
  position:absolute;
  left:-40px;
  top:10px;
  font-size:16px;
  color:#409EFF;
}
.el-form-item.file-upload .des>i.el-icon-circle-check{
  color: #67c23a;
}
.el-form-item.file-upload:not(.is-required){
  margin-bottom:15px;
}
.el-form-item.mb-15{
  margin-bottom:15px;
}
.file-upload .el-form-item__content{
  position:relative;
}
.avatar-upload-bar{
  position:absolute;
  left:1px;
  top:91px;
  width:120px;
  height:30px;
  border-radius:0 0 4px 0;
  overflow: hidden;
  background:rgba(0,0,0,.3);
  color:#fff;
  display:none;
  border-radius:0 0 6px 6px;
}
.avatar-upload .el-form-item__content:hover .avatar-upload-bar{
  display:flex;
}
.avatar-upload-bar>div{
  flex:1;
  position:relative;
  cursor:pointer;
}
.avatar-upload-bar>div>i{
  font-size:20px;
  width:100%;
  height:100%;
  text-align:center;
  line-height:30px;
}
.avatar-preview{
  cursor:zoom-in;
}
.avatar-preview .el-image{
  position:absolute;
  left:0;
  top:0;
  width:100%;
  height:100%;
  opacity:0;
  z-index:1;
}
.avatar-preview ::v-deep.el-image__preview{
  cursor: zoom-in;
}
.avatar-uploader, .file-uploader{
  display:inline-block;
  vertical-align: top;
  width:130px;
}
.avatar-uploader{
  height:130px;
}
.avatar-uploader ::v-deep.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
}
.avatar-uploader ::v-deep.el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.file-uploader{
  height:36px;
  font-size:0;
}
.file-uploader ::v-deep.el-upload{
  font-size:0;
}
.upload-file-display{
  padding-right:60px;
  text-overflow: ellipsis;
  transition: color .3s;
  white-space: nowrap;
  position:relative;
}
.upload-file-display:hover{
  background:#f5f7fa;
  color: #409eff
}
.upload-file-display:hover .upload-file-bar{
  display:block;
}
.upload-file-bar{
  display:none;
  position:absolute;
  right:10px;
  top:0;
  height:40px;
  color:#999;
  cursor:pointer;
}
.upload-file-bar>i:hover{
  color:#666;
}
</style>