<template>
  <el-dialog append-to-body class="debug" @close="closeDialog" :close-on-click-modal="false" :title="title" :visible.sync="dialogFormVisible" :destroy-on-close="true" width="50%">
    <div v-if="this.row.type === 'flowManager'">
      <h3>测试配置 <el-checkbox style="margin-left: 40px;" v-model="track">包括跟踪</el-checkbox></h3>
    </div>
    <h3 class="titles">请求文档</h3>
    <el-form :model="resFrom" :rules="rules" ref="resFrom" label-width="100px" class="demo-ruleForm">
        <el-row :gutter="20">
            <el-col :span="12" class="selectWidth">
                <el-form-item v-if="this.reqType !== 'soap'" label="报文类型" prop="desc">
                    <el-select v-model="resFrom.type" 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 v-if="this.reqType === 'soap'" label="请求方法" prop="desc">
                    <el-select v-model="resFrom.type" placeholder="请选择">
                        <el-option
                        v-for="item in soapMethod"
                        :key="item.name"
                        :label="item.name"
                        :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="编码" prop="desc">
                    <el-input v-model="resFrom.code"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="12"  class="inputDisplay">
                <el-form-item label="请求文件" prop="desc">
                    <el-input v-model="resFrom.name"></el-input>
                    <el-button @click="choicePDF()" type="parmiay">选择文件</el-button>
                    <input
                      ref="filElemPDF"
                      type="file"
                      class="upload-file"
                      @change="readFile"
                      style="display: none"
                      id="fileUploadSQ"
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <!-- <el-row :gutter="20" v-if="this.reqType === 'soap'">
            <el-col :span="24">
                <el-form-item class="soapCode" label="请求报文" prop="desc">
                    <codeEidt :values="fileDatas"  @changes="changeCon1" :cmMode="mode" />
                </el-form-item>
            </el-col>
        </el-row> -->
       
        <el-row :gutter="20">
            <el-col :span="24">
                <el-form-item   class="soapCode" label="请求报文" prop="desc">
                    <codeEidt :values="fileDatas"  @changes="changeCon1" :cmMode="mode" />
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
    <h3>
        传输设置
        <el-button style="float: right"  type="text" @click="isShow('ruleForm','fileexpand')" :class="[fileexpand ? 'el-icon-arrow-down' : 'el-icon-arrow-left']"></el-button>
    </h3>
    <div ref="ruleForm">
        <el-form :model="ruleForm" :rules="rules"  label-width="100px" class="demo-ruleForm">
            <el-row :gutter="20" style="margin-top:20px" >
            <!-- v-if="this.row.type !== 'flowManager'" -->
                <el-col :span="8">
                    <el-form-item label="">
                        <el-checkbox style="margin-left: -90px;" v-model="isEnableBasic">是否启用用户</el-checkbox>
                    </el-form-item>
                </el-col>
                <el-col style="margin-left: -135px;" :span="8">
                    <el-form-item label="用户名" prop="desc">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="密码" prop="desc">
                        <el-input type="password" v-model="ruleForm.password"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="row.connectorType === 'DB'">
              <el-form-item label="分组： "   prop="domainName">
                <el-input
                   
                  v-model="domainClass.domainName"
                  suffix-icon="el-icon-search"
                  @click.native="areaDialog=true"
                  readonly>
                </el-input>
              </el-form-item>
            </el-row>
            <el-row :gutter="20" v-if="this.reqType !== 'soap' && this.row.type !== 'flowManager'">
                <el-col :span="12" class="selectWidth">
                    <el-form-item label="请求方法" prop="desc">
                        <el-select v-model="ruleForm.http" placeholder="请选择">
                            <el-option
                            v-for="item in option"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24" v-if="this.reqType !== 'soap' && this.row.type !== 'flowManager'">
                    <el-form-item label="查询参数" prop="desc">
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="名称" prop="desc">
                                    <el-input v-model="queryArg.key"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="值" prop="desc">
                                    <el-input v-model="queryArg.value"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4" class="addAlign">
                                <el-button @click="addRow('queryArgData', 'queryArg')">添加</el-button>
                            </el-col>
                        </el-row>
                        <div>
                            <el-table
                                :data="queryArgData"
                                border
                                style="width: 100%">
                                <el-table-column
                                prop="key"
                                align="center"
                                label="名称"
                                width="180">
                                </el-table-column>
                                <el-table-column
                                prop="value"
                                label="值"
                                align="center"
                                width="180">
                                </el-table-column>
                                <el-table-column
                                align="center"
                                label="操作">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="delRow(scope.row, 'queryArgData')" icon="el-icon-delete" size="small"></el-button>
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="用户标头" prop="desc">
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="名称" prop="desc">
                                    <el-input v-model="nameHead.key"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item label="值" prop="desc">
                                    <el-input v-model="nameHead.value"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4" class="addAlign">
                                <el-button  @click="addRow('nameHeadData', 'nameHead')">添加</el-button>
                            </el-col>
                        </el-row>
                        <div>
                            <el-table
                                :data="nameHeadData"
                                border
                                style="width: 100%">
                                <el-table-column
                                prop="key"
                                align="center"
                                label="名称"
                                width="180">
                                </el-table-column>
                                <el-table-column
                                prop="value"
                                align="center"
                                label="值"
                                width="180">
                                </el-table-column>
                                <el-table-column
                                align="center"
                                label="操作">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="delRow(scope.row,'nameHeadData')" icon="el-icon-delete" size="small"></el-button>
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <SelectArea v-model="areaDialog" :connectorId="domainClass.domainId" @confirm="getArea" />
    <endView v-model="dialogEnd" :track="track" :row="executeObj" :titles="row" @confirm="End" />
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" :loading="restDisable" @click="restDisable = true,rest()">重 置</el-button>
      <el-button type="primary" :loading="exeDisable" @click="exeDisable = true,execute()">执 行</el-button>
    </span>
  </el-dialog>
