<template>
<div>
     <el-row class="article-add">
        <el-form ref="form" :rules="rules" :model="addForm" label-position="right" label-width="80px">
          <el-form-item prop="title" label="标题">
            <el-input class="title-input" v-model.trim="addForm.title" placeholder="请输入文章标题,长度在 1 到 50 个字符" show-word-limit  maxlength="50"></el-input>
          </el-form-item>
          <el-form-item class="imgInstructions" label="封面">
            <div class="el-form-item__content">
               <imageUpload :value="converImage" width="410px" height="168px" @success="handleUploadSuccess" @remove="handleRemoveSuccess"></imageUpload>
              <!-- <dl>
              <dt>上传封面说明</dt>
              <dd>上传为4:3(如:400*300)的png或jpg图片</dd>
              <dd>允许上传图片大小为：5MB</dd>
            </dl> -->
            </div>

          </el-form-item>
          <el-form-item prop="keyword" label="关键字"><el-input show-word-limit maxlength="50" placeholder="请输入关键字,长度在 0 到 50 个字符" v-model.trim="addForm.keyword"></el-input></el-form-item>
          <el-form-item prop="summary" label="摘要">
            <el-input show-word-limit maxlength="200" placeholder="请输入摘要,仅限200字以内(未填写摘要信息时，自动从内容中提取!)" v-model.trim="addForm.summary" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }"></el-input>
          </el-form-item>
          <el-form-item prop="content" label="正文">
            <WxEditor v-model.trim="addForm.content" placeholder="请输入内容,长度至少在100个字符" :minHeight="250">
              </WxEditor></el-form-item>
          <el-form-item class="footer-btn ">
            <div class="btnbox">
              <div class="check-right">
            <el-checkbox style="margin-left:00px" v-model="checked"></el-checkbox><span style="font-size:14px;color:#787878;margin-left: 10px;">我已阅读并遵守<span style="color:#588afc;margin-right:10px;cursor: pointer;" @click="addFormCheckedShow = true">平台内容发布要求</span> </span>
            </div>
           <div class="button-left">
            <el-button type="primary" plain :loading="craftLoading" @click="submit(1)" style="margin-right: 40px;">保存草稿</el-button>
            <el-button :loading="loading" @click="submit(2)" :disabled="!checked" type="primary">提交</el-button>
          </div>
            </div>
            
          </el-form-item>
        </el-form>
      </el-row>
      <el-dialog class="checked-show" :visible.sync="addFormCheckedShow" width="800px" :show-close="false" top="14vh" :modal="false">
        <agreement></agreement>
        <span slot="footer" class="dialog-footer">
          <el-button style="margin-right:10px" type="primary" @click="addFormCheckedShow = false">确 定</el-button>
        </span>
      </el-dialog>
</div>

</template>

