<template>
  <el-form ref="form" class="article-form" :model="form" :rules="rules" label-width="85px">
    <el-form-item label="风采类型" prop="professionalStyle">
      <el-select v-model="form.styleType" placeholder="请选择风采类型">
        <el-option v-for="item in professionalStyleList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="标题" prop="title">
      <el-input v-model="form.title" maxlength="80" show-word-limit />
    </el-form-item>
    <el-form-item label="副标题" prop="subTitle">
      <el-input v-model="form.subTitle" type="textarea" maxlength="90" show-word-limit />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <!--<content-item v-if="contentItemVisible" ref="contentComp" :html.sync="form.content" />-->
      <avue-ueditor v-model="form.content" v-bind="editorOptions"></avue-ueditor>
    </el-form-item>
    <!--<el-form-item label="附件" prop="attachment">
        <el-upload class="upload-demo" :http-request="uploadImg" :data="{type:'att'}" :file-list="attachmentList" :on-remove="handleRemoveImg" :on-preview="handlePreview" :accept='["image/jpeg", "image/png", "image/tga", "image/gif", "image/bmp"]'>
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>-->

    <el-form-item label="封面" prop="cover">
      <div style="display: flex;">
        <el-upload class="avatar-uploader cover-w16h9" style="margin-right: 30px !important;" :http-request="uploadImg" :data="{type:'img'}" :show-file-list="false" :before-upload="beforeAvatarUpload">
          <el-image fit="contain" v-if="form.cover" :src="form.cover" class="avatar"></el-image>
          <el-icon v-else class="el-icon-plus avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <!--1.建议长×宽比例为16:9，否则默认拉伸<br /> 2.像素最大不超过960*540<br />3.只能上传jpg/png文件，且不超过5MB-->
      </div>
    </el-form-item>
    <el-form-item label="视频" prop="videos">
      <div style="display: flex;">
        <el-upload class="avatar-uploader cover-w16h9" style="margin-right: 30px !important;" :http-request="uploadImg" :data="{type:'video'}" :show-file-list="false" :before-upload="beforeAvatarUpload">
          <video fit="contain" v-if="form.videos" :src="form.videos" class="avatar"></video>
          <el-icon v-else class="el-icon-plus avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </div>
    </el-form-item>
    <el-form-item label="顺序" prop="sort">
      <el-input v-model="form.sort" type="number" show-word-limit />
    </el-form-item>
    <div style="height: 72px;"></div>
    <div style="position: fixed;bottom: 0;padding: 20px 0;z-index: 999;">
      <el-button type="primary" @click="toSave(1)">保存</el-button>
      <!--<el-button type="primary" @click="toSave(0)">存为草稿</el-button>-->
      <!--<el-button type="primary" @click="toPreview">预览</el-button>-->
      <el-button type="info" @click="toCancel">关闭</el-button>
    </div>
  </el-form>
</template>