</template>

<script>
import SelectArea from '@/views/esb_service/node_manage/SelectArea'
import codeEidt from '@/views/esb_service/resource_file/editts.vue'
import { debugExecute, debugExecuteDb, debugLog, methodsWsdl } from '@/api/debug'
import { parseFile } from '@/api/esb_service.js'
import endView from './end.vue'
import { throws } from 'assert'
export default {
  components: {
    codeEidt,
    SelectArea,
    endView
  },
  data() {
    const options = [
      {
        label: 'application/xml',
        value: 'application/xml'
      }, {
        label: 'application/text',
        value: 'application/text'
      }, {
        label: 'application/json',
        value: 'application/json'
      }, {
        label: 'text/plain',
        value: 'text/plain'
      }, {
        label: 'text/xml',
        value: 'text/xml'
      }
    ]
    const option = [
      {
        label: 'POST',
        value: 'POST'
      }, {
        label: 'GET',
        value: 'GET'
      }, {
        label: 'PUT',
        value: 'PUT'
      }, {
        label: 'DELETE',
        value: 'DELETE'
      }
    ]
    return {
      domainClass: {
        domainId: '',
        domainName: '',
        domainUrl: ''
      },
      areaDialog: false,
      types: '',
      soapMethod: [],
      exeDisable: false,
      isEnableBasic: false,
      restDisable: false,
      reqType: 'soap',
      modes: 'application/json',
      mode: 'xml',
      fileData: '',
      fileDatas: '',
      track: false,
      dialogFormVisible: false,
      dialogEnd: false,
      options: options,
      title: '',
      option: option,
      fileexpand: true,
      executeObj: {},
      queryArg: {
        key: '',
        value: ''
      },
      nameHead: {
        key: '',
        value: ''
      },
      ruleForm: {},
      resFrom: {
        type: 'application/json',
        code: 'UTF-8'
      },
      rules: {
        domainName: [
            { required: true, message: '请选择分组', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
      },
      queryArgData: [],
      nameHeadData: []
    }
  },
  props: {
    row: {
      type: Object,
      default() {
        return {}
      }
    },
    value: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    }
  },
  watch: {
    value(val) {
      if (val) {
        console.log(this.type,'11111')
        this.title = this.row.type === 'flowManager' ? `消息流测试-${this.row.name}` : this.row.type === 'bsManager' ? `业务服务测试-${this.row.name}` : `代理服务测试-${this.row.name}`
        this.dialogFormVisible = val
        this.reqType = this.row.messageType
        if (this.reqType === 'soap') {
          this.resFrom.type = ''
          parseFile(this.row.defineFileInfo.id).then(res => {
            this.types = res.data.parserContent.schemaMap ? 'service' : 'message'
            this.soapMethod = res.data.parserContent.bindingList[0].operation
          })
        }
      }
    },
    'resFrom.type': {
      handler: function(val) {
        console.log(val,'this ,type')
        if (this.reqType === 'soap' && val) {
          const objs = {
            id: this.row.id,
            methods: val,
            types: this.types,
            type: this.type
          }
          methodsWsdl(objs).then(res => {
            this.fileDatas = res
          }).catch(e => {
          })
        }
      }
    }
  },
  
  methods: {
    getArea(data) {
      this.domainClass.domainId = data.id
      this.domainClass.domainName = data.name
      this.domainClass.domainUrl = data.proxyAddress
    },
    choicePDF() {
      this.$refs.filElemPDF.dispatchEvent(new MouseEvent('click'))
    },
    readFile(item) {
      this.resFrom.name = this.$refs.filElemPDF.value
      console.log(this.$refs.filElemPDF.files, this.$refs.filElemPDF.value)
    },
    End() {
      this.dialogEnd = false
    },
    rest() {
      Object.keys(this.$data).forEach(item => {
        if (Array.isArray(this.$data[item]) && !['option', 'options', 'soapMethod'].includes(item)) {
          this.$data[item] = []
        }
        if (Object.prototype.toString.call(this.$data[item]) === '[object Object]') {
          if (item === 'resFrom') {
            this.$data[item] = {
              type: ''
            }
          } else {
            this.$data[item] = {}
          }
        }
        if (Object.prototype.toString.call(this.$data[item]) === '[object String]') {
          if (!['mode', 'modes', 'reqType', 'types'].includes(item)) {
            this.$data[item] = ''
          }
        }
      })
      console.log(this.$data)
      this.resFrom.code='UTF-8'
      this.restDisable = false
    },
    execute() {
      const body =  this.fileDatas
      let arr = {}
      // let reslt = JSON.stringify(arr)
      arr['"content-type"']=this.resFrom.type
      let requestHeaders = arr
      
      let basic = {}
      let queryParam = ''
      // this.nameHeadData.forEach(item => {
      //   requestHeaders[item.key] = item.value 
      // console.log(item.value ,'item.value ')
      // },  )
      // requestHeaders = this.resFrom.type
      this.queryArgData.forEach((item, index) => {
        queryParam += item.key
        queryParam += '='
        queryParam += item.value
        if (index !== this.queryArgData.length - 1) queryParam += '&'
      })
      
      if (this.isEnableBasic) {
        if (this.ruleForm.name && this.ruleForm.password) {
          basic.username = this.ruleForm.name
          basic.password = this.ruleForm.password
        } else {
          this.$message.warning('请输入账号密码')
          this.exeDisable = false
          return
        }
      }

      basic.isEnableBasic = this.isEnableBasic
      if (this.row.connectorType === 'DB') {
        if (!this.domainClass.domainId || this.domainClass.domainId === '') {
          this.$message.warning('请选择分组')
          this.exeDisable = false
          return
        }
        debugExecuteDb({
          id: this.row.id,
          debugeType: this.type,
          serviceId: this.row.id,
          requestBody: body,
          requestHeaders,
          businessDebugeInfoDto: {
            ...this.domainClass,
            projectId: this.row.projectId,
            publishUrl: `${process.env.VUE_APP_HOST_URL}${process.env.VUE_APP_BASE_URL}/soa/proxyService/publish/`
          },
          queryParam,
          ...basic
        }).then(res => {
          this.executeObj = res.data
          if (this.track) {
            debugLog(res.data.debugeId).then(req => {
              this.executeObj.views = req
              this.exeDisable = false
              this.dialogEnd = true
            }).catch(e => {
              this.exeDisable = false
            })
          } else {
            this.exeDisable = false
            this.dialogEnd = true
          }
        }).catch(e => {
          this.exeDisable = false
        })
      } else {
        debugExecute({
          id: this.row.id,
          debugeType: this.type,
          serviceId: this.row.id,
          requestBody: body,
          requestHeaders,
          queryParam,
          ...basic
        }).then(res => {
          this.executeObj = res.data
          if (this.track) {
            debugLog(res.data.debugeId).then(req => {
              this.executeObj.views = req
              this.exeDisable = false
              this.dialogEnd = true
            }).catch(e => {
              this.exeDisable = false
            })
          } else {
            this.exeDisable = false
            this.dialogEnd = true
          }
        }).catch(e => {
          this.exeDisable = false
        })
      }
    },
    addRow(name, names) {
      let vals = 0
      Object.keys(this.$data[names]).forEach((item, index) => {
        if (this.$data[names][item]) {
          vals += index + 1
        }
      })
      if (vals === 3) {
        this.$data[name].push(this.$data[names])
        this.$data[names] = {}
      } else {
        this.$message.warning('请先输入')
      }
    },
    delRow(row, name) {
      this.$data[name].splice(this.$data[name].findIndex(item => item.key === row.key), 1)
    },
    changeCon1(val) {
      this.fileDatas = val
    },
    changeCon(val) {
      this.fileData = val
    },
    closeDialog() {
      this.rest()
      this.dialogFormVisible = false
      this.$emit('confirm', false)
    },
    isShow(c, el) {
      this[el] = !this[el]
      this.slideToggle(c, this[el])
    },
    slideToggle(c, show) {
      const parent = this.$refs[c]
      if (show) {
        parent.style.overflow = 'hidden'
        parent.style.height = 40 + parent.lastElementChild.offsetHeight + 'px'
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          parent.style.overflow = 'visible'
          parent.style.height = 'visible'
        }, 500);
      } else {
        parent.style.overflow = 'hidden'
        parent.style.height = 40 + parent.lastElementChild.offsetHeight + 'px'
        setTimeout(() => {
          parent.style.overflow = 'hidden'
          parent.style.height = '0'
        }, 10)
      }
    }
  }
}
</script>
<style lang="scss">
  .titles{
    margin-top: 12px;
  }
.debug {
  .selectWidth {
    .el-select {
      width: 100%;
    }
  }
  .soapCode {
    .CodeMirror {
      height: 230px;
    }
  }
  .inputDisplay {
    .el-form-item__content {
      display: flex
    }
    .el-button {
      margin-left: 10px;
    }
  }
  .addAlign {
    text-align: center;
  }
}
</style>
