<template>
    <el-card shadow="never" class="aui-card--fill">
        <div class="mod-news__typicalcase}">
            <el-form :inline="true"
                     :model="dataForm"
                     :rules="dataRule"
                     ref="dataForm"
                     :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
                <el-row>
                    <el-form-item label="banner：" v-loading="loading" prop="mainPicture">
                        <el-upload class="avatar-uploader"
                                   :action="uploadUrl"
                                   :show-file-list="false"
                                   :on-success="handleAvatarActSuccess"
                                   :on-error="handelError"
                                   :before-upload="beforeAvatarUpload">
                            <img v-if="dataForm.mainPicture"
                                 :src="dataForm.mainPicture"
                                 class="avatar">
                            <i v-else
                               class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip"
                                 class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="案例标题：" prop="caseTitle">
                        <el-input v-model="dataForm.caseTitle" type="text"
                                  maxlength="40"
                                  show-word-limit
                                  placeholder="请输入标题，40字以内"
                                  clearable
                                  style="width:500px"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="摘要：" prop="typicalAbstract">
                        <el-input  v-model="dataForm.typicalAbstract" placeholder="文本输入框，限制200字内" type="textarea"
                                   style="width:500px"
                                   maxlength="200"
                                   clearable></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <div v-for="(item, index) in dataForm.dynamicItem" :key="index">
                        <div style="text-align: left">{{"案例"+(index+1)}}</div>
                        <el-row>
                            <el-form-item label="案例来源："
                                          prop="caseSource">
                                <el-input v-model="item.caseSource"
                                          :disabled="true"
                                          type="text"
                                          clearable
                                          style="width: 40rem;">
                                </el-input>&emsp;
                                &emsp;
                                <el-button @click="addConnect(index)">{{"选择案例"}}</el-button>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="案例类型："prop="associatedType">
                                <el-select v-model="item.associatedType" :disabled="true">
                                    <el-option label="议题" value="0"></el-option>
                                    <el-option label="项目" value="1"></el-option>
                                    <el-option label="话题" value="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="内容描述：" prop="contentDescription">
                                <el-upload ref="upload"
                                           :action="uploadUrl"
                                           id ="quill-upload"
                                           :show-file-list="false"
                                           :before-upload="uploadBeforeUploadHandle"
                                           :on-success="uploadSuccessHandle"
                                           style="display: none;">
                                    <el-button ref="uploadBtn"
                                               type="primary"
                                               id="uploadBtn"
                                               size="small">{{ $t('upload.button') }}</el-button>
                                </el-upload>
                                <quill-editor ref="myQuillEditor" v-model="item.contentDescription" :options="editorOption" @focus="onEditorFocus(index)"></quill-editor>
                            </el-form-item>
                        </el-row>
                    </div>
                </el-row>
                <el-form-item>
                    <el-button :disabled="isAble" @click="addItem">{{"添加案例"}}</el-button>
                </el-form-item>
            </el-form>
            <el-form>
                <el-button type="primary" :disabled="isAble" @click="dataFormSubmitHandle()">{{"发布案例"}}</el-button>
                <el-button size="small" :disabled="isAble" style="width: 95px" @click="back">返回</el-button>
            </el-form>
            <el-form>
                <el-row>

                </el-row>
            </el-form>
            <typicalcase-connect-list v-if="connectListVisible"  ref="connectList" @refreshDataList="getDataList"  v-on:connectResponse="connectResponse"></typicalcase-connect-list>
        </div>
    </el-card>
</template>