<script>
import agreement from '@/components/Portal/agreement.vue'
import { mapGetters } from 'vuex';
import WxEditor from '@/components/Editor/index.vue';
import imageUpload from '@/components/ImageUpload/artimgUpload.vue';
import apiArticle from '@/api/modules/article.js';
export default {
  name: 'atticleAdd',
  components: { WxEditor, imageUpload,agreement },
  computed: {
    ...mapGetters(['userInfo'])
  },
  props:{
      editForm:{
          type:Object,
          required:true,
      },
      jumpLimit:{
        type:Boolean,
        default:()=>{
          return true
        }
      }
  },
  data() {
    return {
      addFormCheckedShow:false,
      fileBaseUrl:process.env.VUE_APP_FILE_BASE_URL,
      checked:false,
      addForm: {
      },
      loading:false,
      converImage: '',
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }, { min: 1, max: 100, message: '请输入长度为 1 到 100 的字符', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        // checked: [{message: '请选择协议', trigger: 'blur' }]
      },
      showForm:false,
      craftLoading:false,
    };
  },
  created() {
    if(this.editForm.id){
      let id=this.editForm.id;
      apiArticle.detail(id,false).then(res => {
        if (res.status == 200) {
          this.addForm = res.result;
          // this.addForm.content = res.result.content.trim();
          // console.log(this.addForm.content)
          if(this.addForm.coverurl){
            this.converImage = this.fileBaseUrl + this.addForm.coverurl;
          }
        }
      });
    }
  },
  methods: {
    // handleAvatarSuccess(res, file) {
    //   this.addForm.imageUrl = URL.createObjectURL(file.raw);
    // },
    handleUploadSuccess(file) {
      this.addForm.coverurl = file.result.filePath;
      this.converImage = this.fileBaseUrl + file.result.filePath;
    },
    handleRemoveSuccess(file) {
      this.addForm.coverurl = '';
      this.converImage = '';
    },
    draft() {
      if(this.craftLoading){
        return
      }
      this.craftLoading=true
      this.addForm.status = 1;
        apiArticle
          .save(this.addForm)
          .then(res => {
            if (res.status == 200) {
              this.addForm = res.result;
              this.$message.success('保存成功');
            } else {
              this.$message.error('保存失败');
            }
            this.craftLoading=false
          })
          .catch(err => {
            this.$message.error('保存失败');
            this.craftLoading=false
          });

    },
    save(){
      if(this.loading){
        return;
      }
      this.loading=true;
      this.addForm.status = 2;
      // let content= this.addForm.content.replace(/<.*?>/ig,"");
      // let content= this.addForm.content.replace(/[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!，。？！<>…—&$=()-+/*{}[\]]|\r\n\s/g,"");
      if(this.addForm.content.trim() == ''){
         this.$message.warning('您输入的内容为空，无法发布')
          // type: 'warning'
          this.loading=false
          return 
      }
      this.addForm.content=this.addForm.content.trim()
        apiArticle.save(this.addForm).then(res => {
            if (res.status == 200) {
              if(res.message=='服务处理成功'){
                this.$message(
                {
                  type:'success',
                  message:"发布文章成功"
                });
                let event = {
                key: "PublishArticle",//后台的事件key  发布文章且审核通过
                title: "发表文章",//事件的标题
                parameters:"",//用户自定义参数 name:value,name:value
                content: "发表了文章",//事件的内容
                objId: res.result.id,//关联的id
                objType: "2",//关联的类型
                objInfo: this.addForm.title,
                aid: this.userInfo.aid, //当前登录人的id
                aname: this.userInfo.name,//当前人的姓名
                status: 1 //状态，直接写1
              }
              this.$store.dispatch("userTrigger", event);
              }
              if(res.message.indexOf('审核')!=-1){
                this.$message(
                {
                  type:'warning',
                  message:"发布文章失败，因包含敏感词,请等待人工审核"
                });
              }
              
              this.$emit("success",{result:res.result,status: this.addForm.status});
              if(!this.jumpLimit){
                return
              }
              setTimeout(()=>{
                    let routeData = this.$router.resolve({ path: '/article/detail?id='+res.result.id}); // , query: {  id: 1 }
                    window.open(this.webBaseUrl+routeData.href, '_blank');
                // location.href = this.webBaseUrl + 'detail?id=' + res.result.id;
              },1000)
              // location.href = this.webBaseUrl + 'detail?id=' + res.result.id;
            } else {
              this.$message.error(res.message);
              this.loading=false;
            }
          })
          .catch(err => {
            this.$message.error('发布失败');
            this.loading=false;
          });

    },
    submit(type) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (type == 2) {
            if(this.addForm.content.length<100){
              return this.$message.warning("文章内容请输入不小于100的字符")
            }
            this.save();
          } else {
            this.draft();
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.btnbox{
  display: flex;
  width: 100%;
  .check-right{
    flex: 1;
  }
  .button-left{
    margin-left: auto;
  }
}
::v-deep .el-form-item__label{
  font-size: 18px !important;
  color: #333 !important;
  font-weight: 600 !important;
}
::v-deep .checked-show{
  .el-dialog__header{
    padding:0;
  }
  .el-dialog__body {
    padding: 30px 20px;
    // overflow-y: auto;
}
  .el-dialog__footer{
    border-top: 1px solid #fff;
    background-color: #fff;
    padding: 10px 20px 20px;
  }
}

.nav {
  margin-bottom: 10px;
}
.article-add {
  background: #fff;
  padding: 20px 0;
  padding-right: 20px;

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload--picture-card {
    width: 200px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
    margin-top: 50px;
    display: block;
  }
  .icon-text {
    font-size: 14px;
    display: block;
    height: 30px;
    line-height: 35px;
  }
  .avatar {
    width: 250px;
    height: 178px;
    display: block;
  }
  .imgInstructions {
    .el-form-item__content {
      display: flex;
      justify-content: flex-start;
      dl {
        margin: 0;
        padding: 10px;
        margin-left: 20px;
        line-height: 1.5;
        dt {
          font-size: 18px;
          font-weight: 600;
        }
        dd {
          margin: 0;
        }
      }
    }
  }
}
</style>
