<template>
  <div class="div_main">
    <div class="div_btn">

      <el-button type="default"
                 size="mini"
                 @click="diaCancel">取消返回</el-button>
      <el-button v-if="formType!='D'"
                 type="primary"
                 size="mini"
                 @click="saveForm">保存发布</el-button>

    </div>

    <div v-if="isLoaded"
         class="div_content">

      <el-form :inline="true"
               :model="dataForm"
               :rules="dataRule"
               ref="dataForm"
               :disabled="formType=='D'"
               :label-width="'120px'">
        <el-form-item label="标题"
                      prop="title">
          <el-input class="item_width_1"
                    v-model="dataForm.title"
                    placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="分类"
                      prop="categoryCode">
          <el-select class="item_width_1"
                     v-model="dataForm.categoryCode"
                     placeholder="请选择">
            <el-option v-for="item in categoryList"
                       :key="item.categoryCode"
                       :label="item.categoryName"
                       :value="item.categoryCode">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="发布单位"
                      prop="orgId">
          <el-select class="item_width_1"
                     v-model="dataForm.orgId"
                     placeholder="请选择">
            <el-option v-for="(item,index) in orgList"
                       @click.native="orgChange(index)"
                       :key="item.orgId"
                       :label="item.orgName"
                       :value="item.orgId">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div class="div_editor">
        <el-tabs v-model="activeName"
                 @tab-click="tabClick">
          <el-tab-pane style="height:500px"
                       v-for="(item) in moduleArray"
                       :key="item.moduleId"
                       :label="item.moduleName"
                       :name="item.moduleId">
            <!-- 富文本编辑器 -->

            <Tinymce class="tinymce_view"
                     v-if="formType!='D'"
                     v-model="item.moduleContent"
                     :height="450"
                     :customerId="customerId"
                     placeholder="在这里输入文字" />

            <p v-else
               class="text_p"
               v-html="item.moduleContent"></p>
          </el-tab-pane>
        </el-tabs>

      </div>

      <el-form :inline="true"
               :model="externalLink"
               ref="externalLink"
               :disabled="formType=='D'"
               :label-width="'120px'">

        <el-form-item label="外链地址"
                      prop="externalLink">
          <el-input class="item_width_1"
                    v-model="externalLink.externalLink"
                    placeholder="外链地址"></el-input>
        </el-form-item>
        <el-form-item label="地址说明"
                      prop="description">
          <el-input class="item_width_1"
                    v-model="externalLink.description"
                    placeholder="地址说明"></el-input>
        </el-form-item>
        <div>
          <el-form-item class="block"
                        label="附件"
                        prop="attach">
            <el-upload class="upload-demo"
                       :action="uploadUlr"
                       :data="{customerId:customerId}"
                       accept=".doc,.pdf,.xls,.docx,.xlsx"
                       :on-success="handleFileSuccess"
                       :on-remove="handleFileRemove"
                       :on-preview="handleFileDownload"
                       :limit="3"
                       :before-upload="beforeUpload"
                       :file-list="fileList">
              <el-button size="small"
                         type="primary">点击上传</el-button>
              <div slot="tip"
                   class="el-upload__tip">只能上传word、excel、pdf文件</div>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'


import Tinymce from '@c/tinymce2/index.vue'
// import tinymce from 'tinymce/tinymce'
// import Editor from '@tinymce/tinymce-vue'
// import 'tinymce/themes/silver'
// import 'tinymce/icons/default/icons'

