<template>
  <div class="fullheight">
    <el-dialog
      width="80%"
      top="6vh"
      title="服务编排"
      class="sp-manager__dialog"
      :visible="dialogVisible"
      :before-close="beforeCloseDialog"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <el-form
        :model="formData"
        v-form
        data-vv-scope="PortalServiceChoreographyForm"
      >
        <el-row :gutter="0" justify="start" align="top" type="flex">
          <el-col :span="12" style="">
            <ht-form-item label="名称" label-width="120px">
              <ht-input
                v-model="formData.name"
                class="ht"
                placeholder="请输入名称"
                autocomplete="off"
                validate="required"
                :maxlength="50"
                :showWordLimit="true"
              ></ht-input>
            </ht-form-item>
          </el-col>
          <el-col :span="12" style="">
            <ht-form-item label="别名" label-width="120px">
              <ht-input
                v-model="formData.alias"
                class="ht"
                v-pinyin="formData.name"
                placeholder="请输入别名"
                autocomplete="off"
                :validate="{
                  required: true,
                  regex: {
                    exp: '^[a-zA-Z][a-zA-Z0-9_]*$',
                    message: '只能输入字母、数字、下划线，且以字母开头'
                  }
                }"
                :disabled="!!formData.id"
                :maxlength="50"
                :showWordLimit="true"
              ></ht-input>
            </ht-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0" justify="start" align="top" type="flex">
          <el-button
            icon="el-icon-plus"
            size="mini"
            @click="addRows()"
            style="margin-bottom:5px;"
            plain
            >添加</el-button
          >
        </el-row>
        <table class="form-table" cellspacing="0" cellpadding="0" border="0">
          <tbody>
            <tr class="linkageTable-tr">
              <td>接口名称</td>
              <td width="60%">输入参数</td>
              <td width="25%">输出参数</td>
              <td width="5%">操作</td>
            </tr>

            <tr v-for="(column, index) in nodeList" :key="index">
              <td width="190px">
                <ht-select
                  v-model="column.alias"
                  :filterable="true"
                  :options="interfaceList"
                  :props="interfaceProps"
                  @change="interfaceChange(column, column.alias)"
                  :validate="{required: true}"
                  placeholder="请选择接口"
                />
              </td>
              <td>
                    <table cellspacing="0" cellpadding="0" border="0">
                      <tr
                        v-for="(input, index1) in column.params.input"
                        :key="index1"
                      >
                        <td>
                          <ht-input
                            v-model="input.key"
                            class="mt"
                            placeholder="请输入字段"
                            :validate="{required: true}"
                          ></ht-input>
                        </td>
                        <td>
                          <ht-select
                            v-if="index === 0"
                            v-model="input.type"
                            :options="valueList"
                            @change="inputTypeChange(input)"
                            placeholder="请选择值来源"
                            class="bt"
                            :validate="{required: true}"
                          />
                          <ht-select
                            v-else
                            v-model="input.type"
                            :options="value_sourceList_list"
                            @change="inputTypeChange(input)"
                            placeholder="请选择值来源"
                            class="bt"
                            :validate="{required: true}"
                          />
                        </td>
                        <td v-if="input.type == '2'">
                          <ht-input
                            v-model="input.value"
                            class="ht"
                            placeholder="请输入值"
                          ></ht-input>
                        </td>
                        <td v-if="input.type == '3'">
                          <el-button
                            @click="showScriptDialog(input)"
                            type="text"
                            class="typeBtn"
                            >选择脚本
                            <i class="el-icon-search"></i>
                          </el-button>
                          <ht-input
                            type="textarea"
                            v-model="input.value"
                            class="ht"
                            placeholder="请输入值"
                          ></ht-input>
                        </td>
                        <td v-if="input.type == '5' && nodeList.length > 1">
                          <ht-select
                            v-model="input.value"
                            :options="outputList(index)"
                            placeholder="请选择输出参数"
                            class="ht"
                          />
                        </td>
                        <td>
                          <el-button
                            class="btn-padding"
                            style="margin-left:5px;margin-top:5px"
                            icon="el-icon-plus"
                            @click="column.params.input.push({...inputObj})"
                          ></el-button>
                          <el-button
                            class="btn-padding"
                            style="margin-left:5px;margin-top:5px"
                            icon="el-icon-delete"
                            @click="column.params.input.remove(input)"
                          ></el-button>
                        </td>
                      </tr>
                    </table>
              </td>
              <td>
                    <table cellspacing="0" cellpadding="0" border="0">
                      <tr
                        v-for="(output, index2) in column.params.output"
                        :key="index2"
                      >
                        <td>
                          <ht-input
                            v-model="output.key"
                            class="ht"
                            placeholder="请输入字段"
                          ></ht-input>
                        </td>
                        <td width="80px">
                          <el-button
                            class="btn-padding"
                            style="margin-left:5px;margin-top:5px"
                            icon="el-icon-plus"
                            @click="column.params.output.push({...outputObj})"
                          ></el-button>
                          <el-button
                            class="btn-padding"
                            style="margin-left:5px;margin-top:5px"
                            icon="el-icon-delete"
                            @click="column.params.output.remove(output)"
                          ></el-button>
                        </td>
                      </tr>
                    </table>
              </td>
              <td width="60px" style="text-align: center;">
                <el-button
                  icon="el-icon-delete"
                  class="btn-padding"
                  @click="nodeList.remove(column)"
                ></el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </el-form>
      <div slot="footer" style="text-align: right">
        <el-button @click="beforeCloseDialog">{{
          $t('eip.common.cancel')
        }}</el-button>
        <el-button type="primary" @click="saveData">{{
          $t('eip.common.save')
        }}</el-button>
      </div>
      <!-- 脚本选择对话框 -->
      <eip-script-dialog
        :appendToBody="true"
        ref="eipScriptDialog"
        @onConfirm="handleScriptSelected"
      ></eip-script-dialog>
    </el-dialog>
  </div>
