<template>
  <div class="newContent">
    <div>
      <Form ref="contentForm" :model="newContentForm" :rules="newContentRule" :label-width="120">
        <Form-item label="牛只分类" prop="contypeId">
          <Select v-model="newContentForm.contypeId" :label-in-value="true" placeholder="请选择所属分类" style="width:480px">
            <Option v-for="type in typeDataList" :key="type.id" :value="type.code" :label="type.name">{{type.name}}</Option>
          </Select>
        </Form-item>
        <Form-item label="新闻类型" prop="newsType">
          
          <Select v-model="newContentForm.newsType" placeholder="请选择新闻类型" style="width:480px">
            <Option value="新闻类型">新闻类型</Option>
            <Option value="平台动态">平台动态</Option>
            <Option value="运营资讯">运营资讯</Option>
            <Option value="媒体报道">媒体报道</Option>
          </Select>
        </Form-item>
        <Form-item label="发布时间" prop="releaseTime">
          <Date-picker type="date" placeholder="选择日期"
          format="yyyy-MM-dd"
          :options="options"
          v-model="newContentForm.releaseTime"/>
        </Form-item>
        <Form-item label="内容名称" prop="name">
          <Input v-model="newContentForm.name" placeholder="请输入内容名称" style="width: 480px"></Input>
          <!-- <span v-if="item.type==3||item.newsType==4">9个字符以内</span>
          <span v-else>6个字符以内</span> -->
        </Form-item>
        <Form-item label="链接地址" prop="url">
          <Input v-model="newContentForm.url" placeholder="请输入链接地址" style="width: 480px"></Input>
        </Form-item>
        <Form-item label="首页展示" prop="isShow">
          <RadioGroup v-model="newContentForm.isShow" type="button">
            <Radio label="1">是</Radio>
            <Radio label="0">否</Radio>
          </RadioGroup>
        </Form-item>
        <Form-item label="顺序号" prop="showOrder">
          <Input v-model="newContentForm.showOrder" placeholder="请输入顺序号" style="width: 200px"></Input>
        </Form-item>
       
        <Form-item label="上传图片" prop="filePath">
          <Upload
            ref="upload"
            type="drag"
            :action="uploadUrl"
            :headers="{'X-AIYANGNIU-SIGNATURE':token}"
            :show-upload-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            class="upload_outer_img">
            <div v-if="!newContentForm.filePath" class="upload_border">
              <p><Icon type="md-cloud-upload" size="35" color="#2db7f5" /></p>
              <p>点击上传图片</p>
            </div>
            <div v-else> <img :src="newContentForm.filePath" width="100%" alt=""></div>
          </Upload>
          <div v-show="newContentForm.filePath" style="color:#2db7f5; cursor: pointer;" @click="gotoCheckImg(newContentForm.filePath)">
            <i class="iconfont icon-htmal5icon09"></i> 查看大图
          </div>
          <div style="color:#aaa;font-size:12px;">图片格式为 jpg、jpeg、png</div>
        </Form-item>
        <Form-item label="简介" prop="intro">
            <Input v-model="newContentForm.intro" placeholder="请输入内容简介" type="textarea" :autosize="{minRows: 2,maxRows: 5}" style="width: 480px"></Input>
        </Form-item>
        <Form-item label="内容详情" prop="content">
          <BasicEditor ref="editotTool"></BasicEditor>
        </Form-item>
      </Form>
    </div>
    <div style="text-align:center;margin-bottom:3em;">
      <Button @click="$router.back()" style="margin-right:5em;">取消返回</Button>
      <Button type="primary" @click="conformSub">确定提交</Button>
    </div>
  </div>
</template>