<script>
  // import contentItem from "@/components/richtext/tinymce.vue"
  import {
    getDetail,
    add,
    update
  } from "@/api/ycwh/professionalStyle";
  import {
    uploadFile
  } from "@/api/oss/oss";
  import { getLazyTree } from "@/api/base/region";
  //
  import { professionalStyleOptions } from "../../common/constants.js";

  export default {
    props: ['id'],
    components: {
      // contentItem
    },
    data() {
      var checkListNull = (rule, value, cb) => {
        if(value && value.length > 0) {
          return cb();
        }
        cb(new Error("请选择标签"));
      };
      return {
        loading: false,
        //
        professionalStyleList: professionalStyleOptions,
        //
        regionList: [],
        //
        attachmentList: [],
        // 提交内容
        form: {
          id: null,
          styleType: '',
          title: '',
          subTitle: '',
          content: '',
          // 标签
          videos: null,
          top: '',
          sort: ''
        },
        //
        contentItemVisible: false,
        rules: {
          styleType: [{
            required: true,
            message: '请选择风采类型',
            trigger: 'blur'
          }],
          title: [{
              required: true,
              message: '请输入标题',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 80,
              message: '长度不能超过80个字',
              trigger: 'blur'
            }
          ],
          subTitle: [{
              required: true,
              message: '请输入副标题',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 90,
              message: '长度不能超过90个字',
              trigger: 'blur'
            }
          ],
          cover: [{
            required: true,
            message: '请上传封面',
            trigger: 'blur',
          }],
          content: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }],
        },
        // 富文本相关配置
        editorOptions: {
          //普通上传地址
          action: "https://api.avuejs.com/imgupload",
          customConfig: {}, //wangEditor编辑的配置
          //是否启用oss(qiniu/ali)
          oss: '',
          headers: {},
          data: {},
          propsHttp: {
            home: '',
            url: 'url',
            res: 'data'
          },
          //七牛云oss配置
          qiniu: {
            AK: "",
            SK: "",
            scope: "",
            url: "",
            deadline: 1
          },
          //阿里云oss配置
          ali: {
            region: "",
            endpoint: "",
            accessKeyId: "",
            accessKeySecret: "",
            bucket: ""
          }
        },
        mapForm: [],
      }
    },
    watch: {},
    created() {
      this.toReloadData()
    },
    mounted() {
      if(this.id && this.id > 0) {
        this.getDetail(this.id)
      }
    },
    watch: {},
    methods: {
      getDetail(id) {
        if(!(id && id > 0)) {
          return;
        }
        /** 获取对应的文章详情 */
        getDetail(id).then(res => {
          if(res.data.success && res.data.data) {
            let data = res.data.data;
            if(data.regionId && data.regionId > 0) {
              data.regionId = data.regionId.toString()
            }
            if(data.content) {
              data.content = decodeURIComponent(data.content)
            }
            //
            this.form = data;
          }
        })
      },
      toReloadData(data) { //
        this.form = data || {}
        this.contentItemVisible = true
      },
      toSave(isPublish) {
        if(this.loading) {
          return;
        }
        this.loading = true;
        this.$refs.form.validate((valid) => {
          if(valid) { //校验通过
            let submitObj = JSON.parse(JSON.stringify(this.form)) //克隆一份数据，避免影响到富文本编辑器
            submitObj.content = encodeURIComponent(submitObj.content)

            /** id不为空则为编辑，为空则新增 */
            let saveFunc = submitObj.id ? update : add
            this.loading = true;
            //  发布或存为草稿
            submitObj.isPublish = isPublish || 0;
            // 处理附件列表
            if(this.attachmentList && this.attachmentList.length > 0) {
              submitObj.attachment = ""
              this.attachmentList.map(e => {
                if(submitObj.attachment) {
                  submitObj.attachment += "," + e.name + "::" + e.url
                } else {
                  submitObj.attachment += e.name + "::" + e.url
                }
              })
            } else {
              submitObj.attachment = ''
            }
            // content
            submitObj.content = submitObj.content || ''

            saveFunc(submitObj).then(() => {
              this.$message({
                type: "success",
                message: "保存成功!"
              })
              this.$emit("toCancel", true)
            }, error => {
              this.loading = false;
              window.console.log(error)
            })
          } else { //校验不通过
            this.$message.error('存在未完善的内容，请完善后再试!');
            this.loading = false;
            return false;
          }
        })
      },
      toView() {
        // 预览
      },
      toCancel() {
        this.$emit("toCancel", false)
      },
      // 图片上传
      uploadImg(params) { // 调用接口上传不使用upload上传
        if(!(params.data && params.data.type)) {
          // att img
          return;
        }
        let uploadType = params.data.type;
        //
        let fd = new FormData();
        let f = params.file;
        fd.append("file", f);
        uploadFile(fd).then(res => {
          if(res && res.data && res.data.success) {
            // 提交内容
            if(uploadType == 'img') {
              this.form.cover = res.data.data.link;
              this.$refs.form.validateField(["cover"], () => {
                // 只触发校验不做其他处理
              })
            } else if(uploadType == 'video') {
              this.form.videos = res.data.data.link;
              this.$refs.form.validateField(["videos"], () => {
                // 只触发校验不做其他处理
              })
            } else if(uploadType == 'att') {
              this.attachmentList.push({
                uid: f.uid,
                name: f.name,
                url: res.data.data.link
              })
            }
            this.$forceUpdate();
          }
          this.loading = false;
        }, e => {
          console.log(e)
          this.loading = false;
        });
      },
      beforeAvatarUpload(file) {
        // 封面限制5m    附件暂时不限制
        //        const isJPG = file.type === 'image/jpeg';
        //        if(!isJPG) {
        //          this.$message.error('上传头像图片只能是 JPG 格式!');
        //        }
        const isLt5M = (file.size / 1024 / 1024) < 5;
        if(!isLt5M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return true;
      },
      handlePreview(file) {
        window.open(file.url);
      },
      handleRemoveImg(file, fileList) {
        this.attachmentList = fileList;
      },
      toPreview() {
        let submitObj = JSON.parse(JSON.stringify(this.form)) //克隆一份数据，避免影响到富文本编辑器
        /** id不为空则为编辑，为空则新增 */
        this.loading = true;
        // 标签预览需要处理

        // content
        submitObj.content = submitObj.content || ''
        // 新选择的标签、专栏需要单独赋值提供显示
        // goPreview(this, "article", submitObj, this.tagOptions)
      }
    },
  }
</script>

<style scoped lang="scss">
  @import "./index.scss"
</style>