<template>
  <div class="agencyinfo">
    <el-form ref="formData" :model="formData" :rules="rules" label-width="140px">
      <div style="z-index: 999;position: relative;">
        <!-- <el-button type="primary" class="float-r" v-show="formData.name" @click="showFile">查看文件内容</el-button> -->
        <el-button type="primary" class="float-r mr-15" @click="submit" >保存</el-button>
        <!-- <el-button type="primary" class="float-r mr-15" @click="showMsg"  v-if="currentRow.id">依赖检测</el-button> -->
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick" type="card">
        <el-tab-pane label="一般信息" name="first">
          <el-row :gutter="18">
            <el-col :span="18">
              <el-form-item label="文件名称：" prop="name">
                <el-input v-model="formData.name"></el-input>
              </el-form-item>
              <el-form-item label="描述：">
                <el-input v-model="formData.description" type="textarea"></el-input>
              </el-form-item>
              <!-- <el-form-item label="文件类型：" v-if="fileType === 'wsdl'">
                <el-input v-model="formData.type" readonly></el-input>
              </el-form-item> -->
              <el-form-item label="文件内容：" class="fileContent">
                <el-form-item label="命名空间：" label-width="80px" v-if="parserContent.namespaces">
                  <div>{{parserContent.namespaces.web}}</div>
                </el-form-item>
                <el-form-item label="binding：" label-width="80px" v-if="parserContent.bindingList">
                  <div v-for="(item, index) in parserContent.bindingList" :key="index">{{item.name}}</div>
                </el-form-item>
                <el-form-item label="ports：" label-width="80px" v-if="parserContent.serviceList">
                  <div v-for="(item, index) in parserContent.serviceList" :key="index">
                    <div v-for="(item2, index2) in item.ports" :key="index2">{{item2.name}}</div>
                  </div>
                </el-form-item>
                <el-form-item label="操作：" label-width="80px" v-if="parserContent.bindingList">
                  <div v-for="(item, index) in parserContent.bindingList" :key="index">
                    <div v-for="(item2, index2) in item.operation" :key="index2">{{item2.name}}</div>
                  </div>
                </el-form-item>
              </el-form-item>
              <el-form-item label="端点URL：" v-if="fileType === 'wsdl'">
                <div v-for="(val, index) in parserContent.endpoints" :key="index">{{val}}</div>
              </el-form-item>
              <!-- <el-form-item label="schema：">
                <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
              </el-form-item> -->
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane v-if="currentRow.id" label="依赖检测" name="second">
          <depend-onthe-test type="resource" :formData="formData"  :titleName="titleName" :dialogVisible="dialogVisible"/>
        </el-tab-pane>
        <el-tab-pane v-show="formData.name && activeName === 'third'" label="文件内容" name="third">
           <el-button @click="saveFile">保存文件</el-button>
           <codeEidt :values="fileData"  @changes="changeCon" :cmMode="modes" />
          <!-- <pre class="content"><textarea ref="pre" v-model="fileData"></textarea></pre> -->
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-dialog :close-on-click-modal="false" title="文件内容" :visible.sync="dialogVisible" append-to-body top="10vh">
      <pre class="content">{{fileData}}</pre>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DependOntheTest from '@/components/Dependonthetest/Dependonthetest'
import { saveFiles, showFileContent, parseFile, saveResourceCotent } from '@/api/esb_service'
import { checkFormData } from '@/utils/common'
import codeEidt from './editts.vue'
import { createNamespacedHelpers } from 'vuex'
// const { mapMutations, mapGetters } = createNamespacedHelpers('app')
const { mapGetters } = createNamespacedHelpers('app')
export default {
  components: {
    DependOntheTest,
    codeEidt
  },
  data() {
    return {
      modes: this.$route.query.type === 'jslt' ? 'application/json' : 'xml',
      formData: {},
      activeName: 'first',
      typeList: [],
      dialogVisible: false,
      fileData: '',
      parserContent: {},
      // defaultProps: {
      //   children: 'children',
      //   label: 'label'
      // },
      fileType: this.$route.query.type,
      rules: {
        name: [{ required: true, message: '请输入文件名称', trigger: 'change' }]
      },
      resourcetVisible: false,
      dialogVisibles: false,
      titleName: '资源文件'
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    isShowSubmit: {
      type: Boolean,
      default: true
    },
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: function(val) {
        this.dialogVisibles = val
        this.$nextTick(() => {
          this.$refs.formData.clearValidate()
        })
        this.$set(this.currentRow, 'changetime', Date.parse(new Date()))
      },
      deep: true
    },
    dialogVisibles(val) {
      this.$emit('input', val)
    },
    currentRow: {
      immediate: true,
      handler: function(val) {
        this.formData = Object.assign({}, val)
        this.parserContent = {}
        if (val && val.id) {
          this.getDetail()
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters(['projectID'])
  },
  methods: {
    changeCon(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
      }
    },
    forbidTab(e) {
      e.preventDefault()
    },
    replaceSpacing() {
      this.formData.contentString += '  '
    },
    getDetail() {
      let name = this.formData.name.split('.')[0]
      parseFile(this.formData.id).then((rt) => {
        if (rt.status === '200' && rt.data) {
          this.parserContent = rt.data.parserContent || {}
        }
      }).catch(() => {
      })
      console.log('123')
    },
    handleClick(tab, event) {
      console.log(tab, event)
      if (tab.name === 'third') {
        this.showFile()
      }
    },
    showFile() {
      showFileContent(this.formData.id).then((rt) => {
        if (rt.status === '200') {
          this.fileData = rt.data
          // this.dialogVisible = true
        }
      }).catch(() => {
      })
    },
    saveFile() {
      // if (this.$route.query.type !== 'jslt') {
      //   const isXml = this.validateXML(this.formData.contentString)
      //   if (isXml.error_code !== 0) {
      //     this.$message.error(isXml.msg)
      //     return
      //   }
      // } else {
      //   try {
      //     const obj = JSON.parse(this.formData.contentString)
      //   } catch (error) {
      //     this.$message.error('格式错误')
      //     return
      //   }
      // }
      const obj = {
        id: this.formData.id,
        contentString: this.formData.contentString,
        type: this.formData.type,
        projectId: this.projectID,
        name: this.currentRow.name
      }
      saveResourceCotent(obj).then((rt) => {
        if (rt.status === '200') {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    async submit() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          // console.log(this.formData)
          this.formData.projectId = this.projectID
          saveFiles(this.formData).then((rt) => {
            if (rt.status === '200') {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.$emit('confirm')
            }
          }).catch(err => {
            const data = err.data || []
            const hint = [
              { fieName: '文件名称', field: 'name' },
              { fieName: '描述', field: 'description' }
            ]
            checkFormData(data, hint)
          })
        }
      })
    },
    // tree事件
    handleNodeClick(data) {
      // console.log(data)
    },
    showMsg() {
      this.resourcetVisible = true
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.el-select {
  width: 100%;
}
textarea {
  width: 100%;
  height: 400px;
}
.content {
  padding: 20px;
  line-height: 28px;
  // max-height: 300px;
  // overflow-y: scroll;
}
.fileContent {
  /deep/ .el-form-item__content {
    .el-form-item {
      margin-bottom: 8px;
    }
    .el-form-item__label {
      text-align: left;
    }
  }
}
</style>