let loading// 加载动画
export default {
  data () {
    return {

      defaultValue: '',
      customerId: '',
      formType: '', // 操作类型A/U  D(详情)
      guideId: '', // 父组件传来功能id
      categoryList: [],
      orgList: [],

      dataForm: {
        guideId: '',
        title: '',
        categoryCode: '',
        orgId: '',
        orgType: '',
        orgName: '',
        moduleList: [],
        externalLinks: [],
        attachmentList: []
      },
      externalLink: {
        externalLink: "",
        description: ""
      },

      isLoaded: false,//是否加载结束
      editorOption: {
        placeholder: '编辑文章内容'
      },
      activeName: "",
      moduleArray: [],
      selTabIndex: 0,

      fileList: [
        // {
        //   name: 'food.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // }, {
        //   name: 'food2.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // }
      ],
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/upload-guide-file',

    }
  },
  mounted () {
    this.customerId = localStorage.getItem('customerId')
    // tinymce.init({})
  },

  methods: {
    saveProjectInfo () {

    },

    async initData (guideId, formType) {
      this.startLoading()

      this.formType = formType
      this.guideId = guideId
      this.resetData()
      await this.loadOrg()
      await this.getcategory()
      await this.loadModule()

      if (formType === 'A') {


      } else {
        this.guideId = guideId
        this.dataForm.guideId = guideId
        await this.loadFormData()
      }

      this.endLoading()
      this.isLoaded = true

    },

    async getcategory () {
      const url = '/gov/voice/guidecategory/getcategory'
      // const url = 'http://yapi.elinkservice.cn/mock/102/gov/voice/guidecategory/getcategory'

      const params = {
        queryOrigin: 'saveorupdate'
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.categoryList = data

      } else {
        this.$message.error(msg)
      }
    },

    async loadOrg () {
      const url = '/gov/org/staff/orgList'
      // const url = 'http://yapi.elinkservice.cn/mock/102/gov/org/staff/orgList'

      const params = {}
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.orgList = data
        if (data.length > 0) {
          this.dataForm.orgId = data[0].orgId
          this.dataForm.orgType = data[0].orgType
          this.dataForm.orgName = data[0].orgName
        }

      } else {
        this.$message.error(msg)
      }
    },

    //获取模块tab
    async loadModule () {
      const url = '/gov/voice/guidemodule/list'
      // const url = 'http://yapi.elinkservice.cn/mock/102/gov/voice/guidemodule/list'

      const params = {}
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.moduleArray = data

        this.moduleArray.forEach(element => {
          element.editorOption = {
            placeholder: '输入' + element.moduleName
          }
        });

        if (data.length > 0) {
          this.activeName = data[0].moduleId
        }

      } else {
        this.$message.error(msg)
      }
    },

    //单位下拉框改变
    orgChange (index) {
      console.log(index)
      this.dataForm.orgName = this.orgList[index].orgName
      this.dataForm.orgType = this.orgList[index].orgType
    },

    tabClick (selTab) {
      console.log(selTab.index)
      this.selTabIndex = selTab.index

    },

    onEditorChange ({ editor, html, text }) {

      if (this.isLoaded) {
        this.moduleArray[this.selTabIndex].moduleContent = html
      }

    },

    async loadFormData () {
      this.isLoaded = false
      // const url = 'http://yapi.elinkservice.cn/mock/102/gov/voice/guide/detail'
      const url = '/gov/voice/guide/detail'
      let params = {
        guideId: this.guideId
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.dataForm = data
        // debugger

        if (data.externalLinks && data.externalLinks.length > 0) {
          this.externalLink = data.externalLinks[0]
        }
        if (data.attachmentList) {
          this.fileList = data.attachmentList
        }

        if (data.moduleList && data.moduleList.length > 0) {
          this.moduleArray = data.moduleList
        }

        console.log(this.moduleArray)

      } else {
        this.$message.error(msg)
      }
    },
    dormatHtml(content) {
      let c = ''
      if (content.indexOf('DOCTYPE') != -1) {
        c = content.slice(45, -16);
      }
      console.log('content', typeof content)
      return c || content
    },
    saveForm () {
      this.dataForm.moduleList = []
      this.moduleArray.forEach(element => {
        if (element.moduleContent) {
          element.moduleContent = this.dormatHtml(element.moduleContent)
          this.dataForm.moduleList.push(element)
        }
      });

      if (this.externalLink.externalLink && this.externalLink.description) {
        this.dataForm.externalLinks = []
        this.dataForm.externalLinks.push(this.externalLink)
      } else if (!this.externalLink.externalLink && !this.externalLink.description) {
        this.dataForm.externalLinks = []
      } else {
        this.$message({
          type: 'error',
          message: '链接地址和地址说明必须同时填写'
        })
      }

      if (this.fileList.length > 0) {
        this.dataForm.attachmentList = this.fileList
      }

      if (this.moduleArray.length === 0 && this.dataForm.externalLinks.length === 0 && this.fileList.length === 0) {
        this.$message({
          type: 'error',
          message: '文档内容、外链、附件至少填写一样'
        })
        return false
      }

      console.log(this.dataForm)

      // return false

      this.$refs['dataForm'].validate((valid, messageObj) => {

        if (!valid) {
          app.util.validateRule(messageObj)
        } else {
          let url = ''
          if (this.formType === 'U') {
            url = '/gov/voice/guide/edit'
            // url = 'http://yapi.elinkservice.cn/mock/102/gov/voice/guide/edit'
          } else {
            url = "/gov/voice/guide/add"
            // url = "http://yapi.elinkservice.cn/mock/102/gov/voice/guide/add"
          }

          window.app.ajax.post(url, this.dataForm,
            (data, rspMsg) => {
              this.$message({
                type: 'success',
                message: '保存成功'
              })
              this.$emit('refresh')
              this.$emit('cancleBack')
            },
            (rspMsg, data) => {

              this.$message.error(rspMsg)
            })
        }
      })
    },

    resetData () {
      this.moduleArray = []
      // this.moduleArray.forEach(element => {
      //   if (element.moduleContent) {
      //     element.moduleContent = ''
      //   }
      // });
      this.externalLink = {
        externalLink: "",
        description: ""
      }
      this.fileList = []
      this.dataForm = {
        guideId: '',
        title: '',
        categoryCode: '',
        orgId: '',
        orgType: '',
        orgName: '',
        moduleList: [],
        externalLinks: [],
        attachmentList: []
      }
    },
    // 取消
    diaCancel () {
      this.resetData()
      this.$emit('cancleBack')
    },


    beforeUpload (file) {
      const array = file.name.split('.')
      const extension = array[array.length - 1]

      if (extension !== 'xls'
        && extension !== 'xlsx'
        && extension !== 'doc'
        && extension !== 'docx'
        && extension !== 'pdf') {
        this.$message.error('只能上传word、excel、pdf文件！')
        return false
      }



      // if (!isLt2M) {
      //   this.$message.warning('上传模板大小不能超过 5MB!')
      //   return
      // }

      // return false // 返回false不会自动上传
    },

    handleFileRemove (file) {

      if (file && file.status === "success") {
        this.fileList.splice(this.fileList.findIndex(item => item.uid === file.uid), 1)
      }
    },

    handleFileSuccess (res, file) {

      if (res.code === 0 && res.msg === 'success') {
        const array = file.name.split('.')
        const fileType = array[array.length - 1]

        file.url = res.data.url
        file.type = fileType
        this.fileList.push(file)
        console.log(this.fileList)
      } else this.$message.error(res.msg)
    },

    //下载
    handleFileDownload (file) {

      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.download = file.name;
      console.log(a)
      a.href = file.url;
      a.dispatchEvent(event);


    },

    // 开启加载动画
    startLoading () {

      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }

  },
  components: {
    Tinymce

  },
  computed: {
    dataRule () {
      return {
        categoryCode: [
          { required: true, message: '分类不能为空', trigger: 'blur' }
        ],
        orgId: [
          { required: true, message: '发布单位不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }

        ]
      }
    },

    ...mapGetters(['clientHeight', 'resolution']),
  },
}
</script>

<style lang="css" scoped>
.div_btn {
  z-index: 10;
  position: absolute;
  right: 50px;
  top: 20px;
  /* margin: 0 0 20px 0; */
}

.div_editor {
  margin-left: 60px;
  width: 90%;
}

.div_editor >>> .el-tabs--card > .el-tabs__header .el-tabs__nav {
  border: none;
}
.el-tabs__nav-wrap::after {
  background-color: white;
}
.el-tabs__active-bar {
  background-color: white;
}

.div_content {
  margin-top: 30px;
}

.item_width_1 {
  width: 300px;
}
.item_width_2 {
  width: 500px;
}
.block {
  display: block;
}
.text_p {
  height: 400px;
  overflow: auto;
}
.tinymce_view {
  height: 400px;
  overflow: auto;
}
</style>


