<template>
  <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" :class="`form-container ${options.page}-form`" >
    <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">
        <el-upload
          :disabled="isDetails"
          class="avatar-uploader"
          action="https://baidu.com"
          :show-file-list="false"
          :before-upload="val => beforeUpload(val, 'web_img_uri')">
          <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>
        <p class="des">请上传文件，最多上传一张/份<br>支持：PNG、JPG</p>
      </el-form-item>
      <el-form-item label="移动端图片：" class="file-upload">
        <el-upload
          :disabled="isDetails"
          action="https://baidu.com"
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="val => beforeUpload(val, 'mobile_terminal_img_uri')">
          <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>
        <p class="des">请上传文件，最多上传一张/份<br>支持：PNG、JPG</p>
      </el-form-item>
      <el-form-item label="上传附件：" class="file-upload">
        <el-upload
          :disabled="isDetails"
          action="https://baidu.com"
          class="file-uploader"
          ref="upload"
          :show-file-list="false"
          :before-upload="val => beforeUpload(val, 'enclosure_uri')">
          <el-button slot="trigger" size="small" type="primary" :disabled="isDetails">上传文件</el-button>
        </el-upload>
        <p class="des"><i class="el-icon-circle-check" v-if="form.enclosure_uri"></i>请上传文件，最多上传一份<br>支持：word、excel、pdf</p>
      </el-form-item>
      <el-form-item label="上传视频：" class="file-upload">
        <el-upload
          :disabled="isDetails"
          action="https://baidu.com"
          class="file-uploader"
          ref="upload"
          :show-file-list="false"
          :before-upload="val => beforeUpload(val, 'video_uri')">
          <el-button slot="trigger" size="small" type="primary" :disabled="isDetails">上传视频</el-button>
        </el-upload>
        <p class="des"><i class="el-icon-circle-check" v-if="form.video_uri"></i>请上传文件，最多上传一份<br>支持：MP4</p>
      </el-form-item>
      <el-form-item label="开始时间：" prop="start_time">
        <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-switch v-model="form.hasEndDate" :active-value="1" :inactive-value="0" active-text="有" inactive-text="无" :disabled="isDetails"></el-switch>
        <el-date-picker v-if="form.hasEndDate" v-model="form.end_time" type="datetime" placeholder="选择结束时间" size="small" clearable :disabled="isDetails"/>
      </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 defaultForm = {
  project_id: '',
  type_id: '',
  title: '',
  uri: '',
  abstract: '',
  remarks: '',
  content: '',
  web_img_uri: '',
  mobile_terminal_img_uri: '',
  enclosure_uri: '',
  video_uri: '',
  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),
      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'
    }
  },
  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)
      }
    }
  },
  methods: {
    beforeUpload(file, target) {
      const type = ['enclosure_uri', 'video_uri'].includes(target) ? 'file' : 'image'
      switch (target) {
        case 'web_img_uri':
        case 'mobile_terminal_img_uri':
          console.log(file)
          break
        case 'enclosure_uri':
          console.log(file)
          break
        case 'video_uri':
          console.log(file)
          break
      }
      this.fetchUpload(file, type, target)
      return false
    },
    handleClose() {
      this.$emit('drawFormClose')
      this.form = Object.assign({}, defaultForm)
    },
    tinymceBlur() {
      this.$refs['el-form-item-tinymce'].$emit('el.form.blur')
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        const form = { ...this.form }
        if (valid) {
          if (form.start_time) {
            form.start_time = this.toUnitTimestamp(form.start_time) || 0
          }
          if (form.hasEndDate === 1) {
            form.end_time = this.toUnitTimestamp(form.end_time) || 0
          } else {
            delete form.end_time
          }
          delete form.hasEndDate
          this.$emit('drawFormSubmit', form)
        } else {
          return false
        }
      })
    },
    toUnitTimestamp(time) {
      return formatToDate(time).getTime() / 1000
    },
    fetchContentTypeList() {
      if (this.form.project_id) {
        getProjectContentTypeList(this.pageType, this.form.project_id).then((res) => {
          if (res.code === 0 && Array.isArray(res.data)) {
            this.typeList = res.data
          }
        })
      }
    },
    fetchUpload(file, type, target) {
      const formData = new window.FormData()
      formData.append('file', file)
      formData.append('type', type)
      fileUpload(formData).then(res => {
        if (res.code === 0 && res.message === 'SUCCESS') {
          this.form[target] = res.data[0].full_path
        }
      })
    }
  }
}
</script>
<style scoped>
.form-container{
  padding-top:15px;
  display:flex;
  align-items: stretch;
}
.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:24px;
  font-size:12px;
  position:relative;
}
.el-form-item.file-upload .des>i{
  position:absolute;
  left:-40px;
  top:14px;
  color: #67c23a;
  font-size:16px;
}
.el-form-item.file-upload:not(.is-required){
  margin-bottom:5px;
}
.el-form-item.mb-15{
  margin-bottom:15px;
}
.avatar-uploader, .file-uploader{
  display:inline-block;
  vertical-align: top;
  width: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;
}
</style>