<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="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 === 1" 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="#"
          :show-file-list="false"
          :before-upload="val => beforeUpload(val, 'web_img')">
          <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_uri')"></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"
          action="#"
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="val => beforeUpload(val, 'mobile_terminal_img')">
          <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_uri')"></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"
            action="#"
            class="file-uploader"
            ref="upload"
            :show-file-list="false"
            :before-upload="val => beforeUpload(val, 'enclosure')">
            <el-button slot="trigger" size="small" type="primary" :disabled="isDetails">上传文件</el-button>
          </el-upload>
          <p class="des">
            <i class="el-icon-loading" v-if="enclosure_loading"></i>
            <i class="el-icon-circle-check" v-if="!enclosure_loading && 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_uri')"></i>
          </span>
        </div>
      </el-form-item>
      <el-form-item label="上传视频：" class="file-upload">
        <div style="padding-top:6px;height:36px;">
          <el-upload :disabled="isDetails" action="#" class="file-uploader" ref="upload" :show-file-list="false" :before-upload="val => beforeUpload(val, 'video')">
            <el-button slot="trigger" size="small" type="primary" :disabled="isDetails">上传视频</el-button>
          </el-upload>
          <p class="des">
            <i class="el-icon-loading" v-if="video_loading"></i>
            <i class="el-icon-circle-check" v-if="!video_loading && 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_uri')"></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 { fileUpload } from '@/api/system'
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: ''
}
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),
      web_img_loading: '',
      mobile_terminal_img_loading: '',
      enclosure_loading: '',
      video_loading: '',
      rules: {
        project_id: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        type_id: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ]
      }
    }
  },
  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.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 = splitStrLast(this.form.enclosure_uri, '/')
      // }
      // if (this.form.video_uri) {
      //   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()
        }
      }
    },
    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)) {
          this.fetchUpload(file, 'image', target)
        } else {
          errorMsg = '上传图片格式错误，只允许png/jpg格式'
        }
      } else if (target === 'enclosure') {
        const typeList = ['doc', 'docx', 'pdf', 'xls', 'xlsx']
        if (typeList.includes(suffix)) {
          this.fetchUpload(file, 'file', target)
        } else {
          errorMsg = '上传附件格式错误，只允许word/excel/pdf格式'
        }
      } else {
        if (suffix === 'mp4') {
          this.fetchUpload(file, 'file', target)
        } else {
          errorMsg = '上传附件格式错误，只允许mp4格式'
        }
      }
      if (errorMsg) this.$message.error(errorMsg)
      return false
    },
    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] = ''
      if (['enclosure_uri', 'video_uri'].includes(target)) {
        this.form[target + '_name'] = ''
      }
    },
    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
          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
    },
    fileDownload(fileUrl, fileName) {
      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标签
    },
    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 = []
            }
          }
        })
      }
    },
    fetchUpload(file, type, target) {
      const formData = new window.FormData()
      formData.append('file', file)
      formData.append('type', type)
      this[target + '_loading'] = '1'
      fileUpload(formData).then(res => {
        this[target + '_loading'] = ''
        if (res.code === 0 && res.message === 'SUCCESS') {
          this.form[target + '_uri'] = res.data[0].full_path
          this.form[target + '_title'] = res.data[0].title
          this.form[target + '_size'] = res.data[0].size + ''
        }
      })
    }
  }
}
</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>