<template>
  <div class="article">
    <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入文章标题" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="文章描述" prop="description">
            <el-input v-model="formData.description"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入内容"
                      clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="是否新闻" prop="isTop">
            <el-radio-group v-model="formData.isTop">
              <el-radio-button v-for="(item, index) in isTopOptions" :key="index"
                               :label="item.dictValue">{{ item.dictLabel }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="是否显示" prop="isView">-->
<!--            <el-radio-group v-model="formData.isView">-->
<!--              <el-radio-button v-for="(item, index) in isViewOptions" :key="index"-->
<!--                               :label="item.dictValue">{{ item.dictLabel }}-->
<!--              </el-radio-button>-->
<!--            </el-radio-group>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="8">
          <el-form-item label="是否英语" prop="isEnglish">
            <el-radio-group v-model="formData.isEnglish">
              <el-radio-button v-for="(item, index) in isEnglishOptions" :key="index"
                               :label="item.dictValue">{{ item.dictLabel }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-row v-show="sistArticleTypeOption.length>0 && approveShow.sist">
            <el-col :span="12">
              <el-form-item label="信息网站">
                <el-select v-model="params.sistArticleType" @change="getSistApprove(params.sistArticleType)"
                           placeholder="请选择文章类型" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="dict in sistArticleTypeOption"
                    :key="dict.id"
                    :label="dict.title"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批人">
                <el-select v-model="params.sistApprove" placeholder="请选择文章类型" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="dict in sistApproveOption"
                    :key="dict.userId"
                    :label="dict.userName"
                    :value="dict.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="labArticleTypeOption.length>0 && approveShow.lab">
            <el-col :span="12">
              <el-form-item label="实验室网站">
                <el-select v-model="params.labArticleType" placeholder="请选择文章类型"
                           @change="getLabApprove(params.labArticleType)" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="dict in labArticleTypeOption"
                    :key="dict.id"
                    :label="dict.title"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批人">
                <el-select v-model="params.labApprove" placeholder="请选择文章类型" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="dict in labApproveOption"
                    :key="dict.userId"
                    :label="dict.userName"
                    :value="dict.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12" v-show="imgurlShow">
          <el-form-item >
            <UploadFile v-model="formData.imgurl"
                        file-type="image"
                        :v-public="true"
                        :v-data="false"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :offset="1" :span="22">

          <el-upload
            class="upload-demo"
            ref="upload"
            :action="uploadFileUrl"
            :headers="headers"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
            :auto-upload="true"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          </el-upload>

        </el-col>
      </el-row>
      <el-row>
        <el-col :offset="1" :span="22">
          <TinymceEditor v-model="formData.content"></TinymceEditor>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="submitForm">
          <el-form-item size="large">
            <el-button type="success" @click="saveDrafts">保存草稿</el-button>
            <el-button type="primary" @click="submitForm">提交审核</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
// import ArticleFile from './ArticleFile'
// import Editor from '@/views/utils/Editor'
import TinymceEditor from '@/views/utils/tinymce/Tinymce'
import {updateArticle, getArticle, drafts, getArticleType, getArticleApprove} from "@/api/sist/article";
import {Message} from "element-ui";
import UploadFile from '@/views/utils/uploadFile.vue';
import { getArticleNav } from '../../../../api/sist/article'
import { getToken } from '../../../../utils/auth'
import { addFile, delFile } from '../../../../api/sist/file'


export default {
  components: {
    TinymceEditor,
    UploadFile,
    // ArticleFile
  },
  props: [],
  data() {
    return {
      isAdmin:false,
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList:[],
      fileMapper:[],
      submit: 1,
      imgurlShow:false,
      formData: {
        id: null,
        title: null,
        isTop: '2',
        isEnglish: '0',
        content: "",
        imgurl:null,
      },
      approveShow: {
        sist: true,
        lab: true,
      },
      params: {
        sistArticleType: null,
        sistApprove: null,
        labArticleType: null,
        labApprove: null,
      },
      sistArticleTypeOption: [],
      labArticleTypeOption: [],
      sistApproveOption: [],
      labApproveOption: [],
      articleTypeOptions: [],
      isTopOptions: [],
      isViewOptions: [],
      isEnglishOptions: [],
      sitetypeOptions: [],
      rules: {
        title: [{
          required: true,
          message: '请输入文章标题',
          trigger: 'blur'
        }],
        isTop: [{
          required: true,
          message: '请选择是否顶置',
          trigger: 'change'
        }],
        isEnglish: [{
          required: true,
          message: '请选择是否英语',
          trigger: 'change'
        }],
        isView: [{
          required: true,
          message: '请选择是否显示',
          trigger: 'change'
        }],
        imgurl: [{
          required: true,
          message: '请选择是否显示',
          trigger: 'change'
        }],
        sitetype: [{
          required: true,
          message: '单选框组不能为空',
          trigger: 'change'
        }],
        publishTime: [{
          required: true,
          message: '请选择发布日期',
          trigger: 'change'
        }],
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.approveShow = {
      sist: true,
      lab: true
    }
    this.formData.id = this.$route.params && this.$route.params.articleId;
    if (this.formData.id === undefined) {
      this.formData.id = null;
    } else {
      getArticle(this.formData.id).then(response => {
        this.formData = response.data
        if (this.formData.siteType === '2') {
          this.approveShow.sist = false
          if (null != this.formData.navId){
            this.params.labArticleType = parseInt(this.formData.navId)
            this.getLabApprove(this.params.labArticleType)
          }
        } else if (this.formData.siteType === '1') {
          this.approveShow.lab = false
          if (null != this.formData.navId){
            this.params.sistArticleType = parseInt(this.formData.navId)
            this.getSistApprove(this.params.sistArticleType)
          }
        }
      })
    }
    this.getDicts("article_site_type").then(response => {
      this.sitetypeOptions = response.data;
    });
    this.getDicts("is_top").then(response => {
      this.isTopOptions = response.data;
    });
    this.getDicts("is_view").then(response => {
      this.isViewOptions = response.data;
    });
    this.getDicts("is_english").then(response => {
      this.isEnglishOptions = response.data;
    });
    this.getDicts("article_status").then(response => {
      this.statusOptions = response.data;
    });
    getArticleNav().then(res=>{
      let data = res.data
      this.articleTypeOptions = data
      for (let item of data) {
        if (item.sitetype == 1){
          this.sistArticleTypeOption.push(item)
        }else {
          this.labArticleTypeOption.push(item)
        }
      }
    })
  },
  mounted() {
  },
  methods: {
    handleRemove(file, fileList) {
      let fileId = null
      let index = 0
      for (let item of this.fileMapper) {
        console.log(file.uid, item)
        if (file.uid == item.uid) {
          fileId = item.id
          break
        }
        index++
      }
      console.log(index)
      let that = this
      delFile(fileId).then(res => {
        that.fileMapper.splice(index, 1)
        console.log(that.fileMapper)
        that.$message.success('提交成功!')
      })
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      let data = {
        isPublic: '1',
        fileType: '',
        fileName:res.fileName,
        fileAddr: res.fileAddr
      }
      addFile(data).then(res => {
        console.log(res)
        let dataFile = res.data
        let mapperItem = {
          id: dataFile.fileId,
          uid: file.uid,
          url:dataFile.url,
          fileName:data.fileName,
        }
        let url =  dataFile.uri
        url = url.replace("/pubfiles","/attached")
        let fileStr = '<p><a target="_blank" href="'+url+'">'+mapperItem.fileName+'</a><br/></p>'
        this.formData.content = this.formData.content + fileStr
        this.fileMapper.push(mapperItem)
      })
      this.$message.success('提交成功!')
    },

    getSistApprove(navId) {
      this.judgeThumbnail(navId)
      getArticleApprove(navId).then(res => {
        this.sistApproveOption = res.data
      })
    },
    getLabApprove(navId) {
      this.judgeThumbnail(navId)
      getArticleApprove(navId).then(res => {
        this.labApproveOption = res.data
      })
    },
    judgeThumbnail(navId){
      let articleList = this.articleTypeOptions
      for (let article of articleList) {
        console.log(article.title)
        if (navId === article.id && article.isThumbnail == 1){
          this.imgurlShow = true
          return
        }
      }
    },
    submitForm() {
      let that_ = this
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if ((that_.params.sistArticleType === null || that_.params.sistArticleType === "") && (that_.params.labArticleType === null || that_.params.labArticleType === "")) {
            Message({
              message: "请至少选择一个网站发布文章",
              type: "error",
            })
            return
          } else if ((that_.params.sistArticleType === null || that_.params.sistArticleType === "") && (that_.params.labArticleType !== null || that_.params.labArticleType !== "") && (that_.formData.sistApprove === null || that_.params.sistApprove === "")) {
            Message({
              message: "请选择信息网站的审批人",
              type: "error",
            })
            return
          } else if ((that_.params.sistArticleType === null || that_.params.sistArticleType === "") && (that_.params.labArticleType != null || that_.params.labArticleType !== "") && (that_.params.labApprove === null || that_.params.labApprove === "")) {
            Message({
              message: "请选择实验室网站的审批人",
              type: "error",
            })
            return
          }
        }
        that_.formData.params = that_.params
        if (that_.submit == 0) {
          Message({
            message: "您操作过快",
            type: "error",
          })
        } else {
          that_.submit = 0
          that_.loading = true;
          // this.formData.imgurl = this.form.imgurl.url
          updateArticle(that_.formData).then(response => {
            that_.loading = false;
            if (response.code == 200) {
              that_.msgSuccess("提交审批成功");
              that_.submit = 1
              that_.close();
            }
          }).catch(e => {
            that_.submit = 1
          });
        }
        // TODO 提交表单
      })
    },
    close() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({path: "/SIST/article/", query: {t: Date.now()}})
    },
    saveDrafts() {
      let that = this
      this.$refs['elForm'].validate(valid => {
        drafts(that.formData).then(res => {
          if (that.formData.id == null || this.formData.id == "") {
            that.formData.id = res.data
          }
          if (res.code == 200) {
            that.msgSuccess('保存成功');
          } else {
            that.Message({
              message: res.code,
              type: "error"
            })
          }
        })
      })
    },
  }
}

</script>
<style>
.el-select-dropdown, .el-message {
  z-index: 2147483647 !important;
}
</style>
<style scoped lang="scss">
.article {
  margin-top: 20px;
}

.submitForm {
  margin-top: 20px;
  text-align: center;
}
</style>
