<!--
 * @Author: wj 1454560336@qq.com
 * @Date: 2023-12-26 10:38:09
 * @LastEditors: wj 1454560336@qq.com
 * @LastEditTime: 2023-12-27 15:26:58
 * @FilePath: \admin-manage\src\views\studyManage\communityManage\addArticle.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
-->
<template>
<div class="addArticle app-container">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      v-loading="loading"
      label-width="130px"
    >
      <el-form-item label="标题：" prop="communityTitle">
        <el-input
          v-model="setQuery.communityTitle"
          class="item-width-300"
        ></el-input>
      </el-form-item>
      <el-form-item label="封面：" prop="coverImg">
        <Upload
          type="coverImg"
          id="coverImg"
          width="400px"
          height="300px"
          uploadType="SHOP_INFO"
          :imgUrl="setQuery.coverImg"
          @uploadEnd="uploadEnd"
        ></Upload>
      </el-form-item>
      <el-form-item label="分类：" prop="communityId">
 
        <el-select
          v-model="setQuery.communityId"
          clearable
          class="item-width-300"
          placeholder="请选择分类"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容：" prop="communityDetail">
       <div style="border: 1px solid #ccc;width:500px">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="setQuery.communityDetail"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
            />
        </div>
      </el-form-item>
    </el-form>

    <div class="btn-group">
       <el-button>取 消</el-button>
     <el-button type="primary" :loading="loading"  @click="save">确 定</el-button>
    </div>

</div>
    
</template>

<script>
import Upload from '@/components/Upload'
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { requestUploadImg, finishUploadImg } from '@/api/common';
import {addOrUpdateCommunity,detailCommunity,getAllColumnId} from '@/api/study';
import OSS from "ali-oss";

export default Vue.extend({
    components: { Editor, Toolbar,Upload },
    data() {
        return {
            editor: null,
            toolbarConfig: { },
            editorConfig: { 
                placeholder: '请输入内容...',
                MENU_CONF:{
                    uploadImage : {
                        // 自定义上传
                        customUpload(file, insertFn) { 
                            // file 即选中的文件
                                requestUploadImg({
                                "fineName": file.name,
                                "operate": 'OTHER'
                            }).then(res=>{
                                if(res.state == 'Success'){
                                    const client = new OSS({
                                    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                                    region: res.content.endPoint.split('.')[0],
                                    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
                                    accessKeyId: res.content.token.accessKeyId,
                                    accessKeySecret: res.content.token.accessKeySecret,
                                    // 填写Bucket名称。
                                    bucket: res.content.bucket,
                                    stsToken:res.content.token.securityToken
                                    });

                                    client
                                    .multipartUpload(res.content.paths[0].join('/'), file)
                                    .then((r) => {
                                        // 上传完成
                                        finishUploadImg([{path:res.content.paths[0]}]).then(msg=>{
                                        if(msg.state == 'Success'){
                                            let url = 'http://' + res.content.bucket + '.'+ res.content.endPoint + '/' + res.content.paths[0].join('/')
                                                insertFn(url, '', '')
                                        }
                                        })
                                    
                                    })
                                    .catch((err) => {
                                        console.log(err); //上传失败之后
                                    });
                                }
                            })
                        }
                    }
                }
            },
            mode: 'default', // or 'simple'
            options:[],
            setQuery:{
                "communityDetail": "",
                "communityId": '',
                "communitySource": 1,
                "communityTitle": "",
                "coverImg": "",
                "publishUserId": localStorage.getItem('epid'),
                "sort": 1
            },
            rules: {
                coverImg: [{ required: true, message: "请上传封面", trigger: "change" }],
                communityId: [{ required: true, message: "请选择分类", trigger: "change" }],
                communityTitle: [{ required: true, message: "请输入标题", trigger: "blur" }],
                communityDetail: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
            },
            loading:false
        }
    },
    methods: {
        uploadEnd(val){
            this.setQuery[val.type] = val.url
        },
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        save(){
            this.loading = true
            addOrUpdateCommunity(this.setQuery).then(res=>{
                this.loading = false
                if(res.state == 'Success'){
                   this.$notify({
                  title: '成功',
                  message: '操作成功',
                  type: 'success'
                });
               
                this.$router.push('/studyManage/communityManage/index')
                }
            })
        },
        detailCommunity(tabId){
            this.loading = true
            detailCommunity({tabId}).then(res=>{
                this.loading = false
                if(res.state == 'Success'){
                  this.setQuery.communityDetail = res.content.communityDetail
                  this.setQuery.communityTitle = res.content.communityTitle
                  this.setQuery.communityId = res.content.communityId +""
                  this.setQuery.coverImg = res.content.coverImg
                }
            })
        },
        // 获取分类列表
        getTab(){
            getAllColumnId().then(res=>{
                if(res.state == 'Success'){
                  for (const item of res.content) {
                    this.options.push({
                            value:item.columnId,
                            label:item.communityName
                        })
                  }
                
                }
            })
        }
    },
    mounted() {
        this.getTab()
       this.setQuery.id =  this.$route.query.id || ''
       if(this.$route.query.id){
            this.detailCommunity(this.$route.query.id)
       }
       
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
})
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.addArticle{
    .btn-group{
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>