<script>
import { defineComponent,ref,reactive,onMounted,getCurrentInstance } from 'vue'
import {compressFileM} from '@/utils/system/uploadCompress.js'
import {content} from '@/request/api'
import api from '@/request/apiConfig' //真实接口配置
import {ElNotification} from 'element-plus'
import BasicEditor from '@/components/wangEditor/BasicEditor.vue'
import { ElMessage } from 'element-plus'
import router from '@/router'
export default defineComponent({
  components:{
    BasicEditor
  },
  setup() {
    const token = localStorage.aynUserToken
    let {proxy} = getCurrentInstance();
    let newContentForm = reactive({contypeId: '',newsType: '',isShow: '1',showOrder: '',name:'',url:'',releaseTime:'',filePath: '',intro:'',content:''})
    const options= {
      disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000;
      }
    }
    // 表单验证项
    let newContentRule = ref({
      contypeId: [{ required: true, message: '请选择所属类别', trigger: 'change' }],
      newsType: [{ required: true, message: '请选择新闻类型', trigger: 'change' }],
      releaseTime: [{ required: true, type:'date', message: '请选择发布时间', trigger: 'change' }],
      name: [{ required: true, message: '请填写内容名称', trigger: 'blur' }],
      isShow: [{ required: true, message: '请选择展示状态', trigger: 'change' }],
    })
    const uploadUrl = api.apiManager + '/manager/images/upload'

    // 获取分类的列表
    let typeDataList = ref([])
    async function getTypeDataList(){
      await content.GetContentTypeList({limit:10000,offset:0}).then((res) => {
        if (res.code =='101') {
          typeDataList.value = res.data || []
        }
      })
    }
    
    function beforeUpload(file){
      // 进行2.5倍系数压缩
      return (compressFileM(file,2.5))
    }

    function handleFormatError (file) {
      ElNotification.warning({
        title: '温馨提示',
        message: '文件格式不正确',
        showClose: false,
      })
    }

    function handleSuccess(res, file, fileList){
      if(res.code == '101'){
        newContentForm.filePath = res.data
      }
    }

    // 打开新页面查看照片
    function gotoCheckImg(pic){
      window.open(pic,'blank')
    }

    // 编辑获取详情内容
    async function getContentDetail(){
      await content.GetContentDetail({id: router.currentRoute.value.query.id}).then(res => {
        if(res.code == '101' && res.data) {
          let _data = res.data
          newContentForm = Object.assign(newContentForm, {
            contypeId: _data.contypeId,
            newsType: _data.newsType,
            isShow: _data.isShow,
            name: _data.name,
            url: _data.url,
            showOrder: _data.showOrder,
            intro: _data.intro,
            content: _data.content,
            filePath: _data.filePath,
            id:_data.id,
            releaseTime: new Date(_data.releaseTime),
          })
          proxy.$refs.editotTool.valueHtml = _data.content
        }
      })
    }

    // 确定提交表单
    function conformSub(){
      newContentForm.content = proxy.$refs.editotTool.valueHtml  //富文本传值
      let reqFn = null
      if(newContentForm.id){
        reqFn = content.UpdateContent
      }else{
        reqFn = content.AddNewContent
      }
      proxy.$refs['contentForm'].validate(async (valid) => {
        if (valid) {
          await reqFn(newContentForm).then(res=>{
            if(res.code == 101){
              ElMessage({
                message: res.message || '添加成功!',
                type: 'success',
              })
              router.back()
            }else{
              ElMessage({
                message: res.message || '添加失败!',
                type: 'warning',
              })
            }
          }).catch(e=>{
            ElMessage({
              message: e.message || '添加失败!',
              type: 'error',
            })
          })
        } else {
          ElMessage({
            message:'请填写完表单数据!',
            type: 'warning',
          })
        }
      })
    }

    onMounted(async()=>{
      getTypeDataList()
      // 编辑获取详情
      if(router.currentRoute.value.path === '/contentManage/editContent'){
        getContentDetail()
      }
    })

    return {
      uploadUrl,token,options,
      newContentForm,typeDataList,newContentRule,
      handleFormatError,handleSuccess,beforeUpload,gotoCheckImg,conformSub
    }
  },

})
</script>

<style lang="scss" scoped>
.newContent{
  padding: 1em;
  .upload_outer_img{
    max-width: 45%;
    img{
      width: 100%; padding: 0;
    }
    .upload_border{
      width: 100%; padding: 3em;
    }
  }
  
}
</style>
<style lang="scss">
.newContent{
  .ivu-upload-drag{
    border: 0px;
  }
}
</style>