<script>
import debounce from 'lodash/debounce'
import TypicalcaseConnectList from './typicalcase-connect-list'
import { quillEditor } from 'vue-quill-editor'
import CaseInfoList from './typicalcase-list'
import Quill from 'quill'
import Cookies from 'js-cookie'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import mixinViewModule from '@/mixins/view-module'
export default {
  mixins: [mixinViewModule],
  created () {
    this.addItem()
    this.addItem()
    this.$nextTick(() => {
      // 富文本
      this.hideUpload = false
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
      // if (this.quillEditor) {
      //   this.quillEditor.deleteText(0, this.quillEditor.getLength())
      // } else {
      //   this.quillEditorHandle()
      // }
      // 富文本end
    })
  },
  components: {
    quillEditor,
    TypicalcaseConnectList,
    CaseInfoList
  },
  data () {
    return {
      fileList: [],
      connectListVisible: false,
      content: '',
      loading: false,
      isAble: false,
      editorOption: {
          placeholder: 'Please enter it here...',
          modules:{
              toolbar:{
                  container: [
                      ['bold', 'italic', 'underline', 'strike'],// 加粗，斜体，下划线，删除线
                      ['blockquote'],// 引用
                      [{ 'header': 1 }, { 'header': 2 }],// 标题，键值对的形式；1、2表示字体大小
                      [{ 'list': 'ordered'}, { 'list': 'bullet' }],//列表
                      [{ 'indent': '-1'}, { 'indent': '+1' }],// 缩进
                      [{ 'direction': 'rtl' }],// 文本方向
                      [{ 'size': ['small', false, 'large', 'huge'] }],// 字体大小
                      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],//几级标题
                      [{ 'color': [] }, { 'background': [] }],// 字体颜色，字体背景颜色
                      [{ 'font': [] }],//字体
                      [{ 'align': [] }],//对齐方式
                      ['clean'],//清除字体样式
                      ['image']//上传图片、上传视频
                  ],
                  handlers: {
                      'image': function (value) {
                          if (value) {
                              // 给个点击触发Element-ui，input框选择图片文件
                              document.querySelector('#quill-upload input').click()
                          } else {
                              this.quill.format('image', false);
                          }
                      }
                  }
              }
          }
      },
      uploadUrl: '',
      dataForm: {
        id: '',
        state: 1,
        caseTitle: '',
        caseNumber: 0,
        mainPicture: '',
        typicalAbstract: '',
        dynamicItem: []
      },
        imgIndex: 0,
      requiredFlag: false
    }
  },
  mounted () {
    this.dataForm.id = this.$route.query.id
    this.init()
  },
  computed: {
    dataRule () {
      return {
        caseTitle: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        mainPicture: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        typicalAbstract: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
          associatedId: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onEditorFocus(index) {
        this.imgIndex = index
    },
    handleChange (file) {
      this.beforeAvatarUpload(file)
    },
    back () {
        this.$parent.selectComponent = 'CaseInfoList'
        this.$router.push({ path: '/case-typicalcase'})
    },
    connectResponse (connectResponse) {
        // 部门名称
        this.dataForm.dynamicItem[connectResponse.caseIndex].caseSource = connectResponse.allDeptNames
        // 案例类别
        this.dataForm.dynamicItem[connectResponse.caseIndex].associatedType = connectResponse.associatedType
        // 内容描述
        if (connectResponse.associatedType == 0) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].contentDescription = connectResponse.issueContent
        } else if (connectResponse.associatedType == 1) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].contentDescription = connectResponse.itemContent
        } else if (connectResponse.associatedType == 2) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].contentDescription = connectResponse.topicContent
        }
        // 类别
        this.dataForm.dynamicItem[connectResponse.caseIndex].category = connectResponse.categoryName
        // 案例ID
        this.dataForm.dynamicItem[connectResponse.caseIndex].associatedId = connectResponse.id
        // 网格Id
        this.dataForm.dynamicItem[connectResponse.caseIndex].sourceGridId = connectResponse.gridId
        //发布人姓名
        if (connectResponse.associatedType == 0) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].publisherName = connectResponse.nickName
        } else if (connectResponse.associatedType == 1) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].publisherName = connectResponse.nickName
        } else if (connectResponse.associatedType == 2) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].publisherName = connectResponse.nickname
        }
        // 头像
        this.dataForm.dynamicItem[connectResponse.caseIndex].publisherHeader = connectResponse.userFace
        // 内容
        if (connectResponse.associatedType == 0) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].content = connectResponse.issueContent
        } else if (connectResponse.associatedType == 1) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].content = connectResponse.itemContent
        } else if (connectResponse.associatedType == 2) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].content = connectResponse.topicContent
        }
        if (connectResponse.associatedType == 0) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].releaseTime = connectResponse.distributeTime
        } else if (connectResponse.associatedType == 1) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].releaseTime = connectResponse.distributeTime
        } else if (connectResponse.associatedType == 2) {
            this.dataForm.dynamicItem[connectResponse.caseIndex].releaseTime = connectResponse.createdTime
        }
        this.dataForm.dynamicItem[connectResponse.caseIndex].expressingAttitude = connectResponse.participantsNum

        this.requiredFlag = true
    },
    addConnect(index){
        this.connectListVisible = true
        this.$nextTick(() => {
            this.$refs.connectList.init(index)
        })
    },
    // 动态添加
    addItem () {
      this.dataForm.dynamicItem.push({
          caseSource: '',
          associatedType: '',
          contentDescription: '',
          category: '',
          associatedId: '',
          sourceGridId: '',
          publisherName: '',
          publisherHeader: '',
          releaseTime: '',
          content: '',
          expressingAttitude: ''

      })
    },

    // 富文本编辑器
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      this.quillEditor.container.style.height = `${300}px`
      // // 自定义上传图片功能 (使用element upload组件)
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.dataForm.actContent = this.quillEditor.root.innerHTML
        if ((this.dataForm.actContent).length > 10000) {
          return this.$message.error('您输入的的内容已超过字数')
        }
      })
    },
    // 上传图片之前 (富文本)
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
    },

    // 上传图片成功 (富文本)
    uploadSuccessHandle (res) {
      let quill = this.$refs.myQuillEditor[this.imgIndex].quill;
        console.log(quill)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      quill.insertEmbed(quill.getSelection().index, 'image', res.data.url)
      quill.setSelection(quill.getSelection().index + 1)
    },
    // 上传图片ends
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
            this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
        this.$http.get(`/cloudAnalysis/typicalcase/${this.dataForm.id}`).then(({ data: res }) => {
            if (res.code !== 0) {
                return this.$message.error(res.msg)
            }
            this.dataForm = {
                ...this.dataForm,
                ...res.data
            }
        }).catch(() => {})
        this.requiredFlag = true
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if(!this.requiredFlag){
            alert("请关联案例！")
            return false
        }
          for(let item of this.dataForm.dynamicItem) {
              if(item.associatedId != '') {
                  this.dataForm.caseNumber = this.dataForm.caseNumber + 1
              }
          }
        this.isAble = true;
        this.$http[!this.dataForm.id ? 'post' : 'put']('/cloudAnalysis/typicalcase', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            this.isAble = false;
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
                this.isAble = false;
                this.back()
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),
      handleAvatarActSuccess (res, file) {
          this.loading = false
          this.dataForm.mainPicture = res.data.url
      },
      beforeAvatarUpload (file) {
          this.loading = true
      },
      handelError () {
          this.loading = false
      },
  }
}
</script>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
<style lang="scss">
    .project-handle {
        .el-timeline {
            padding-left: 9px;
            font-size: 13px;
        }
        .el-textarea {
            width: 600px !important;
        }
        .el-input {
            width: 600px !important;
        }
    }
    .el-form-item__label {
        font-weight: bold;
    }
    .quill-editor {
        width:60rem;
        height: 400px;
        .ql-container {
            height: 350px;
        }
    }
