<template>
  <div>
    <el-card class="box-card" shadow="always">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
        <el-button-group style="float: right;">
          <el-button size="mini" icon="el-icon-plus" round @click="submitForm" :loading="loadingOptions.loading" :disabled="loadingOptions.isDisabled">{{loadingOptions.loadingText}}</el-button>
          <el-button size="mini" icon="el-icon-back" round @click="showCard">返回</el-button>
        </el-button-group>
      </div>
      <div :style="classCardbody">
        <el-steps :active="active" finish-status="success" align-center>
          <el-step title="属性配置"></el-step>
          <el-step title="执行配置"></el-step>
          <el-step title="参数配置"></el-step>
        </el-steps>
        <el-form ref="form1" :model="form1" :rules="rules1" label-width="80px" v-if="active == 1">
          <el-form-item label="API名称" prop="apiName">
            <el-input v-model="form1.apiName" placeholder="请输入API名称" />
          </el-form-item>
          <el-form-item label="API版本" prop="apiVersion">
            <el-input v-model="form1.apiVersion" placeholder="请输入API版本" />
          </el-form-item>
          <el-form-item label="API路径" prop="apiUrl">
            <el-input v-model="form1.apiUrl" placeholder="请输入API路径" />
          </el-form-item>
          <el-form-item label="请求方式" prop="reqMethod">
            <el-select v-model="form1.reqMethod" placeholder="请选择请求方式">
              <el-option
                v-for="dict in reqMethodOptions"
                :key="dict.id"
                :label="dict.itemValue"
                :value="dict.itemText"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="返回格式" prop="resType">
            <el-select v-model="form1.resType" placeholder="请选择返回格式">
              <el-option
                v-for="dict in resTypeOptions"
                :key="dict.id"
                :label="dict.itemValue"
                :value="dict.itemText"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="IP黑名单" prop="deny">
            <el-input v-model="form1.deny" type="textarea" placeholder="请输入IP黑名单多个用，隔开" />
          </el-form-item>
          <el-form-item label="是否限流" prop="rateLimit">
            <el-radio-group v-model="form1.rateLimit">
              <el-radio
                v-for="dict in rateLimitOptions"
                :key="dict.id"
                :label="dict.itemText"
              >{{dict.itemValue}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请求次数" prop="times" v-if="form1.rateLimit === '1'">
            <el-input-number v-model="form1.times" controls-position="right" :min="1" />
          </el-form-item>
          <el-form-item label="请求时间范围" prop="seconds" v-if="form1.rateLimit === '1'">
            <el-input-number v-model="form1.seconds" controls-position="right" :min="1"/>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form1.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.id"
                :label="dict.itemText"
              >{{dict.itemValue}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form1.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <el-form ref="form2" :model="form2" :rules="rules2" label-width="80px" v-if="active == 2">
          <el-form-item label="数据源" prop="sourceId">
            <el-select v-model="form2.sourceId" placeholder="请选择数据源">
              <el-option
                v-for="source in sourceOptions"
                :key="source.id"
                :label="source.sourceName"
                :value="source.id"
                :disabled="source.status === '0'"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配置方式" prop="configType">
            <el-select v-model="form2.configType" placeholder="请选择配置方式">
              <el-option
                v-for="dict in configTypeOptions"
                :key="dict.id"
                :label="dict.itemValue"
                :value="dict.itemText"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form ref="form3" :model="form3" :rules="rules3" label-width="80px" v-if="active == 3">
        </el-form>
        <el-button style="margin-top: 12px;" @click="handleNextStep" v-if="active < 3">下一步</el-button>
        <el-button style="margin-top: 12px;" @click="handleLastStep" v-if="active > 1">上一步</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { addDataSet } from '@/api/factory/dataset'
import { listDataSource, queryByPage } from '@/api/factory/datasource'
import sqlFormatter from 'sql-formatter'
import SqlEditor from '@/components/SqlEditor'

export default {
  name: 'DataApiAdd',
  components: {
    SqlEditor
  },
  props: {
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      classCardbody: {
        overflow: 'auto',
        height: document.body.offsetHeight - 240 + 'px'
      },
      title: '数据集新增',
      // 展示切换
      showOptions: {
        data: {},
        showList: true,
        showAdd: false,
        showEdit: false,
        showDetail: false
      },
      // 保存按钮
      loadingOptions: {
        loading: false,
        loadingText: '保存',
        isDisabled: false
      },
      active: 1,
      // 表单参数
      form1: {
        id: undefined,
        apiName: undefined,
        apiVersion: undefined,
        apiUrl: undefined,
        reqMethod: undefined,
        resType: undefined,
        deny: undefined,
        rateLimit: '1',
        times: 5,
        seconds: 60,
        status: '1',
        remark: undefined,
        executeConfig: {},
        reqParams: [],
        resParams: []
      },
      // 表单校验
      rules1: {
        apiName: [
          { required: true, message: 'API名称不能为空', trigger: 'blur' }
        ],
        apiVersion: [
          { required: true, message: 'API版本不能为空', trigger: 'blur' }
        ],
        apiUrl: [
          { required: true, message: 'API路径不能为空', trigger: 'blur' }
        ],
        reqMethod: [
          { required: true, message: '请求方式不能为空', trigger: 'blur' }
        ],
        resType: [
          { required: true, message: '返回格式不能为空', trigger: 'blur' }
        ]
      },
      form2: {
        sourceId: undefined,
        configType: undefined
      },
      rules2: {},
      form3: {},
      rules3: {},
      // 请求方式数据字典
      reqMethodOptions: [],
      // 返回格式数据字典
      resTypeOptions: [],
      // 是否限流数据字典
      rateLimitOptions: [],
      // 状态数据字典
      statusOptions: [],
      // 数据源数据字典
      sourceOptions: [],
      // 配置方式数据字典
      configTypeOptions: []
    }
  },
  created () {
    this.getDicts('data_req_method').then(response => {
      if (response.success) {
        this.reqMethodOptions = response.data
      }
    })
    this.getDicts('data_res_type').then(response => {
      if (response.success) {
        this.resTypeOptions = response.data
      }
    })
    this.getDicts('sys_yes_no').then(response => {
      if (response.success) {
        this.rateLimitOptions = response.data
      }
    })
    this.getDicts('sys_common_status').then(response => {
      if (response.success) {
        this.statusOptions = response.data
      }
    })
    this.getDataSourceList()
    this.getDicts('data_config_type').then(response => {
      if (response.success) {
        this.configTypeOptions = response.data
      }
    })
  },
  methods: {
    showCard () {
      this.$emit('showCard', this.showOptions)
    },
    getDataSourceList () {
      listDataSource().then(response => {
        if (response.success) {
          this.sourceOptions = response.data
        }
      })
    },
    /** 步骤条下一步 */
    handleNextStep () {
      if (this.active === 1) {
        this.$refs['form1'].validate(valid => {
          if (valid) {
            this.active++
          }
        })
      } else if (this.active === 2) {
        this.$refs['form2'].validate(valid => {
          if (valid) {
            this.active++
          }
        })
      }
    },
    /** 步骤条上一步 */
    handleLastStep () {
      this.active--
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form3'].validate(valid => {
        if (valid) {
          this.loadingOptions.loading = true
          this.loadingOptions.loadingText = '保存中...'
          this.loadingOptions.isDisabled = true
          addDataSet(this.form).then(response => {
            if (response.success) {
              this.$message.success('保存成功')
              setTimeout(() => {
                // 2秒后跳转列表页
                this.$emit('showCard', this.showOptions)
              }, 2000)
            } else {
              this.$message.error('保存失败')
              this.loadingOptions.loading = false
              this.loadingOptions.loadingText = '保存'
              this.loadingOptions.isDisabled = false
            }
          }).catch(error => {
            this.$message.error(error.data.msg || '保存失败')
            this.loadingOptions.loading = false
            this.loadingOptions.loadingText = '保存'
            this.loadingOptions.isDisabled = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
