<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <catalogue-tree
          @callback="catalogueCallBack"
          catalogueType="integration"
        />
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          :class="showSearch ? '' : ' hide'"
          label-width="68px"
        >
          <el-form-item label="服务名称" prop="serviceName">
            <el-input
              v-model="queryParams.serviceName"
              placeholder="请输入服务名称"
              clearable
              @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/integration:service:add']"
              >新增</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="serviceList">
          <el-table-column label="编号" align="center" prop="id" width="80" />
          <el-table-column label="服务名称" prop="serviceName" />
          <el-table-column
            label="请求方法"
            align="center"
            prop="requestMethod"
            width="100"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_request_method"
                :value="scope.row.requestMethod"
              />
            </template>
          </el-table-column>
          <el-table-column label="标签" align="center" prop="tag" />
          <el-table-column
            label="服务地址"
            prop="serviceUrl"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system/integration:service:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system/integration:service:remove']"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-setting"
                @click="handleUpdate(scope.row, 1)"
                v-hasPermi="['system/integration:service:edit']"
                >调试</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-col>
    </el-row>

    <!-- 添加或修改整合服务对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      top="7vh"
      width="1200px"
      append-to-body
      class="service-dialog"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="服务目录" prop="catalogueId">
              <treeselect
                v-model="form.catalogueId"
                :options="treeList"
                :show-count="true"
                placeholder="请选择目录"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input
                v-model="form.serviceName"
                placeholder="请输入服务名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="服务地址" prop="serviceUrl">
              <el-input
                v-model="form.serviceUrl"
                placeholder="请输入服务地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="信息标识符" prop="infoId">
              <el-input v-model="form.infoId" placeholder="请输入信息标识符" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提供机构" prop="provideOrganization">
              <el-select
                v-model="form.provideOrganization"
                placeholder="请选择提供机构"
                filterable
              >
                <el-option
                  v-for="dict in dict.type.sys_provide_organization"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标签" prop="tag">
              <el-select
                v-model="form.tag"
                placeholder="请选择"
                multiple
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(tag, i) in tagList"
                  :label="tag.tagName"
                  :value="tag.tagName"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px">
          <el-col :span="24">
            <h3><b>服务请求</b></h3>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="鉴权" prop="needAuth">
              <el-checkbox
                label="需要鉴权"
                v-model="form.needAuth"
              ></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="鉴权方式" prop="authWay" v-if="form.needAuth">
              <el-select v-model="form.authWay" placeholder="请选择鉴权方式">
                <el-option
                  v-for="dict in dict.type.sys_auth_way"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="请求方法" prop="requestMethod">
              <el-select
                v-model="form.requestMethod"
                placeholder="请选择请求方法"
              >
                <el-option
                  v-for="dict in dict.type.sys_request_method"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数形式" prop="paramForm">
              <el-select v-model="form.paramForm" placeholder="请选择参数形式">
                <el-option
                  v-for="dict in dict.type.sys_param_form"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="响应格式" prop="responseForm">
              <el-select
                v-model="form.responseForm"
                placeholder="请选择响应格式"
              >
                <el-option
                  v-for="dict in dict.type.sys_response_form"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.responseForm === 'standard'">
          <el-col :span="24">
            <el-form-item label="数据过滤" prop="filterJson">
              <el-input
                v-model="form.filterJson"
                type="textarea"
                placeholder="服务固定查询参数(search字段)，用户使用该服务查询时，会固定拼接这里填写的JSON格式"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row style="margin: 20px 0 10px 0">
        <el-col :span="12">
          <h3 style="margin: 0"><b>参数配置</b></h3>
        </el-col>
        <el-col :span="12" style="display: flex; justify-content: flex-end">
          <el-button type="primary" size="mini" @click="handleItemAdd(null)"
            >新增</el-button
          >
          <el-button type="default" size="mini" @click="handleDebug(1)"
            >调试</el-button
          >
          <el-button
            type="success"
            size="mini"
            @click="handleDebug(0)"
            v-if="form.responseForm === 'standard'"
            >获取出参</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="tableData" height="350">
        <el-table-column label="编号" align="center" width="120" prop="id" />
        <el-table-column
          label="参数类型"
          align="center"
          prop="paramType"
          width="120"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.isEdit === 1">
              <el-select
                v-model="scope.row.paramType"
                placeholder="请选择"
                size="mini"
              >
                <el-option label="入参" value="in"></el-option>
                <el-option label="出参" value="out"></el-option>
              </el-select>
            </template>
            <template v-else>
              <el-tag v-if="scope.row.paramType === 'in'">入参</el-tag>
              <el-tag type="success" v-if="scope.row.paramType === 'out'"
                >出参</el-tag
              >
            </template>
          </template>
        </el-table-column>
        <el-table-column label="参数名" align="center" prop="paramName">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.paramName"
              placeholder="必须唯一"
              v-if="scope.row.isEdit"
              size="mini"
            />
            <span v-else>{{ scope.row.paramName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="参数中文名" align="center" prop="paramComment">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.paramComment"
              placeholder="请输入参数中文"
              v-if="scope.row.isEdit"
              size="mini"
            />
            <span v-else>{{ scope.row.paramComment }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          label="缓存映射字段"
          prop="mapColumnName"
          v-if="form.responseForm === 'standard'"
        >
          <template slot="header">
            缓存映射字段
            <el-tooltip
              content="服务数据缓存时，该参数必填，为缓存到本地数据表的表列名，名称必须符合表列名命名规范，且不能变更"
              placement="bottom"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.mapColumnName"
              placeholder="必须是英文、数字、下划线"
              v-if="scope.row.isEdit && scope.row.paramType === 'out'"
              size="mini"
            />
            <span v-if="!scope.row.isEdit && scope.row.paramType === 'out'">{{
              scope.row.mapColumnName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="数据类型"
          align="center"
          prop="dataType"
          width="150"
        >
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.dataType"
              placeholder="请选择"
              size="mini"
              v-if="scope.row.isEdit === 1"
              filterable
            >
              <el-option
                v-for="dict in dict.type.sys_data_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <span v-else>{{ scope.row.dataType }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="是否必需"
          align="center"
          prop="isRequired"
          width="80"
        >
          <template slot-scope="scope">
            <!-- <el-select
              v-model="scope.row.isRequired"
              placeholder="请选择"
              v-if="scope.row.isEdit === 1"
              size="mini"
            >
              <el-option
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <template v-if="scope.row.paramType === 'in'">
              <el-checkbox
                label=""
                v-model="scope.row.isRequired"
                v-if="scope.row.isEdit === 1"
              ></el-checkbox>
              <span v-else>{{
                scope.row.isRequired === "Y" || scope.row.isRequired === true
                  ? "是"
                  : "否"
              }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              placeholder="备注"
              v-if="scope.row.isEdit === 1"
              size="mini"
            />
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              v-if="!scope.row.isEdit"
              @click="handleItemUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="mini"
              v-if="scope.row.isEdit"
              @click="handleItemSave(scope.row)"
              >确定</el-button
            >
            <el-button
              type="text"
              size="mini"
              @click="handleItemRemove(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 接口调试/获取出参 -->
    <el-dialog
      :title="debugTitle"
      :visible.sync="debugFlag"
      top="7vh"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-alert
        type="info"
        title="通过调用接口，解析接口返回标准数据格式，自动填充出参，要求接口必须是标准格式，且调用接口成功"
        :closable="false"
        style="margin-bottom: 20px"
        v-if="!isDebug"
      ></el-alert>
      <el-form ref="debugForm" :model="debugForm" label-width="80px">
        <el-form-item label="请求地址:"> {{ form.serviceUrl }} </el-form-item>
        <el-form-item label="鉴权方式:"
          ><dict-tag :options="dict.type.sys_auth_way" :value="form.authWay"
        /></el-form-item>
        <el-form-item label="请求方法:">{{ form.requestMethod }}</el-form-item>
        <el-form-item label="参数形式:">{{ form.paramForm }}</el-form-item>
        <el-form-item label="必要入参">
          <el-input
            type="textarea"
            placeholder="请根据接口规范填入必要入参（JSON格式），无必要入参可不填"
            v-model="debugForm.requestParam"
            rows="10"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="接口返回"
          v-if="isDebug && debugForm.debugResponse"
        >
          <!-- <el-input
            v-model="debugForm.debugResponse"
            placeholder=""
            type="textarea"
            rows="10"
          ></el-input> -->
          <LocalJsonViewer
            :value="debugForm.debugResponse"
            v-if="debugForm.debugResponse"
          ></LocalJsonViewer>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDebug" :loading="debugLoading"
          >提 交</el-button
        >
        <el-button @click="cancelDebug">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listService,
  getService,
  delService,
  addService,
  updateService,
  getServiceItem,
  debugService,
} from "@/api/system/integration/service";
import { listTag } from "@/api/system/base/tag";
import { listCatalogue } from "@/api/system/integration/catalogue";
import CatalogueTree from "@/components/CatalogueTree";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { validURL } from "@/utils/validate";
import LocalJsonViewer from "@/components/LocalJsonViewer";
import "vue-json-viewer/style.css";

import { arrayToJson } from "@/utils/dxp";

export default {
  name: "Service",
  dicts: [
    "sys_param_form",
    "sys_provide_organization",
    "sys_auth_way",
    "sys_request_method",
    "sys_data_type",
    "sys_yes_no",
    "sys_response_form",
  ],
  components: { CatalogueTree, Treeselect, LocalJsonViewer },
  data() {
    const validateJSON = (rule, value, callback) => {
      if (value) {
        try {
          JSON.parse(value);
          callback();
        } catch(e) {
          callback("请输入正确的JSON");
        }
      }
      callback();
    };
    return {
      // 遮罩层
      loading: true,
      submitting: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 整合服务表格数据
      serviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标志时间范围
      daterangeCreateTime: [],
      // 删除标志时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        catalogueId: null,
        serviceName: null,
        serviceUrl: null,
        needAuth: null,
        authWay: null,
        requestMethod: null,
        paramForm: null,
        infoId: null,
        tag: null,
        provideOrganization: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateTime: null,
      },
      // 目录树
      treeList: [],
      // 标签
      tagList: [],
      // 表单参数
      form: {
        requestMethod: "POST",
      },
      // 表单校验
      rules: {
        catalogueId: [
          { required: true, message: "目录不能为空", trigger: "change" },
        ],
        serviceName: [
          { required: true, message: "服务名称不能为空", trigger: "change" },
        ],
        serviceUrl: [
          { required: true, message: "服务地址不能为空", trigger: "change" },
          // { validator: validateUrl, trigger: "change" },
        ],
        filterJson: [{ validator: validateJSON, trigger: "change" }],
        needAuth: [
          {
            required: true,
            message: "是否需要授权不能为空",
            trigger: "change",
          },
        ],
        authWay: [
          {
            required: true,
            message: "请选择鉴权方式",
            trigger: "change",
          },
        ],
        requestMethod: [
          {
            required: true,
            message: "请选择请求方法",
            trigger: "change",
          },
        ],
        paramForm: [
          {
            required: true,
            message: "请选择参数形式",
            trigger: "change",
          },
        ],
        responseForm: [
          {
            required: true,
            message: "请选择返回格式",
            trigger: "change",
          },
        ],
      },
      tableData: [], // 参数树
      debugFlag: false,
      isDebug: null, // 是否调试模式
      debugForm: {},
      debugTitle: null,
      debugLoading: false,
    };
  },
  created() {
    this.getCatalogueList();
    this.getTagList();
    this.getList();
  },
  methods: {
    catalogueCallBack(data) {
      this.queryParams.catalogueId = data.id;
      this.handleQuery();
    },
    /** 查询目录列表 */
    getCatalogueList() {
      listCatalogue({
        pageNum: 1,
        pageSize: 100000,
        catalogueType: "integration",
      }).then((response) => {
        let treeList = [];
        if (response.rows && response.rows.length > 0) {
          response.rows.forEach((p) => {
            treeList.push({
              id: p.id,
              parentId: p.parentId,
              label: p.catalogueName,
              children: [],
            });
          });
        }
        this.treeList = this.handleTree(treeList);
      });
    },
    getTagList() {
      listTag({}).then((response) => {
        this.tagList = response.rows;
      });
    },
    /** 查询整合服务列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && "" != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] =
          this.daterangeCreateTime[0] + " 00:00:00";
        this.queryParams.params["endCreateTime"] =
          this.daterangeCreateTime[1] + " 23:59:59";
      }
      if (null != this.daterangeUpdateTime && "" != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] =
          this.daterangeUpdateTime[0] + " 00:00:00";
        this.queryParams.params["endUpdateTime"] =
          this.daterangeUpdateTime[1] + " 23:59:59";
      }
      listService(this.queryParams).then((response) => {
        this.serviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.debugFlag = false;
      this.reset();
    },
    cancelDebug() {
      this.debugFlag = false;
      this.debugForm = {
        requestParam: null,
        debugResponse: null,
      };
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        catalogueId: null,
        serviceName: null,
        serviceUrl: null,
        needAuth: null,
        authWay: null,
        requestMethod: null,
        paramForm: null,
        infoId: null,
        tag: null,
        provideOrganization: null,
        status: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
      this.tableData = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      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();

      const form = JSON.parse(JSON.stringify(this.form));

      // 默认值
      form.requestMethod = "POST";
      form.paramForm = "Body";
      form.needAuth = true;
      form.responseForm = "standard";

      this.form = form;

      this.open = true;
      this.title = "添加整合服务";
    },
    /** 修改按钮操作 */
    handleUpdate(row, showDebug) {
      this.reset();
      const id = row.id || this.ids;
      getService(id).then((response) => {
        if (response.data) {
          if (response.data.needAuth === "Y") {
            response.data.needAuth = true;
          }
        }
        this.form = response.data;
        if (this.form.tag && this.form.tag.length > 0) {
          this.form.tag = this.form.tag.split(",");
        }

        // 获取参数明细
        getServiceItem(id).then((res) => {
          if (res.data) {
            res.data.forEach((p) => {
              if (p.isRequired === "Y") {
                p.isRequired = true;
              }
            });
          }

          this.tableData = res.data;
          if (showDebug) {
            this.handleDebug(1);
          } else {
            this.open = true;
            this.title = "修改整合服务";
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 检查参数
          if (!this.tableData || this.tableData.length === 0) {
            this.$modal.msgError("请添加参数");
            return;
          }

          // console.log(this.tableData);

          const repeat = [];
          for (let i = 0; i < this.tableData.length; i++) {
            const p = this.tableData[i];
            if (!this.validateRow(p)) {
              return;
            }

            if (repeat && repeat.indexOf(p.paramName) >= 0) {
              this.$modal.msgError(`id=${p.id}参数名重复`);
              return;
            } else {
              repeat.push(p.paramName);
            }
          }

          const serviceItems = JSON.parse(JSON.stringify(this.tableData));
          // console.log(serviceItems)
          serviceItems.forEach((p, i) => {
            if (p.isRequired) {
              p.isRequired = "Y";
            }
            if (!p.sort) {
              p.sort = i;
            }
            // console.log(p.id);
            if (!p.createBy) {
              delete p.id;
            }

            delete p.isEdit;
          });
          const form = JSON.parse(JSON.stringify(this.form));
          if (form.tag) {
            form.tag = form.tag.join(",");
          }
          if (form.needAuth) {
            form.needAuth = "Y";
          }
          form.serviceItems = serviceItems;
          this.submitting = true;
          if (form.id != null) {
            updateService(form)
              .then((response) => {
                this.submitting = false;
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {
                this.submitting = false;
              });
          } else {
            addService(form)
              .then((response) => {
                this.submitting = false;
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {
                this.submitting = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除整合服务编号为"' + ids + '"的数据项？')
        .then(function () {
          return delService(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/integration/service/export",
        {
          ...this.queryParams,
        },
        `service_${new Date().getTime()}.xlsx`
      );
    },
    handleItemAdd() {
      // let maxId = 0;
      // if (this.tableData && this.tableData.length > 0) {
      //   maxId = Math.max.apply(
      //     null,
      //     this.tableData.map((i) => i.id)
      //   );
      // }

      this.tableData.push({
        id: "tmp_" + Math.ceil(Math.random() * 100000),
        paramType: null,
        paramName: null,
        dataType: null,
        isRequired: null,
        remark: null,
        isEdit: 1,
      });
    },
    handleItemUpdate(row) {
      const tableData = JSON.parse(JSON.stringify(this.tableData));
      tableData.forEach((p) => {
        if (p.id === row.id) {
          p.isEdit = 1;
        }
      });

      this.tableData = tableData;
    },
    handleItemRemove(row) {
      this.tableData = this.tableData.filter((p) => p.id !== row.id);
    },
    handleItemSave(row) {
      if (this.validateRow(row)) {
        row.isEdit = 0;
      }
    },
    validateRow(row) {
      // 参数校验
      if (!row.paramType) {
        this.$modal.msgError(`id=${row.id}请选择参数类型`);
        return false;
      }

      if (!row.paramName) {
        this.$modal.msgError(`id=${row.id}请填写参数名`);
        return false;
      }

      // if (row.paramType === "out" && this.form.responseForm === "standard") {
      //   console.log(row.mapColumnName);
      //   if (!row.mapColumnName || row.mapColumnName.length === 0) {
      //     this.$modal.msgError(`id=${row.id}请填写缓存映射表字段名`);
      //     return false;
      //   }

      //   // 校验只能是英文，数字，下划线
      //   const reg = /^[a-z0-9_]*$/g;
      //   if (!reg.test(row.mapColumnName)) {
      //     this.$modal.msgError(
      //       `id=${row.id}缓存映射表字段名必须为英文、数字、下划线`
      //     );
      //     return false;
      //   }
      // }

      // 映射字段验重
      if (row.paramType === "out" && this.form.responseForm === "standard") {
        const mapRepeat = this.tableData.find(
          (p) =>
            row.mapColumnName &&
            p.mapColumnName === row.mapColumnName &&
            p.id !== row.id
        );
        if (mapRepeat) {
          this.$modal.msgError(
            `id=${row.id}缓存映射字段${row.paramName}与id=${mapRepeat.id}缓存映射字段重复`
          );
          return false;
        }
      }

      // 参数名验重
      const repeat = this.tableData.find(
        (p) => p.paramName === row.paramName && p.id !== row.id
      );
      if (repeat) {
        this.$modal.msgError(
          `id=${row.id}参数名${row.paramName}与id=${repeat.id}参数名重复`
        );
        return false;
      }

      if (!row.dataType) {
        this.$modal.msgError(`id=${row.id}请选择数据类型`);
        return false;
      }

      return true;
    },
    submitDebug() {
      try {
        const tmp = JSON.parse(this.debugForm.requestParam);
        if (typeof tmp !== "object") {
          // console.log(typeof tmp);
          this.$modal.msgError("必要入参必须是JSON格式");
          return;
        }
      } catch (e) {
        this.$modal.msgError("必要入参必须是JSON格式");
        return;
      }
      const req = {
        authWay: this.form.authWay,
        paramForm: this.form.paramForm,
        requestMethod: this.form.requestMethod,
        requestParam: this.debugForm.requestParam,
        serviceUrl: this.form.serviceUrl,
      };
      this.debugLoading = true;
      debugService(req).then((res) => {
        this.debugLoading = false;
        if (res.data) {
          if (this.isDebug) {
            const debugForm = JSON.parse(JSON.stringify(this.debugForm));
            debugForm.debugResponse = JSON.parse(res.data);
            this.debugForm = debugForm;
          } else {
            const r = JSON.parse(res.data);
            console.log(r);
            if (r.data.code !== 0) {
              this.$modal.msgError("远程接口调用失败：" + r.data.message);
            } else {
              // this.$modal.msgSuccess("接口调用成功");

              if (r.data.columns && r.data.columns.length > 0) {
                const outParams = [];
                // console.log(r.data.columns);
                r.data.columns.forEach((p) => {
                  // let maxId = 0;
                  // if (this.tableData && this.tableData.length > 0) {
                  //   maxId = Math.max.apply(
                  //     null,
                  //     this.tableData.map((i) => i.id)
                  //   );
                  // }

                  this.tableData.push({
                    id: "tmp_" + Math.ceil(Math.random() * 100000),
                    paramType: "out",
                    paramName: p.field,
                    // paramComment: p.field,
                    mapColumnName: null,
                    dataType: "String",
                    isRequired: true,
                    remark: p.name,
                    isEdit: 0,
                  });
                });

                this.cancelDebug();
              } else {
                this.$modal.msgError("接口返回不符合标准格式，缺少columns");
              }
            }
          }
        } else {
          this.$modal.msgError("接口无返回");
        }
      });
    },
    handleDebug(isDebug) {
      if (!this.form.serviceUrl) {
        this.$modal.msgError("请填写服务地址");
        return;
      }
      if (!this.form.needAuth) {
        this.$modal.msgError("请选择是否需要鉴权");
        return;
      }
      if (!this.form.authWay) {
        this.$modal.msgError("请选择鉴权方式");
        return;
      }
      if (!this.form.requestMethod) {
        this.$modal.msgError("请选择请求方法");
        return;
      }
      if (!this.form.paramForm) {
        this.$modal.msgError("请选择参数形式");
        return;
      }

      // 获取入参
      // console.log(this.tableData);
      const inParams = this.tableData.filter((p) => p.paramType === "in");
      this.debugForm.requestParam = JSON.stringify(
        arrayToJson(inParams, "paramName")
      );

      this.isDebug = isDebug;
      this.debugFlag = true;
      if (this.isDebug === 1) {
        this.debugTitle = "接口调试";
      } else {
        this.debugTitle = "自动获取出参";
      }
    },
  },
};
</script>
