import { parseFile, findAvailableConnectType, getResourceFile } from '@/api/esb_service'
import { getFile } from '@/api/esb_global_management'
export default {
  data() {
    return {
      chickId2: '', // 获取当前选中的文件2id
      chickId1: '', // 获取当前选中的文件2id
      activeNamesss: '',
      typeList: [],
      httpMethod: [],
      bindingList: [],
      serviceList: [],
      ports: [],
      baseUrl: '',
      fileList: [],
      filename: '',
      radio: '1',
      radio1: '1',
      fileList1: [], // 文件类型1
      fileList2: [], // 文件类型2
      data: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }, {
        label: '一级 2',
        children: [{
          label: '二级 2-1',
          children: [{
            label: '三级 2-1-1'
          }]
        }, {
          label: '二级 2-2',
          children: [{
            label: '三级 2-2-1'
          }]
        }]
      }, {
        label: '一级 3',
        children: [{
          label: '二级 3-1',
          children: [{
            label: '三级 3-1-1'
          }]
        }, {
          label: '二级 3-2',
          children: [{
            label: '三级 3-2-1'
          }]
        }]
      }],
      defaultProps: {
        children: 'properties',
        label: 'name'
      },
      messageList: [
        { name: 'SOAP', value: 'SOAP' },
        { name: 'REST', value: 'REST' }
      ],
      strategyList: [
        { name: 'Http基础验证', key: 'basic' }
      ],
      httpMethodList: [
        { name: 'GET', value: 'GET' },
        { name: 'POST', value: 'POST' },
        { name: 'PUT', value: 'PUT' },
        { name: 'DELETE', value: 'DELETE' }
      ],
      payloadTypeList: [
        { name: 'XML', value: 'xml', isShow: true },
        { name: 'JSON', value: 'json', isShow: true },
        { name: 'FILE', value: 'file', isShow: true }
      ],
      defineFileTypeList: [
        { name: 'wsdl', value: 'wsdl' },
        { name: 'XML Schema', value: 'xsd' },
        { name: 'JSON Schema', value: 'jsd' }
      ],
      protocolList: [],
      isSimple: true,
      connectorVisible: false,
      resourcefileVisible: false,
      resourceFileVisible2: false,
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: ['change', 'blur'] }
        ],
        'targetService.name': [
          { required: true, message: '目标不能为空', trigger: ['change', 'blur'] }
        ],
        messageType: [
          { required: true, message: '消息类型不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.httpMethod': [
          { required: true, message: '请求方法不能为空', trigger: ['change', 'blur'] }
        ],
        payloadType: [
          { required: true, message: '报文格式不能为空', trigger: ['change', 'blur'] }
        ],
        defineFileType: [
          { required: true, message: '定义文件类型不能为空', trigger: ['change', 'blur'] }
        ],
        defineFile: [
          { required: true, message: '请求报文不能为空', trigger: ['change', 'blur'] }
        ],
        secondDefineFile: [
          { required: false, message: '响应报文不能为空', trigger: ['change', 'blur'] }
        ],
        protocol: [
          { required: true, message: '协议不能为空', trigger: ['change', 'blur'] }
        ],
        'serviceParamsMap.binding': [
          { required: true, message: '端点不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.maxMessagesPerPoll': [
          { required: true, message: '每次轮询数量不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.onConsume': [
          { required: true, message: '成功后处理不能为空', trigger: ['change', 'blur'] }
        ],
        'connector.name': [
          { required: true, message: '适配器不能为空', trigger: ['change', 'blur'] }
        ],
        uri: [
          { required: true, message: '端点uri不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.path': [
          { required: true, message: '目录路径不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.fileExist': [
          { required: true, message: '文件已存在策略不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.moveExisting': [
          { required: true, message: '移动目录不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.tempFileName': [
          { required: true, message: '临时文件名不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.pollType': [
          { required: true, message: '轮询策略不能为空', trigger: ['change', 'blur'] }
        ],
        'connectorSrvParamsMap.readLock': [
          { required: true, message: '锁策略不能为空', trigger: ['change', 'blur'] }
        ],
        'domainName': [
          { required: true, message: '分组不能为空', trigger: ['change', 'blur'] }
        ],
        'serviceParamsMap.as2Version': [
          { required: true, message: 'AS2 协议的版本不能为空', trigger: ['change', 'blur'] }
        ],
        'serviceParamsMap.requestUri': [
          { required: true, message: '请求 URI不能为空', trigger: ['change', 'blur'] }
        ],
        'serviceParamsMap.targetHostname': [
          { required: true, message: '目标服务器域名不能为空', trigger: ['change', 'blur'] }
        ],
        'serviceParamsMap.targetPortNumber': [
          { required: true, message: '目标服务器端口号不能为空', trigger: ['change', 'blur'] }
        ]
      },
      defineFileType: 'wsdl',
      kafkaParams: [
        { label: '代理：', name: 'brokers', isrequired: true, disabled: true, type: 'input' },
        { label: '主题：', name: 'topic', isrequired: true, disabled: false, type: 'input' },
        { label: '安全协议', name: 'BAS_securityProtocol', disabled: false, type: 'select', options: ['PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL'] },
        { label: 'sasl机制：', name: 'BAS_saslMechanism', disabled: false, type: 'select', options: ['PLAIN', 'GSSAPI'] },
        { label: 'saslJaas配置：', name: 'saslJaasConfig', disabled: false, type: 'select', options: ['org.apache.kafka.common.security.plain.PlainLoginModule required'] },
        { label: '账号：', name: 'username', disabled: false, type: 'input' },
        { label: '密码：', name: 'password', disabled: false, type: 'input' }
      ]
    }
  },
  props: {
    isShowSubmit: {
      type: Boolean,
      default: true
    },
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    typeObject() {
      return {
        messageType: this.formData.messageType,
        payloadType: this.formData.payloadType
      }
    }
  },
  watch: {
    httpMethod: {
      handler: function(val) {
        console.log(val)
        if (val.length > 0) {
          this.$set(this.formData.connectorSrvParamsMap, 'httpMethod', val.join())
        }
      },
      deep: true,
      immediate: true
    },
    'formData.messageType': {
      handler: function(val) {
        this.rules.defineFileType[0].required = val !== 'REST' && val !== 'db'
        this.rules.defineFile[0].required = val !== 'REST'
        // this.rules.secondDefineFile[0].required = val !== 'REST'
        this.rules['serviceParamsMap.binding'][0].required = val !== 'REST'
        // 改变报文格式数据显示
        this.payloadTypeList.forEach(item => {
          item.isShow = true
        })
        if (val === 'SOAP') {
          this.payloadTypeList.forEach(item => {
            item.isShow = item.value === 'xml'
          })
        }
      }
    },
    'formData.defineFileType': {
      handler: function(val) {
        this.defineFileTypeList.forEach(item => {
          if (val === item.value) {
            this.defineFileType = item.value
          }
        })
      },
      immediate: true
    },
    'formData.defineFile': {
      handler: function(val) {
        this.parseFile()
      }
    },
    'formData.protocol': {
      handler: function(val) {
        console.log(val, JSON.parse(JSON.stringify(this.protocolList)))
        this.protocolList.forEach(item => {
          if (val === item.type) {
            this.isSimple = item.isSimple
          }
        })
      }
    }
  },
  methods: {
    // 获取默认的配置文件
    getResourceFile(id, pid) {
      getResourceFile(id, pid).then(res => {
        if (res.data.length > 0) {
          this.messageTypeChange('REST')
          this.formData.payloadType = 'json'
          this.payloadTypeChange()
          res.data.map((ite, index) => {
            if (index === 0) {
              this.$set(this.formData, 'objname', `${this.sqlObj.perjectName}-${ite.type}-${ite.name}`)
              if (this.formData.payloadType === 'json') {
                getFile(ite.id).then(res => {
                  this.fileList1.push(res.data.schemaMap.root)
                })
              }
            }
            if (index === 1) {
              this.$set(this.formData, 'objname1', `${this.sqlObj.perjectName}-${ite.type}-${ite.name}`)
              if (this.formData.payloadType === 'json') {
                getFile(ite.id).then(res => {
                  this.fileList2.push(res.data.schemaMap.root)
                })
              }
            }
          })
        }
      })
    },
    // 消息类型 改变时
    messageTypeChange(val) {
      // 改变报文格式数据显示
      if (val === 'SOAP') {
        this.formData.payloadType = 'xml'
        if (!this.formData.defineFile) {
          this.parseFile()
        }
      } else {
        // this.$set(this.formData, 'payloadType', '') // 清空报文格式
        this.formData.payloadType = 'json'
      }
      this.$set(this.formData.connectorSrvParamsMap, 'httpMethod', '') // 清空请求方法Http Method
      this.httpMethod = [] // 清空请求方法Http Method
      this.typeDeal()
      this.$refs.formData.clearValidate(['payloadType', 'defineFileType', 'defineFile', 'serviceParamsMap.binding'])
    },
    // 报文格式 改变时
    payloadTypeChange() {
      this.$set(this.formData, 'objname', '')
      this.$set(this.formData, 'objname1', '')
      this.fileList1 = []
      this.fileList2 = []
      this.typeList = []
      this.typeDeal()
    },
    // 消息类型 加 报文格式  联动公共处理
    typeDeal() {
      this.$set(this.formData, 'defineFileType', '')
      if (this.formData.messageType === 'SOAP' && this.formData.payloadType === 'xml') {
        this.$set(this.formData, 'defineFileType', 'wsdl')
      } else if (this.formData.messageType === 'REST' && this.formData.payloadType === 'xml') {
        this.$set(this.formData, 'defineFileType', 'xsd')
      } else if (this.formData.messageType === 'REST' && this.formData.payloadType === 'json') {
        this.$set(this.formData, 'defineFileType', 'jsd')
      }
      this.$set(this.formData, 'defineFile', '')
      this.$set(this.formData, 'secondDefineFile', '')
      this.$set(this.formData, 'secondDefineFileId', '')
      this.$set(this.formData.serviceParamsMap, 'binding', '')
      this.bindingList = []
      this.serviceList = []
      this.ports = []
      this.$forceUpdate()
    },
    chooseDefineFile() {
      this.resourcefileVisible = true
    },
    // 为了减少原来代码的影响，这里再定义一个。。
    chooseDefineFile2() {
      this.resourceFileVisible2 = true
    },
    handleResourcefile(data) {
      console.log(data)
      this.typeList = []
      this.chickId1 = data[0].id
      // console.log(this.chickId1, '111')
      // console.log(this.data, '2222')
      this.$set(this.formData, 'defineFile', data[0].path)
      this.$set(this.formData, 'defineFileId', data[0].id)
      this.$set(this.formData, 'definename', data[1].name)
      // this.$set(this.formData, 'objname', `${data[1].name}-${data[0].type}-${data[0].name}`)
      this.$set(this.formData, 'objname', `${data[0].name}`)
      if (this.formData.payloadType === 'xml') {
        getFile(data[0].id).then(res => {
          // res.data.schemaMap.map(item => {
          //   this.typeList.push(item)
          // })
          if (this.formData.messageType.toLowerCase() === 'soap') {
            this.$set(this.formData, 'soapBindingList', res.data.bindingList)
          }
          this.typeList = []
          for (var i in res.data.schemaMap) {
            this.typeList.push({
              type: i,
              content: res.data.schemaMap[i]
            })
          }
          console.log(this.typeList, '111')
          if (this.typeList[0]) {
            this.activeNamesss = this.typeList[0].type
          }
          this.fileList1 = []
          this.typeList.map(item => {
            if (item.type === this.activeNamesss) {
              this.fileList1.push(item.content)
            }
          })
          // this.fileList1.push(res.data.schemaMap.root)
        })
        return false
      }
      if (this.formData.payloadType === 'json') {
        getFile(data[0].id).then(res => {
          this.fileList1.push(res.data.schemaMap.root)
        })
      }
    },
    handleResourceFile2(data) {
      this.chickId2 = data[0].id
      this.$set(this.formData, 'secondDefineFile', data[0].path)
      this.$set(this.formData, 'secondDefineFileId', data[0].id)
      this.$set(this.formData, 'definename', data[1].name)
      this.$set(this.formData, 'objname1', `${data[1].name}-${data[0].type}-${data[0].name}`)
      console.log(this.formData, '定义2')
      getFile(data[0].id).then(res => {
        this.fileList2.push(res.data.schemaMap.root)
      })
    },
    parseFile() {
      if (this.formData.defineFileId) {
        // let defineFile = []
        // if (this.formData.defineFile.includes('/')) {
        //   defineFile = this.formData.defineFile.split('/')
        // } else if (this.formData.defineFile.includes('\\')) {
        //   defineFile = this.formData.defineFile.split('\\')
        // }
        // let name, type
        // if (defineFile.length > 1) {
        //   name = defineFile[defineFile.length - 1].split('.')[0]
        //   type = defineFile[defineFile.length - 2]
        // }
        parseFile(this.formData.defineFileId).then(rt => {
          if (rt.status === '200' && rt.data && rt.data.parserContent && rt.data.parserContent.bindingList) {
            this.bindingList = rt.data.parserContent.bindingList || []
            this.serviceList = rt.data.parserContent.serviceList || []
            this.ports = []
            const _this = this
            this.typeList = []
            for (var i in rt.data.parserContent.schemaMap) {
              this.typeList.push({
                type: i,
                content: rt.data.parserContent.schemaMap[i]
              })
            }
            console.log(this.typeList, '111')
            if (this.typeList[0]) {
              this.activeNamesss = this.typeList[0].type
            }
            this.fileList1 = []
            this.typeList.map(item => {
              if (item.type === this.activeNamesss) {
                this.fileList1.push(item.content)
              }
            })
            this.serviceList.forEach(function(service) {
              if (service.ports) {
                _this.ports = [
                  ..._this.ports,
                  ...service.ports
                ]
              }
            })
          }
          console.log(this.ports, '在吗')
        }).catch(() => {
        })
      }
    },
    findAvailableConnectType() {
      findAvailableConnectType().then(rt => {
        if (rt.status === '200') {
          this.protocolList = rt.data
          this.protocolList.push({
            type: 'EDI'
          })
          this.protocolList.forEach(item => {
            if (this.formData.protocol === item.type) {
              this.isSimple = item.isSimple
            }
          })
        }
      }).catch(() => {
        this.tableLoading = false
      })
    },
    protocolChange(val) {
      this.$set(this.formData.connector, 'name', '')
      this.$set(this.formData, 'connectorType', '')
      this.$set(this.formData, 'connectorId', '')
    },
    chooseConnector() {
      this.connectorVisible = true
    },
    handleConnector(data) {
      console.log('适配器', data)
      this.$set(this.formData.connector, 'name', data.name)
      this.$set(this.formData, 'connectorType', data.connectorType)
      this.$set(this.formData, 'connectorId', data.id)
      if (data.jsonInfo) {
        const jsonInfo = JSON.parse(data.jsonInfo)
        this.$set(this.formData.connectorSrvParamsMap, 'brokers', jsonInfo.brokers)
      }
    }
  },
  mounted() {
    this.findAvailableConnectType()
  }
}
