<template>
  <div class=" editor">
    <p class=" text-2xl font-bold mb-5">新增资讯</p>
    <a-form-model ref="ruleForm" :model="form" :rules="rules">
      <div class=" flex content-between justify-between">
        <!-- 标题 -->
        <a-form-model-item class="inline-block w-80 flex-1 mx-3" label="" prop="title">
          <a-input v-model="form.title" placeholder="请输入标题"/>
        </a-form-model-item>
        <!-- 作者 -->
        <a-form-model-item class="inline-block w-80 flex-1 mx-3" label="" prop="author">
          <a-input v-model="form.author" placeholder="请输入作者名称"/>
        </a-form-model-item>
        <!-- 文章分类 -->
        <a-form-model-item class="inline-block w-80 flex-1 mx-3" label="" prop="type">
          <a-select v-model="form.type" placeholder="请选择资讯分类"> 
            <a-select-option v-for="item in articalType" :key="item.value">{{item.label}}</a-select-option>
          </a-select>
        </a-form-model-item>
      </div>
      <!-- 上传概要图片 -->
      <a-form-model-item label="" prop="imgUrl">
        <editor-upload class=" mt-5" :path="form.imageUrl" @getFileHash="getImage" />
      </a-form-model-item>
      <!-- 文章概要 -->
      <a-form-model-item label="" prop="summary">
        <a-textarea v-model="form.summary" :maxLength="50" placeholder="请输入文章概要，字数限制50字以内" auto-size />
      </a-form-model-item>
      <!-- 编辑器 -->
      <a-form-model-item label="" prop="content">
        <editor class="edit-news text-left mt-5" :text="form.editableContent" :editorContent.sync="form.content"
              @getContent="getContent"/>
      </a-form-model-item>
      <!--新增操作 -->
      <a-button type="primary" @click="onSubmit" class=" mt-5">确定</a-button>
    </a-form-model>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import Editor from '@/components/Editor/index.vue'
import EditorUpload from '@/components/Editor/editorUpload.vue'
import News from '@/service/News/index'
import FileService from "@/service/FileService/index";
import { message } from 'ant-design-vue';

const news = new News()

export default Vue.extend({
  components:{ Editor,EditorUpload },
  props:{
    articalType:{
      type:Array,
      default(){
        return [{
          label: '政策',
          value: 1
        }, {
          label: '新闻',
          value: 2
        }]
      }
    }
  },
  computed:{
    disabled(){
      let result = true
      const {title,author,summary,type,content,imgUrl} = this.form
      if(title&&author&&summary&&type&&content&&imgUrl){
        result = false
      }
      return result
    }
  },
  data(){
    const checkImg = (rule: any, value: string, callback: any) => {
      if (!(this as any).form.imgUrl) {
        return callback(new Error('请选择图片'));
      }
      callback()
    }
    const checkContent = (rule: any, value: string, callback: any) => {
      if (!value || !value.replace(/(<p>|<\/p>)+/g,'')) {
        return callback(new Error('请输入内容'));
      }
      callback()
    }
    const rules = {
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
      summary: [{ required: true, message: '请输入概要', trigger: 'blur' }],
      type: [{ required: true, message: '请选择类型', trigger: 'change' }],
      content: [{ required: true, message: '请输入内容', trigger: ['blur', 'change'], validator: checkContent }],
      imgUrl: [{ required: true, trigger: ['change', 'blur'], validator: checkImg }]
    }
    return{
      rules,
      form: {
        title: '',
        author: '',
        imgUrl: '',
        imageUrl: '',
        summary: '',
        content: '',
        editableContent: '',
        type: undefined as number|any
      },
      disable: false
    }
  },
  created() {
    if (this.$route.query.msg) {
      this.disable = true
    }
    this.getDetails()
  },
  methods:{
    getDetails() {
      // 新增
      if (Object.keys(this.$route.query).length === 0) {
        this.form.type = undefined
        return
      }
      const type = this.$route.query.type
      this.form.type = +type
      const msg = JSON.parse(this.$route.query.msg as string)
      this.initData(msg)
    },
    initData(res: any) {
      this.form.title = res.title
      this.form.author = res.writer
      this.form.imgUrl = res.file_name
      this.form.imageUrl = res.file_name ? new FileService().getImageSrc(res.file_name) : ''
      this.form.summary = res.desc
      this.form.editableContent = res.content
      this.form.content = res.content.replace(/(<p>|<\/p>)+/g,'')
      console.log('res', res)
      console.log('imageUrl', this.form.imageUrl)
    },
    getContent(value:string){
      this.form.content = value
    },
    getImage(val: string) {
      this.form.imgUrl = val
      ;(this.$refs.ruleForm as any).validateField('imgUrl')
    },
    addForm() {
      const params = {
        article_type: this.form.type,
        content: this.form.content,
        desc: this.form.summary,
        file_name: this.form.imgUrl,
        title: this.form.title,
        writer: this.form.author
      };
      (this.$refs.ruleForm as any).validate((valid: any) => {
        if (valid) {
          news.addArticle(params).then(res => {
            if (res.code === 200) {
              message.success('新增成功')
              this.$router.push({ name: 'newsManage' })
            }
          })
        } else {
          return false;
        }
      })
    },
    editForm() {
      const msg = JSON.parse(this.$route.query.msg as string)
      // this.form.content = this.form.content.replace(/(<p>|<\/p>)+/g,'')
      const params = {
        article_type: this.form.type,
        content: this.form.content,
        desc: this.form.summary,
        file_name: this.form.imgUrl,
        title: this.form.title,
        writer: this.form.author,
        uuid: msg.uuid as string
      };
      (this.$refs.ruleForm as any).validate((valid: any) => {
        if (valid) {
          news.editArticle(params).then(res => {
            if (res.code === 200) {
              message.success('编辑成功')
              this.$router.push({ name: 'newsManage' })
            }
          })
        } else {
          return false;
        }
      })
    },
    onSubmit() {
      console.log(this.form.content)
      if (this.$route.query.msg) {
        this.editForm()
      } else {
        this.addForm()
      }
    },
  },
  watch: {
    'form.content': function () {
      ;(this.$refs.ruleForm as any).validateField('content')
    }
  }
})
</script>