<template>
  <el-dialog :close-on-click-modal="false" title="添加" class="add" :visible.sync="dialogVisible" v-if="dialogVisible">
    <el-form ref="formDataAdd" :model="formData" :rules="rules" label-width="120px" v-loading="dialogLoading">
      <el-row :gutter="20">
        <el-col :span="20">
          <el-form-item label="资源类型：" prop="type">
            <!-- <el-select v-model="formData.type" clearable placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in typeList" :key="item.name" :label="item.name" :value="item.value">
              </el-option>
            </el-select> -->
            <el-input v-model="formData.typeName" disabled></el-input>
          </el-form-item>
          <el-form-item label="资源文件：" prop="name">
            <el-input v-model="formData.name">
            </el-input>
            <!-- <el-button @click="btnClick" v-if="!formData.type" type="primary" class="ml-10">
              上传<i class="el-icon-upload el-icon--right"></i>
            </el-button> -->
            <upload
              class="ml-10"
              style="display: inline-block"
              :options="uploadOptions"
              :fileList.sync="fileList"
              @on-success="handleSuccess"
              :fileType="$route.query.type" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="文件内容：" prop="contentString">
        <!-- <div class="code-mirror-div">
          <code-mirror-editor
            ref="cmEditor"
            :cmTheme="cmTheme"
            :cmMode="cmMode"
            :autoFormatJson="autoFormatJson"
            :jsonIndentation="jsonIndentation"
          ></code-mirror-editor>
          <CodeMirrorEditort
            ref="cmEditor"
            :cmTheme="cmTheme"
            :cmMode="cmMode"
            :autoFormatJson="autoFormatJson"
            :jsonIndentation="jsonIndentation"
            v-model="formData.contentString"
            />
        </div> -->
        <codeEidt  :values="formData.contentString" @changes="changeCon" :cmMode="modes" />
        <!-- <CodeMirrorEditors v-model="formData.contentString" :mode="modes"  /> -->
        <!-- <codemirror ref="myCm" @keydown.native="onKeyDown" @mousedown.native="onMouseDown" @changes="resetLint" class="code" v-model="formData.contentString" :options="cmOptions"></codemirror> -->
        <!-- <pre class="content"><textarea @keydown.tab="forbidTab($event)" @keyup.tab="replaceSpacing()" v-model="formData.contentString"></textarea></pre> -->
      </el-form-item>
    </el-form>
   <span slot="footer">
      <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
      <el-button type="primary" @click="submit('formDataAdd')">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Upload from '@/components/upload/Upload'
import { saveResourceCotent } from '@/api/esb_service'
import codeEidt from './editts.vue'
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/keymap/sublime' //sublime编辑器效果
import 'codemirror/theme/dracula.css'// 配置里面也需要theme设置为monokai
import 'codemirror/mode/vue/vue.js' // 配置里面也需要mode设置为vue
import 'codemirror/addon/selection/active-line'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
require('script-loader!jsonlint')

