<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入接口名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:apiConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:apiConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:apiConfig:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="apiConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="接口路由" align="center" prop="routePath" width="150" />
      <el-table-column label="接口名称" align="center" prop="name" width="200"/>
      <el-table-column label="返回类型" align="center" prop="returnDataType" width="150">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_api_data_type" :value="scope.row.returnDataType"/>
        </template>
      </el-table-column>
      <el-table-column label="SQL脚本" align="center" prop="sqlStr" />
      <el-table-column label="参数示例" align="center" prop="paramExample" />
      <el-table-column label="创建人" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDebug(scope.row)"
            v-hasPermi="['system:apiConfig:edit']"
          >测试</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:apiConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:apiConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 接口测试 -->
    <el-dialog :title="debugTitle" :visible.sync="debugOpen" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="debugForm" label-width="120px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="接口地址：">/v1/api/common/{{ debugForm.routePath }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求类型：">POST</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="返回类型：">
                <dict-tag :options="dict.type.sys_api_data_type" :value="debugForm.returnDataType"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="SQL脚本：">{{ debugForm.sqlStr }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="paramExample" label="请求参数：">
              <el-input v-model="debugForm.paramExample" type="textarea" placeholder="请输入内容" rows="5"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="result" label="执行结果：">
              <el-input v-model="debugForm.result" type="textarea" placeholder="" rows="5" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDebug">执 行</el-button>
        <el-button @click="debugOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改接口配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item prop="routePath">
          <span slot="label">
            <el-tooltip content="接口路由不能有“/”" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            接口路由
          </span>
          <el-input v-model="form.routePath" placeholder="请输入接口路由" maxlength="120"/>
        </el-form-item>
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入接口名称" maxlength="120"/>
        </el-form-item>
        <el-form-item label="返回类型" prop="returnDataType">
          <el-select v-model="form.returnDataType" placeholder="请选择返回类型">
            <el-option
              v-for="dict in dict.type.sys_api_data_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SQL脚本" prop="sqlStr">
          <span slot="label">
            <el-tooltip content="SQL中如果有动态参数，需用'@参数名'进行占位，字符或时间等类型参数需在SQL脚本中写全单引号。如：select * from sys_user where user_name = '@userName'" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            SQL脚本
          </span>
          <el-input v-model="form.sqlStr" type="textarea" placeholder="请输入内容" rows="8" />
        </el-form-item>
        <el-form-item prop="paramExample">
          <span slot="label">
            <el-tooltip content='返回结果为List类型，如需分页前端传参时需加上：{"page":1,"pageSize":10}' placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            参数示例
          </span>
          <el-input v-model="form.paramExample" type="textarea" placeholder="请输入参数" rows="5"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApiConfig, getApiConfig, delApiConfig, addApiConfig, updateApiConfig, exportApiConfig ,apiDebug} from "@/api/system/apiConfig";

export default {
  name: "ApiConfig",
  dicts: ['sys_api_data_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 接口配置表格数据
      apiConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      debugTitle: "",
      debugOpen: false,
      debugForm: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        routePath: [
          { required: true, message: "接口路由不能为空", trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]+$/,
            message: "路由只能是a-z,A-Z或0-9组成",
            trigger: "blur"
          }
        ],
        name: [
          { required: true, message: "接口名称不能为空", trigger: "blur" }
        ],
        returnDataType: [
          { required: true, message: "返回类型不能为空", trigger: "change" }
        ],
        sqlStr: [
          { required: true, message: "SQL脚本不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询接口配置列表 */
    getList() {
      this.loading = true;
      listApiConfig(this.queryParams).then(response => {
        this.apiConfigList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        routePath: null,
        name: null,
        returnDataType: null,
        sqlStr: null,
        paramExample: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApiConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改接口";
      });
    },
    /** 对接口进行测试*/
    handleDebug(row){
      this.debugOpen = true;
      this.debugTitle = row.name;
      this.debugForm = row
    },
    /** 执行接口*/
    submitDebug(){
      apiDebug(this.debugForm.routePath, this.debugForm.paramExample).then(res =>{
        this.$modal.msgSuccess("执行成功");
        this.debugForm.result = JSON.stringify(res, null, 4)
        this.$forceUpdate()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApiConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApiConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delApiConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有接口数据项？').then(() => {
        this.exportLoading = true;
        return exportApiConfig(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