</style>

<style lang="scss" scoped>
    .project-handle {
        width: 100%;
        height: calc(100vh - 120px);
        background: #ffffff;
        box-sizing: border-box;
        padding: 10px;
        .project-detail {
            width: 100%;
            height: 49%;
            border: 2px solid #ccc;
            box-sizing: border-box;
            padding: 10px;
            padding-top: 20px;
            float:left;
            margin-bottom: 1%;
            position:relative;
            .project-detail-tip {
                position: absolute;
                top: 0;
                left:0;
                width: 80px;
                height: 30px;
                line-height: 30px;
                color: #ffffff;
                background: #4ac38b;
                text-align:center;
            }
            .el-form {
                width: 58%;
                height: 100%;
                float:left;
                overflow-y:auto;
                &::-webkit-scrollbar {
                    width: 5px;
                    height: 1px;
                }
                &::-webkit-scrollbar-thumb {
                    border-radius: 5px;
                    background: #ccc;
                }
                &::-webkit-scrollbar-track {
                    border-radius: 10px;
                    background: #fff;
                }
            }
            .container {
                width: 40%;
                height: 100%;
                float: right;
                .location {
                    height: 30px;
                    line-height: 30px;
                }
                #map {
                    width: 100%;
                    height: calc(100% - 30px);
                }
            }
        }
        .project-progress {
            width: 20%;
            height: 100%;
            float: right;
            border: 2px solid #ccc;
            box-sizing: border-box;
            margin-left: 1%;
            padding-top: 20px;
            overflow-y:auto;
            &::-webkit-scrollbar {
                width: 5px;
                height: 1px;
            }
            &::-webkit-scrollbar-thumb {
                border-radius: 5px;
                background: #aaa;
            }
            &::-webkit-scrollbar-track {
                border-radius: 10px;
                background: #ccc;
            }
        }
        .handle-operation {
            padding-top: 30px;
            box-sizing: border-box;
            width: 100%;
            height: 49%;
            box-sizing: border-box;
            border: 2px solid #ccc;
            float:left;
            position: relative;
            overflow-y:auto;
            &::-webkit-scrollbar {
                width: 5px;
                height: 1px;
            }
            &::-webkit-scrollbar-thumb {
                border-radius: 5px;
                background: #aaa;
            }
            &::-webkit-scrollbar-track {
                border-radius: 10px;
                background: #ccc;
            }
            .handle-operation-tip {
                position: absolute;
                top: 0;
                left:0;
                width: 80px;
                height: 30px;
                line-height: 30px;
                color: #ffffff;
                background: #ff7600;
                text-align:center;
            }
        }
    }
</style>