</template>
<script>
import req from '@/request.js'
const EipScriptDialog = () => import('@/components/dialog/EipScriptDialog.vue')
export default {
  components: {
    EipScriptDialog
  },
  data() {
    return {
      dialogVisible: false,
      interfaceProps: {key: 'alias', value: 'name'},
      formData: {
        name: '',
        alias: '',
        flowDataJson: ''
      },
      valueList: [
        {value: '固定值', key: '2'},
        {value: '脚本', key: '3'},
        {value: '参数传入', key: '4'}
      ],
      value_sourceList_list: [
        {value: '固定值', key: '2'},
        {value: '脚本', key: '3'},
        {value: '参数传入', key: '4'},
        {value: '上个接口', key: '5'}
      ], //值来源数组_列表
      inputObj: {
        key: '',
        type: '',
        value: ''
      },
      outputObj: {
        outputKey: ''
      },
      interfaceManage: {},
      interfaceList: [],
      nodeList: [],
      editConditionRow: {},
      saveMethod: 'POST'
    }
  },
  mounted() {
    this.loadInterfaceList()
    this.$validator = this.$root.$validator
  },
  methods: {
    outputList(index) {
      if (index === 0) {
        return []
      }
      let result = JSON.parse(
        JSON.stringify(this.nodeList[index - 1].params.output)
      )
      return result
    },
    loadInterfaceList() {
      req
        .get(
          window.context.portal + '/portal/portalInterfaceManager/v1/getList'
        )
        .then(resp => {
          this.interfaceList = resp.data
        })
    },
    interfaceChange(row, change) {
      let _this = this
      row.params.input = []
      row.params.output = []
      if (change && change != '') {
        req
          .get(
            window.context.portal +
              '/portal/portalInterfaceManager/v1/getDetailByAlias?alias=' +
              change
          )
          .then(resp => {
            if (resp.data) {
              let data = resp.data
              let conditionfield = []
              let resultfield = []
              let showOut = true
              if (data.connectionType == 'dataSource') {
                let detail = data.dbDetail
                conditionfield = JSON.parse(detail.conditionfield)
                resultfield = JSON.parse(detail.resultfield)
                //暂时去掉自定义sql输出参数设置
                if (detail.type == 'custom') {
                  showOut = false
                }
              } else if (data.connectionType == 'restful') {
                let detail = data.restfulDetail
                conditionfield = JSON.parse(detail.conditionfield)
                resultfield = JSON.parse(detail.resultfield)
              }
              if (conditionfield && conditionfield.length > 0) {
                for (let i = 0; i < conditionfield.length; i++) {
                  let item = conditionfield[i]
                  let input = {}
                  input.key = item.field
                  input.type = item.defaultType
                  input.value = item.defaultValue
                  row.params.input.push(input)
                }
              } else {
                row.params.input.push({...this.inputObj})
              }
              if (resultfield && resultfield.length > 0) {
                for (let i = 0; i < resultfield.length; i++) {
                  let item = resultfield[i]
                  let output = {}
                  output.key = item.field
                  row.params.output.push(output)
                }
              } else {
                if (showOut) {
                  row.params.output.push({...this.outputObj})
                }
              }
            } else {
              row.params.input.push({...this.inputObj})
              row.params.output.push({...this.outputObj})
            }
          })
      }
    },
    inputTypeChange(row) {
      row.value = ''
    },
    showDialog(id) {
      if (id) {
        this.$http
          .get('${portal}/portal/portalServiceChoreography/v1/' + id)
          .then(resp => {
            this.formData = resp.data
            let flowData = JSON.parse(resp.data.flowDataJson)
            this.nodeList = flowData.nodeList
            this.dialogVisible = true
          })
      } else {
        this.formData = {
          name: '',
          alias: '',
          flowDataJson: ''
        }
        this.dialogVisible = true
      }
    },
    saveData() {
      let _this = this
      this.$validator
        .validateAll('PortalServiceChoreographyForm')
        .then(result => {
          if (result) {
            //处理表单数据
            let formData = JSON.parse(JSON.stringify(this.formData))
            let flowDataJson = this.handleFormData()
            formData.flowDataJson = flowDataJson
            req
              .post(
                '${portal}/portal/portalServiceChoreography/v1/save',
                formData
              )
              .then(resp => {
                if (resp.data.state) {
                  this.$message({
                    type: 'success',
                    message: resp.data.message
                  })
                  this.$emit('reloadList', '')
                  this.beforeCloseDialog()
                }
              })
          } else {
            let arr = this.$validator.errors.items.filter(
              item => item.scope == 'PortalServiceChoreographyForm'
            )
            let errorLength = arr.length
            this.$message({
              showClose: true,
              message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
              type: 'warning'
            })
          }
        })
    },
    handleFormData() {
      let data = {
        name: this.formData.name,
        nodeList: this.nodeList
      }
      let lineList = []
      let nodeList = this.nodeList
      if (nodeList.length > 1) {
        for (let i = 1; i < nodeList.length; i++) {
          let item1 = nodeList[i - 1]
          let item2 = nodeList[i]
          let obj = {}
          obj.from = item1.id
          obj.to = item2.id
          lineList.push(obj)
        }
      }
      data.lineList = lineList
      return JSON.stringify(data)
    },
    beforeCloseDialog() {
      this.nodeList = []
      this.formData = {
        name: '',
        alias: '',
        flowDataJson: ''
      }
      this.dialogVisible = false
    },
    afterSaveData() {
      setTimeout(() => {
        this.$emit('reloadList', '')
        this.beforeCloseDialog()
      }, 500)
    },
    addRows() {
      if (this.formData.name == '') {
        this.$message.warning('请先输入名称！')
        return
      }
      let index = this.nodeList.length + 1
      let height = 100 * index
      let item = {
        id: 'node' + index,
        name: this.formData.name + '-节点' + index,
        type: 'task',
        left: height + 'px',
        top: '160px',
        ico: 'el-icon-user-solid',
        alias: '',
        params: {
          input: [],
          output: []
        }
      }
      this.nodeList.push(item)
    },
    handleScriptSelected(script, name) {
      this.editConditionRow.value = this.editConditionRow.value + script
      //强制刷新
      this.$forceUpdate()
    },
    showScriptDialog(row) {
      this.$refs.eipScriptDialog.showDialog()
      this.editConditionRow = row
    }
  }
}
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
}
.mt {
  margin-left: 20px;
  margin-top: 5px;
}
.ht {
  margin-top: 5px;
  margin-left: 20px;
}
.bt {
  margin-top: 5px;
  margin-left: 20px;
  width: 220px !important;
}
.inline-left {
  width: 75%;
  float: left;
  text-align: center;
}
.inline-right {
  width: 25%;
  float: right;
  text-align: center;
}
.typeBtn {
  float: left;
  margin-top: 10px;
  margin-left: 20px;
}

.btn-padding {
  padding: 5px;
}
.linkageTable-tr td {
  text-align: center;
}
</style>