export default {
  components: {
    Upload,
    codeEidt
  },
  data() {
    return {
      cmTheme: 'default',
      cmEditorMode: 'default',
      cmMode: 'json',
      modes: this.$route.query.type === 'jslt' ? 'application/js' : 'xml',
      smartIndent: true,
      jsonIndentation: 2,
      autoFormatJson: true,
      cmOptions: {
        tabSize: 4, // tab的空格个数
        // theme: 'dracula', // 主题样式
        lint: true,
        gutters: [
          'CodeMirror-lint-markers'
        ],
        lineNumbers: true, // 是否显示行数
        lineWrapping: true, // 是否自动换行
        styleActiveLine: true, // line选择是是否加亮
        matchBrackets: true, // 括号匹配
        mode: 'json', // 实现javascript代码高亮
        readOnly: false// 只读
      },
      dialogVisible: this.value,
      dialogLoading: false,
      formData: {
        type: this.$route.query.type,
        contentString: ''
      },
      typeList: [],
      rules: {
        type: [{ required: true, message: '资源类型不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '资源文件不能为空', trigger: 'blur' }],
        contentString: [{ required: true, message: '资源文件不能为空', trigger: 'blur' }]
      },
      uploadOptions: {
        name: 'file',
        // type: 'icon',
        limit: 100000000
      },
      fileList: []
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    addressid: {
      type: String,
      default: ''
    }
  },
  watch: {
    value(val) {
      this.dialogVisible = val
      if (val) {
        this.$set(this.formData, 'name', '')
        this.$set(this.formData, 'contentString', '')
        this.formData.typeName = this.$route.query.type === 'jsd' ? 'JSON Schema'
          : this.$route.query.type === 'xsd' ? 'XML Schema' : this.$route.query.type
      }
    },
    dialogVisible(val) {
      this.$emit('input', val)
    }
  },
  methods: {
    changeCon(val) {
      console.log(val)
      this.formData.contentString = val
    },
    validateXML(xmlContent) {
      // errorCode 0是xml正确，1是xml错误，2是无法验证
      var xmlDoc, errorMessage, errorCode = 0
      // code for IE
      if (window.ActiveXObject) {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
        xmlDoc.async = 'false'
        xmlDoc.loadXML(xmlContent)
        if (xmlDoc.parseError.errorCode !== 0) {
          errorMessage = '错误code: ' + xmlDoc.parseError.errorCode + '\n'
          errorMessage = errorMessage + '错误原因: ' + xmlDoc.parseError.reason
          errorMessage = errorMessage + '错误位置: ' + xmlDoc.parseError.line
          errorCode = 1
        }
        else {
          errorMessage = '格式正确'
        }
      } else if (document.implementation.createDocument) {
        var parser = new DOMParser()
        xmlDoc = parser.parseFromString(xmlContent, 'text/xml')
        var error = xmlDoc.getElementsByTagName('parsererror')
        if (error.length > 0) {
          if (xmlDoc.documentElement.nodeName === 'parsererror') {
            errorCode = 1
            errorMessage = xmlDoc.documentElement.childNodes[0].nodeValue
          } else {
            errorCode = 1
            errorMessage = xmlDoc.getElementsByTagName('parsererror')[0].innerHTML
          }
        } else {
          errorMessage = '格式正确'
        }
      } else {
        errorCode = 2
        errorMessage = '浏览器不支持验证，无法验证xml正确性'
      }
      // this.$message.error(errorMessage)
      return {
        'msg': errorMessage,
        'error_code': errorCode
      }
    },
    btnClick() {
      if (!this.formData.name) {
        this.$message.error('请选择资源类型')
      }
    },
    onKeyDown(event) {
      // try {
      //   var obj = JSON.parse(this.formData.contentString)
      //   if (typeof obj === 'object' && obj) {
      //     // 对字符串进行格式化展示
      //     var nbsp = '&nbsp;&nbsp;&nbsp;&nbsp;'
      //     var num = 0
      //     var jsonend = ''
      //     var array = this.formData.contentString.split('')
      //     for (var i = 0; i < array.length; i++) {
      //       if (array[i] === '{') {
      //         num = num + 1
      //         jsonend = jsonend + array[i] + '<br/>'
      //         var temp = num
      //         while (temp > 0) {
      //           jsonend = jsonend + nbsp
      //           temp = temp - 1
      //         }
      //       } else if (array[i] === '}') {
      //         num = num - 1
      //         jsonend = jsonend + '<br/>'
      //         var temp = num
      //         while (temp > 0) {
      //           jsonend = jsonend + nbsp
      //           temp = temp - 1
      //         }
      //         jsonend = jsonend + array[i]
      //       } else if (array[i] === '[') {
      //         num = num + 1
      //         jsonend = jsonend + array[i] + '<br/>'
      //         var temp = num
      //         while (temp > 0) {
      //           jsonend = jsonend + nbsp
      //           temp = temp - 1
      //         }
      //       } else if(array[i] === ']') {
      //         num = num - 1
      //         jsonend = jsonend + '<br/>'
      //         var temp = num
      //         while (temp > 0) {
      //           jsonend = jsonend + nbsp
      //           temp = temp - 1
      //         }
      //         jsonend = jsonend + array[i]
      //       } else if (array[i] === ',') {
      //         jsonend = jsonend + array[i] + '<br/>'
      //         var temp = num
      //         while (temp > 0) {
      //           jsonend = jsonend + nbsp
      //           temp = temp - 1
      //         }
      //       } else {
      //         jsonend = jsonend + array[i]
      //       }
      //     }
      //     // 格式化完成，写入到页面
      //     this.formData.contentString = jsonend
      //   } else {
      //     console.log('格式错误')
      //     // document.getElementById("qwer").innerHTML = "格式错误"
      //   }
      // } catch (error) {
      //   console.log('格式错误')
      // }
    },
    // 按下鼠标时事件处理函数
    onMouseDown(event) {
      this.$refs.myCm.codemirror.closeHint()
    },
    resetLint() {
      console.log(this.$refs.myCm.codemirror)
      if (!this.$refs.myCm.codemirror.getValue()) {
        this.$nextTick(() => {
          this.$refs.myCm.codemirror.setOption('lint', false)
        })
        return
      }
      this.$refs.myCm.codemirror.setOption('lint', false)
      this.$nextTick(() => {
        this.$refs.myCm.codemirror.setOption('lint', true)
      })
    },
    handleSuccess(res, fileList) {
      this.formData.name = fileList[0].name
      if (res.response.status === '200') {
        this.dialogVisible = false
        this.$emit('confirm', true)
      }
    },
    forbidTab(e) {
      e.preventDefault()
    },
    replaceSpacing() {
      this.formData.contentString += '  '
    },
    submit(name) {
      const obj = {
        id: '',
        projectId: localStorage.getItem('projectID'),
        type: this.$route.query.type,
        name: this.formData.name,
        contentString: this.formData.contentString
      }
      // if (this.$route.query.type !== 'jslt') {
      //   console.log(this.formData.contentString)
      //   const isXml = this.validateXML(this.formData.contentString)
      //   if (isXml.error_code !== 0) {
      //     this.$message.error(isXml.msg)
      //     return
      //   }
      // } else {
      //   console.log(12, this.formData.contentString)
      //   try {
      //     const obj = JSON.parse(this.formData.contentString)
      //   } catch (error) {
      //     this.$message.error('格式错误, 具体请看文件内容输入框')
      //     return
      //   }
      // }
      this.$refs[name].validate((valid) => {
        if (valid) {
          saveResourceCotent(obj).then((rt) => {
            if (rt.status === '200') {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.$emit('confirm', true)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }
  },
  mounted() {
    // findAvailableResourceType().then(rt => {
    //   if (rt.status === '200') {
    //     for (let key in rt.data) {
    //       this.typeList.push({
    //         name: key,
    //         value: rt.data[key]
    //       })
    //     }
    //   }
    // })
  }
}
</script>

<style type="text/scss" lang="scss">
// .CodeMirror {
//     position: absolute;
//     top: 0px;
//     left: 0;
//     height: 300px;
//     width: 100%;
//     overflow-y: auto;
//   }
</style>
<style type="text/scss" lang="scss" scoped>
  .code-mirror-div {
    position: relative;
    // overflow: hidden;
    // width: 570px;
    height: 300px;
  }
  .add /deep/ .el-input {
    width: 80%;
  }
  textarea {
    width: 80%;
    height: 400px;
  }
</style>
