<template>
  <div class="wrap">
    <div class="step">
      <el-steps :active="active" finish-status="success" simple>
        <el-step title="设置API基本信息"></el-step>
        <el-step title="添加服务信息"></el-step>
        <el-step title="添加参数映射关系"></el-step>
      </el-steps>
    </div>
    <div class="formdata" v-if="active === 0 || active === 1">
      <div class="title">
        <h1>API基本信息</h1>
      </div>
      <div class="content">
        <!-- <router-view></router-view> -->
        <template v-if="active === 0">
          <div>
            <baseNewForm
              refName="stepZeroform"
              ref="stepZeroform"
              :spanNumber="24"
              :formRow="stepZeroformRow"
              :ruleForm="stepZeroForm"
              :isFunBtn="false"
              @onSubmit="onSubmitHandle"
              @onChangeRadio="onChangeRadio"
            >
            </baseNewForm>
          </div>
        </template>
        <template v-if="active === 1">
          <div>
            <baseNewForm
              refName="stepOneform"
              ref="stepOneform"
              :spanNumber="24"
              :formRow="stepOneformRow"
              :ruleForm="stepOneForm"
              :isFunBtn="false"
              @onSubmit="onSubmitHandle"
            ></baseNewForm>
          </div>
        </template>
      </div>
    </div>
    <div class="step3" v-if="active === 2">
      <div class="method">
        <div class="title" style="margin-bottom: 30px">
          <h1>传递方式</h1>
        </div>
        <el-radio-group v-model="stepThreeRadio">
          <el-radio
            v-for="el in stepThreeRadioOptions"
            :label="el.id"
            :key="el.id"
            >{{ el.label }}</el-radio
          >
        </el-radio-group>
      </div>
      <div class="tableBox">
        <div class="title">
          <div class="left">Headers 入参</div>
          <div class="btn">
            <el-button
              type="primary"
              @click="jsonImportSwitch(headersTableInfo.tableData, false)"
              >导入JSON</el-button
            >
          </div>
        </div>
        <baseTableForm
          :showIndex="false"
          :indexOperate="false"
          :funWidth="funWidth"
          :funData="funData"
          :tableInfo="headersTableInfo"
          @onFunc="tableButtonHandle"
        >
          <template #parameterType="{ row }">
            <div>
              <el-select
                class="w-100"
                v-model="row[0][row[1].id]"
                :clearable="true"
                placeholder="请选择"
                @change="fatherSelectChangeHandle(row)"
              >
                <el-option
                  v-for="(el, index) in headerparameterTypeOptions"
                  :key="el.id"
                  :label="el.label"
                  :value="el.id"
                >
                </el-option>
              </el-select>
            </div>
          </template>
          <template #concreteType="{ row }">
            <el-select
              class="w-100"
              v-model="row[0][row[1].id]"
              :clearable="true"
              placeholder="请选择"
              @change="(val) => sonSelectChangeHandle(val, row)"
            >
              <el-option
                v-for="(el, index) in concreteTypeOptions[
                  row[0]['parameterType']
                ]"
                :key="el.id"
                :label="el.label"
                :value="el.id"
              >
              </el-option>
            </el-select>
          </template>
          <template #example="{ row }">
            <template v-if="row[0]['parameterType'] === 'authport'">
              <!-- <baseCascader
                v-model="row[0]['example']"
                :itemObj="bodyExitTableInfo"
              >
              </baseCascader> -->
              <el-cascader
                style="width: 100%"
                v-model="row[0][row[1].id]"
                ref="elCascader"
                :clearable="true"
                :show-all-levels="false"
                :options="authQueryOut"
                :props="selectprops"
                :disabled="false"
              ></el-cascader>
            </template>
            <template v-else>
              <el-input v-model="row[0][row[1].id]"></el-input>
            </template>
          </template>
        </baseTableForm>
        <div class="add">
          <el-link
            type="primary"
            @click="addTableData(headersTableInfo.tableData)"
            :underline="false"
            >+ 添加属性</el-link
          >
        </div>
      </div>
      <div class="tableBox">
        <div class="title">
          <div class="left">Query 入参</div>
          <div class="btn">
            <el-button
              type="primary"
              @click="jsonImportSwitch(queryTableInfo.tableData, true)"
              >导入JSON</el-button
            >
          </div>
        </div>
        <baseTableForm
          :showIndex="false"
          :indexOperate="false"
          :funWidth="funWidth"
          :funData="funData"
          :tableInfo="queryTableInfo"
          @newRow="queryTableAddHandle"
          @onFunc="tableButtonHandle"
        >
          <template #parameterType="{ row }">
            <div>
              <el-select
                class="w-100"
                v-model="row[0][row[1].id]"
                filterable
                :clearable="true"
                placeholder="请选择"
                @change="fatherSelectChangeHandle(row)"
              >
                <el-option
                  v-for="(el, index) in headerparameterTypeOptions"
                  :key="el.id"
                  :label="el.label"
                  :value="el.id"
                >
                </el-option>
              </el-select>
            </div>
          </template>
          <template #concreteType="{ row }">
            <el-select
              class="w-100"
              v-model="row[0][row[1].id]"
              filterable
              :clearable="true"
              placeholder="请选择"
              @change="(val) => sonSelectChangeHandle(val, row)"
            >
              <el-option
                v-for="(el, index) in concreteTypeOptions[
                  row[0]['parameterType']
                ]"
                :key="el.id"
                :label="el.label"
                :value="el.id"
              >
              </el-option>
            </el-select>
          </template>
          <template #example="{ row }">
            <template v-if="row[0]['parameterType'] === 'authport'">
              <!-- <baseCascader
                v-model="row[0]['example']"
                :itemObj="bodyExitTableInfo"
              >
              </baseCascader> -->
              <el-cascader
                style="width: 100%"
                v-model="row[0][row[1].id]"
                ref="elCascader"
                :clearable="true"
                :show-all-levels="false"
                :options="authQueryOut"
                :props="selectprops"
                :disabled="false"
              ></el-cascader>
            </template>
            <template v-else>
              <el-input v-model="row[0][row[1].id]"></el-input>
            </template>
          </template>
        </baseTableForm>
        <div class="add">
          <el-link
            type="primary"
            @click="addTableData(queryTableInfo.tableData)"
            :underline="false"
            >+ 添加属性</el-link
          >
        </div>
      </div>

      <div class="tableBox">
        <div class="title">
          <div class="left">Body 入参</div>
          <div class="btn">
            <el-button
              type="primary"
              @click="jsonImportSwitch(bodyEntTableInfo.tableData, true)"
              >导入JSON</el-button
            >
          </div>
        </div>
        <baseTableForm
          :showIndex="false"
          :indexOperate="false"
          :funWidth="funWidth"
          :funData="funData"
          :tableInfo="bodyEntTableInfo"
          @onFunc="tableButtonHandle"
        >
          <template #parameterType="{ row }">
            <div>
              <el-select
                class="w-100"
                v-model="row[0][row[1].id]"
                filterable
                :clearable="true"
                placeholder="请选择"
                @change="fatherSelectChangeHandle(row)"
              >
                <el-option
                  v-for="(el, index) in parameterTypeOptions"
                  :key="el.id"
                  :label="el.label"
                  :value="el.id"
                >
                </el-option>
              </el-select>
            </div>
          </template>
          <template #concreteType="{ row }">
            <el-select
              class="w-100"
              v-model="row[0][row[1].id]"
              filterable
              :clearable="true"
              placeholder="请选择"
              @change="(val) => sonSelectChangeHandle(val, row)"
            >
              <el-option
                v-for="(el, index) in concreteTypeOptions[
                  row[0]['parameterType']
                ]"
                :key="el.id"
                :label="el.label"
                :value="el.id"
              >
              </el-option>
            </el-select>
          </template>
          <template #example="{ row }">
            <template v-if="row[0]['parameterType'] === 'authport'">
              <!-- <baseCascader
                v-model="row[0]['example']"
                :itemObj="bodyExitTableInfo"
              >
              </baseCascader> -->
              <el-cascader
                style="width: 100%"
                v-model="row[0][row[1].id]"
                ref="elCascader"
                :clearable="true"
                :show-all-levels="false"
                :options="authQueryOut"
                :props="selectprops"
                :disabled="false"
              ></el-cascader>
            </template>
            <template v-else>
              <el-input v-model="row[0][row[1].id]"></el-input>
            </template>
          </template>
        </baseTableForm>
        <div class="add">
          <el-link
            type="primary"
            @click="addTableData(bodyEntTableInfo.tableData)"
            :underline="false"
            >+ 添加属性</el-link
          >
        </div>
      </div>
      <div class="tableBox">
        <div class="title">
          <div class="left">body 出参</div>
          <div class="btn">
            <el-button
              type="primary"
              @click="jsonImportSwitch(bodyExitTableInfo.tableData, true)"
              >导入JSON</el-button
            >
          </div>
        </div>
        <baseTableForm
          :showIndex="true"
          :indexOperate="false"
          :funWidth="funWidth"
          :funData="funData"
          :tableInfo="bodyExitTableInfo"
          @onFunc="tableButtonHandle"
        >
          <template #parameterType="{ row }">
            <div>
              <el-select
                class="w-100"
                v-model="row[0][row[1].id]"
                filterable
                :clearable="true"
                placeholder="请选择"
                @change="fatherSelectChangeHandle(row)"
              >
                <el-option
                  v-for="(el, index) in bodyOutOptions"
                  :key="el.id"
                  :label="el.label"
                  :value="el.id"
                >
                </el-option>
              </el-select>
            </div>
          </template>
          <template #concreteType="{ row }">
            <el-select
              class="w-100"
              v-model="row[0][row[1].id]"
              filterable
              :clearable="true"
              placeholder="请选择"
              @change="(val) => sonSelectChangeHandle(val, row)"
            >
              <el-option
                v-for="(el, index) in concreteTypeOptions[
                  row[0]['parameterType']
                ]"
                :key="el.id"
                :label="el.label"
                :value="el.id"
              >
              </el-option>
            </el-select>
          </template>
        </baseTableForm>
        <div class="add">
          <el-link
            type="primary"
            @click="addTableData(bodyExitTableInfo.tableData)"
            :underline="false"
            >+ 添加属性</el-link
          >
        </div>
      </div>
    </div>

    <div class="nextbtn">
      <el-button
        :disabled="active == 0"
        type="primary"
        @click="backActiveHandle"
        >上一步</el-button
      >
      <el-button
        :disabled="active == 2"
        type="primary"
        @click="nextActiveHanlde"
        >下一步</el-button
      >
      <el-button
        :loading="commitLoading"
        :disabled="active !== 2"
        type="primary"
        @click="commit"
        >提交</el-button
      >
      <el-button type="" @click="backPageHandle">取消</el-button>
    </div>
    <baseRightDialog
      :dialogVisible="rightDialog"
      title="JSON导入"
      @handleClose="dialoghandleClose"
      @handleConfirmClick="JSONCommit"
    >
      <div class="top" style="width: 90%; margin: 20px auto">
        <vue-json-editor
          v-model="resultInfo"
          :showBtns="false"
          :mode="'code'"
          @json-change="onJsonChange"
          @json-save="onJsonSave"
          @has-error="onError"
        />
      </div>
    </baseRightDialog>
  </div>
</template>

<script>
import baseCascader from "./compoments/baseCascader/index.vue";
import vueJsonEditor from "vue-json-editor";
import baseRightDialog from "./compoments/baseRightDialog";
import { getApiModuleApi } from "@/api/apiChunks/index.js";
import baseNewForm from "./compoments/baseNewForm.vue";
import baseTableForm from "./compoments/baseTableForm_v2.vue";
import { v4 as uuidv4 } from "uuid";
export default {
  data() {
    return {
      commitLoading: false,
      authQueryOut: [],
      selectprops: {
        label: "parameterName",
        value: "parameterName",
        expandTrigger: "hover",
      },
      resultInfo: {},
      rightDialog: false,
      active: 0,
      stepZeroformRow: [
        {
          elCol: [
            {
              type: "input",
              title: "API名称",
              maxlength: 50,
              id: "apiCode",
              row: 24,
              required: true,
              disabled: this.$route.query.id ? true : false,
            },
          ],
        },
        {
          elCol: [
            {
              type: "input",
              title: "中文名称",
              maxlength: 50,
              id: "apiName",
              // pattern: "^[\u4e00-\u9fa5]{0,}$",
              // message: "请输入中文",
              row: 24,
            },
          ],
        },
        {
          elCol: [
            {
              type: "textrea",
              title: "API功能描述",
              maxlength: 200,
              id: "apiRemark",
              row: 24,
            },
          ],
        },
        {
          elCol: [
            {
              type: "select",
              title: "API从属系统",
              id: "appId",
              row: 24,
              required: true,
              editDisable: true,
              disabled: this.$route.query.id ? true : false,
              options: [],
            },
          ],
        },
        {
          elCol: [
            {
              type: "checkbox",
              title: "允许访问入口",
              id: "enableAccessEntry",
              row: 24,
              required: true,
              options: [],
            },
          ],
        },
        {
          elCol: [
            {
              type: "radio",
              title: "API是否需要认证",
              id: "needLogin",
              row: 24,
              required: true,
              options: [
                {
                  label: "是",
                  id: "1",
                },
                {
                  label: "否",
                  id: "2",
                },
              ],
            },
          ],
        },
        {
          elCol: [
            {
              type: "newSelect",
              title: "认证接口",
              id: "authenticationPort",
              row: 24,
              show: true,
              required: true,
            },
          ],
        },
      ],
      stepZeroForm: {
        enableAccessEntry: [],
        needLogin: "1",
        enableAccessEntry: ["2"],
      },
      stepOneformRow: [
        {
          elCol: [
            {
              type: "radio",
              title: "服务接入协议",
              id: "serviceAccessProtocol",
              row: 24,
              required: true,
              options: [],
            },
          ],
        },
        {
          elCol: [
            {
              type: "input",
              title: "生产环境目标地址",
              maxlength: 200,
              id: "destinationAddress",
              pattern: "",
              message: "URL或协议不合法",
              row: 24,
              required: true,
              prepend: true,
            },
          ],
        },
        {
          elCol: [
            {
              type: "select",
              title: "请求编码",
              id: "requestCoding",
              row: 24,
              required: true,
              options: [],
            },
          ],
        },
        {
          elCol: [
            {
              type: "select",
              title: "请求方法",
              id: "requestMethod",
              row: 24,
              required: true,
              options: [],
            },
          ],
        },
        {
          elCol: [
            {
              type: "num",
              title: "超出时间",
              id: "timeoutPeriod",
              row: 24,
              min: 1,
              max: 600000,
              maxlength: 50,
              required: true,
              message: "ms",
            },
          ],
        },
        {
          elCol: [
            {
              type: "num",
              title: "限流",
              maxlength: 50,
              id: "currentLimiting",
              min: 1,
              row: 24,
              max: 1000,
              required: true,
              message: "TPS",
            },
          ],
        },
      ],
      stepOneForm: {
        serviceAccessProtocol: "1",
        requestCoding: "1",
        timeoutPeriod: 10000,
        currentLimiting: 100,
        requestMethod: "1",
      },
      stepThreeRadio: 1,
      stepThreeRadioOptions: [
        {
          label: "query透传",
          id: 1,
        },
        {
          label: "包装data透传",
          id: 2,
        },
      ],
      funData: [
        {
          type: "addattr",
          text: "添加属性",
          color: "#5a9cf8",
        },
        {
          type: "dele",
          text: "删除",
          color: "#e47470",
        },
      ],
      queryTableInfo: {
        id: "queryIn",
        tableData: [],
        detailFields: [
          {
            type: "input",
            title: "参数名称",
            id: "parameterName",
            width: 250,
            maxlength: 50,
          },
          {
            type: "select",
            title: "参数类型",
            id: "parameterType",
          },
          {
            type: "select",
            title: "具体类型",
            id: "concreteType",
          },
          {
            type: "switch",
            title: "必选",
            id: "required",
            width: 80,
          },
          {
            type: "number",
            title: "长度",
            id: "length",
            width: 100,
            maxlength: 50,
          },
          {
            type: "input",
            title: "示例",
            id: "example",
            maxlength: 50,
          },
          {
            type: "input",
            title: "描述",
            id: "description",
            maxlength: 50,
          },
          {
            type: "number",
            title: "文档顺序",
            id: "sorts",
            width: 100,
            maxlength: 50,
          },
        ],
      },
      bodyEntTableInfo: {
        id: "bodyIn",
        tableData: [],
        detailFields: [
          {
            type: "input",
            title: "参数名称",
            id: "parameterName",
            width: 250,
          },
          {
            type: "select",
            title: "参数类型",
            id: "parameterType",
          },
          {
            type: "select",
            title: "具体类型",
            id: "concreteType",
          },
          {
            type: "switch",
            title: "必选",
            id: "required",
            width: 80,
          },
          {
            type: "number",
            title: "长度",
            id: "length",
            width: 100,
          },
          {
            type: "input",
            title: "示例",
            id: "example",
          },
          {
            type: "input",
            title: "描述",
            id: "description",
          },
          {
            type: "number",
            title: "文档顺序",
            id: "sorts",
            width: 100,
          },
        ],
      },
      bodyExitTableInfo: {
        id: "bodyOut",
        tableData: [],
        detailFields: [
          {
            type: "input",
            title: "参数名称",
            id: "parameterName",
            width: 250,
          },
          {
            type: "select",
            title: "参数类型",
            id: "parameterType",
          },
          {
            type: "select",
            title: "具体类型",
            id: "concreteType",
          },
          {
            type: "switch",
            title: "必选",
            id: "required",
            width: 80,
          },
          {
            type: "number",
            title: "长度",
            id: "length",
            width: 100,
          },
          {
            type: "input",
            title: "示例",
            id: "example",
          },
          {
            type: "input",
            title: "描述",
            id: "description",
          },
          {
            type: "number",
            title: "文档顺序",
            id: "sorts",
            width: 100,
          },
        ],
      },
      headersTableInfo: {
        id: "headerIn",
        tableData: [],
        detailFields: [
          {
            type: "input",
            title: "参数名称",
            id: "parameterName",
            width: 250,
          },
          {
            type: "select",
            title: "参数类型",
            id: "parameterType",
          },
          {
            type: "select",
            title: "具体类型",
            id: "concreteType",
          },
          {
            type: "switch",
            title: "必选",
            id: "required",
            width: 80,
          },
          {
            type: "number",
            title: "长度",
            id: "length",
            width: 100,
          },
          {
            type: "input",
            title: "示例",
            id: "example",
          },
          {
            type: "input",
            title: "描述",
            id: "description",
          },
          {
            type: "number",
            title: "文档顺序",
            id: "sorts",
            width: 100,
          },
        ],
      },
      parameterTypeOptions: [
        {
          label: "基本类型",
          id: "fundamental",
        },
        {
          label: "复杂类型",
          id: "complex",
        },
        {
          label: "基本列表",
          id: "fundamentallist",
        },
        {
          label: "复杂列表",
          id: "complexlist",
        },
      ],
      headerparameterTypeOptions: [
        {
          label: "基本类型",
          id: "fundamental",
        },
      ],
      concreteTypeOptions: {
        fundamental: [
          {
            label: "String",
            id: "String",
          },
          {
            label: "Int",
            id: "Number",
          },
          {
            label: "Long",
            id: "Long",
          },
          {
            label: "Float",
            id: "Float",
          },
          {
            label: "Double",
            id: "Double",
          },
          {
            label: "Boolean",
            id: "Boolean",
          },
        ],
        complex: [
          {
            label: "Object",
            id: "Object",
          },
          {
            label: "Map",
            id: "Map",
          },
        ],
        fundamentallist: [
          {
            label: "String",
            id: "String",
          },
          {
            label: "Int",
            id: "Number",
          },
          {
            label: "Long",
            id: "Long",
          },
          {
            label: "Float",
            id: "Float",
          },
          {
            label: "Double",
            id: "Double",
          },
          {
            label: "Boolean",
            id: "Boolean",
          },
        ],
        complexlist: [
          {
            label: "Object",
            id: "ObjectCom",
          },
        ],
        authport: [
          {
            label: "String",
            id: "String",
          },
          {
            label: "Int",
            id: "Int",
          },
          {
            label: "Long",
            id: "Long",
          },
          {
            label: "Float",
            id: "Float",
          },
          {
            label: "Double",
            id: "Double",
          },
          {
            label: "Boolean",
            id: "Boolean",
          },
        ],
      },
      bodyOutOptions: [
        {
          label: "基本类型",
          id: "fundamental",
        },
        {
          label: "复杂类型",
          id: "complex",
        },
        {
          label: "基本列表",
          id: "fundamentallist",
        },
        {
          label: "复杂列表",
          id: "complexlist",
        },
      ],
      importData: [],
      importFlag: true,
    };
  },
  methods: {
    onChangeRadio(val, index, indexRow, row) {
      if (row.id === "needLogin") {
        if (val == 1) {
          this.stepZeroformRow[6]["elCol"][0]["show"] = true;
        } else {
          this.stepZeroformRow[6]["elCol"][0]["show"] = false;
          this.stepZeroForm["authenticationPort"] = "";
        }
      }
    },
    jsonImportSwitch(data, flag) {
      this.importFlag = flag;
      this.importData = data;
      this.rightDialog = true;
    },
    JSONCommit() {
      if (this.checkJson()) {
        let resultArr = [];
        // this.importData.push(this.JSONDataHandle(resultObj, this.resultInfo));
        if (!this.JSONDataHandle(resultArr, this.resultInfo, this.importFlag)) {
          resultArr.forEach((item) => this.importData.push(item));
          this.$message({
            type: "success",
            message: "导入成功",
          });
          this.dialoghandleClose();
        }
      }
    },
    JSONDataHandle(resultArr, obj, flag = true) {
      return Object.keys(obj).some((item) => {
        let resultObj = {};
        if (typeof obj[item] == "object" && obj[item] != null) {
          if (!flag) {
            this.$message({
              type: "error",
              message: "Heardes不支持导入object类型",
            });
            return true;
          }
          if (obj[item] instanceof Array) {
            if (typeof obj[item][0] === "object" && obj[item][0] != null) {
              resultObj["parameterType"] = "complexlist";
              resultObj["concreteType"] = "ObjectCom";
              resultObj["parameterName"] = item;
              resultObj["id"] = uuidv4();
              resultObj["children"] = [];
              let tempArr = resultObj["children"];
              resultArr.push(resultObj);

              this.JSONDataHandle(tempArr, obj[item][0]);
            } else {
              resultObj["parameterType"] = "fundamentallist";
              resultObj["concreteType"] = "String";
              resultObj["example"] = obj[item][0];
              resultObj["parameterName"] = item;
              resultObj["id"] = uuidv4();
              let tempArr = resultObj["children"];
              resultArr.push(resultObj);
            }
          } else {
            resultObj["concreteType"] = "Object";
            resultObj["parameterName"] = item;
            resultObj["parameterType"] = "complex";
            resultObj["id"] = uuidv4();
            resultObj["children"] = [];
            let tempArr = resultObj["children"];
            resultArr.push(resultObj);
            this.JSONDataHandle(tempArr, obj[item]);
          }
        } else {
          let type = Object.prototype.toString.call(obj[item]).slice(8, -1);
          let concreteType;
          if (type != "Null") {
            concreteType = type;
          } else {
            concreteType = "String";
          }
          Object.prototype.toString.call(obj[item]).slice(8, -1);
          resultObj["concreteType"] = concreteType;
          resultObj["example"] = obj[item] && obj[item].toString();
          resultObj["parameterName"] = item;
          resultObj["parameterType"] = "fundamental";
          resultObj["id"] = uuidv4();
          resultArr.push(resultObj);
        }
      });
    },
    dialoghandleClose() {
      this.rightDialog = false;
      this.resultInfo = {};
      this.importFlag = false;
    },
    // 父下拉框改变处理
    fatherSelectChangeHandle(row) {
      if (row[0].concreteType) {
        row[0].concreteType = "";
      }
      if (row[0] && row[0].children) {
        this.$delete(row[0], "children");
      }
      if (row[0].example) {
        row[0].example = "";
      }
    },
    // 子下拉框改变处理
    sonSelectChangeHandle(val, row) {
      if (
        val != "Object" &&
        val != "ObjectCom" &&
        val != "Map" &&
        row[0].children
      ) {
        this.$delete(row[0], "children");
      }
      if (row[0].example) {
        row[0].example = "";
      }
    },
    async APITestHandle() {},
    // 当为编辑模式时拿数据
    async getEditInfo() {
      const res = await getApiModuleApi(
        {
          tl: "appApiService",
          as: "appApi",
          dj: "queryEntity",
        },
        { id: this.$route.query.id }
      );
      if (res.status == 200) {
        let obj0 = {};
        obj0["apiCode"] = res.attribute.apiCode;
        obj0["apiName"] = res.attribute.apiName;
        obj0["apiRemark"] = res.attribute.apiRemark;
        obj0["enableAccessEntry"] = JSON.parse(res.attribute.enableAccessEntry);
        obj0["appId"] = res.attribute.appId;
        obj0["needLogin"] = res.attribute.needLogin;
        if (res.attribute.needLogin == 2) {
          this.stepZeroformRow[6]["elCol"][0]["show"] = false;
        } else {
          this.stepZeroformRow[6]["elCol"][0]["show"] = true;
        }
        // this.stepZeroformRow[6]["elCol"][0]["show"] = false;
        obj0["authenticationPort"] = res.attribute.authenticationPort;
        let obj1 = {};
        obj1["serviceAccessProtocol"] = res.attribute.serviceAccessProtocol;
        obj1["destinationAddress"] = res.attribute.destinationAddress;
        obj1["requestCoding"] = res.attribute.requestCoding;
        obj1["requestMethod"] = res.attribute.requestMethod;
        obj1["timeoutPeriod"] = res.attribute.timeoutPeriod;
        obj1["currentLimiting"] = res.attribute.currentLimiting;
        this.stepZeroForm = obj0;
        this.stepOneForm = obj1;
        if (JSON.parse(res.attribute.queryIn) instanceof Array) {
          this.queryTableInfo.tableData = JSON.parse(res.attribute.queryIn);
        }
        if (JSON.parse(res.attribute.bodyIn) instanceof Array) {
          this.bodyEntTableInfo.tableData = JSON.parse(res.attribute.bodyIn);
        }
        if (JSON.parse(res.attribute.bodyOut) instanceof Array) {
          this.bodyExitTableInfo.tableData = JSON.parse(res.attribute.bodyOut);
        }
        if (JSON.parse(res.attribute.headerIn) instanceof Array) {
          this.headersTableInfo.tableData = JSON.parse(res.attribute.headerIn);
        }
      }
    },
    // 初始化各种
    async initSysSelect() {
      const res = await getApiModuleApi({
        tl: "sysAppService",
        as: "app",
        dj: "queryList",
      });
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.stepZeroformRow[3].elCol[0].options.push({
            id: item.id,
            label: item.name,
          });
        });
      }
    },
    async initEnableAccessEntry() {
      const res = await getApiModuleApi(
        {
          tl: "generalServiceImpl",
          as: "dictionaryshop",
          dj: "selectDictionaryshop",
        },
        {
          tab_name: "sys_app_api",
          column_name: "enable_access_entry",
        }
      );
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.stepZeroformRow[4].elCol[0].options.push({
            id: item.column_value,
            label: item.column_content,
          });
        });
      }
    },
    async initServiceAccessProtocol() {
      const res = await getApiModuleApi(
        {
          tl: "generalServiceImpl",
          as: "dictionaryshop",
          dj: "selectDictionaryshop",
        },
        {
          tab_name: "sys_app_api",
          column_name: "service_access_protocol",
        }
      );
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.stepOneformRow[0].elCol[0].options.push({
            id: item.column_value,
            label: item.column_content,
          });
        });
      }
    },
    async initRequestCoding() {
      const res = await getApiModuleApi(
        {
          tl: "generalServiceImpl",
          as: "dictionaryshop",
          dj: "selectDictionaryshop",
        },
        {
          tab_name: "sys_app_api",
          column_name: "request_coding",
        }
      );
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.stepOneformRow[2].elCol[0].options.push({
            id: item.column_value,
            label: item.column_content,
          });
        });
      }
    },
    async initRequestMethod() {
      const res = await getApiModuleApi(
        {
          tl: "generalServiceImpl",
          as: "dictionaryshop",
          dj: "selectDictionaryshop",
        },
        {
          tab_name: "sys_app_api",
          column_name: "request_method",
        }
      );
      if (res.status == 200) {
        res.attribute.forEach((item) => {
          this.stepOneformRow[3].elCol[0].options.push({
            id: item.column_value,
            label: item.column_content,
          });
        });
      }
    },
    // 点击提交数据处理
    async commit() {
      this.commitLoading = true;
      let obj = {
        ...this.stepZeroForm,
        ...this.stepOneForm,
      };
      obj[this.queryTableInfo.id] = this.queryTableInfo.tableData;
      obj[this.bodyEntTableInfo.id] = this.bodyEntTableInfo.tableData;
      obj[this.bodyExitTableInfo.id] = this.bodyExitTableInfo.tableData;
      obj[this.headersTableInfo.id] = this.headersTableInfo.tableData;
      obj["bodyInType"] = 1;
      obj["parameterPassingMode"] = this.stepThreeRadio;
      if (!this.$route.query.id) {
        const res = await getApiModuleApi(
          {
            tl: "appApiService",
            as: "appApi",
            dj: "addEntity",
          },
          obj
        );
        if (res.status == 200) {
          this.$message({
            message: "保存接口成功！",
            type: "success",
          });
          this.$router.replace({
            name: "apiView",
            query: { id: res.attribute },
          });
        }
      } else {
        obj["id"] = this.$route.query.id;
        const res = await getApiModuleApi(
          {
            tl: "appApiService",
            as: "appApi",
            dj: "editEntity",
          },
          obj
        );
        if (res.status == 200) {
          this.$message({
            message: "编辑接口成功！",
            type: "success",
          });
          this.$router.replace({
            name: "apiView",
            query: { id: res.attribute },
          });
        }
      }
      this.commitLoading = false;
    },
    // 添加行
    addTableData(tabledata) {
      tabledata.push({ id: uuidv4() });
    },
    // 删除行辅助函数（递归）
    idWatch(arr, id) {
      arr.some((item, index) => {
        if (item.id === id) {
          arr.splice(index, 1);
          return true;
        } else if (item.children && item.children.length) {
          this.idWatch(item.children, id);
        } else {
          return false;
        }
      });
    },
    // 表格操作按钮
    tableButtonHandle(row, item, data) {
      if (item.type === "dele") {
        this.$confirm("确认删除？")
          .then(() => {
            this.idWatch(data, row.id);
          })
          .catch(() => {});
      } else if (item.type === "addattr") {
        if (
          row.concreteType != "Object" &&
          row.concreteType != "Map" &&
          row.concreteType != "ObjectCom"
        ) {
          this.$notify({
            title: "添加失败",
            message: "具体类型为Object或Map时才能生成子集!",
            type: "error",
          });
          return;
        } else if (!row.children) {
          console.log(row)
          this.$set(row, "children", []);
          row.children.push({ id: uuidv4() });
        } else {
          row.children.push({ id: uuidv4() });
        }
        this.$notify({
          title: "添加成功",
          message: "添加成功！",
          type: "success",
        });
      }
    },
    // 添加行
    queryTableAddHandle(tableInfo) {
      tableInfo.tableData.push({});
    },
    queryTableDeleHandle() {},
    // 点击取消
    backActiveHandle() {
      this.active--;
    },
    // 点击下一步
    nextActiveHanlde() {
      if (this.active + 1 > 2) return;
      if (this.active == 0) {
        this.$refs.stepZeroform.submitForm();
      } else if (this.active == 1) {
        this.$refs.stepOneform.submitForm();
      }
    },
    // 点击取消
    backPageHandle() {
      this.$router.back();
    },
    // 点击下一步
    onSubmitHandle(form) {
      if (this.active == 0) {
        if (this.stepZeroForm.needLogin == 1) {
          // 如果需要认证点击下一步
          // 请求认证接口拿到bodyOut
          this.getAuthInfo(this.stepZeroForm.authenticationPort);
          // 更改select选项
          this.headerparameterTypeOptions = [
            {
              label: "基本类型",
              id: "fundamental",
            },
            {
              label: "认证类型",
              id: "authport",
            },
          ];
          this.parameterTypeOptions = [
            {
              label: "基本类型",
              id: "fundamental",
            },
            {
              label: "复杂类型",
              id: "complex",
            },
            {
              label: "基本列表",
              id: "fundamentallist",
            },
            {
              label: "复杂列表",
              id: "complexlist",
            },
            {
              label: "认证类型",
              id: "authport",
            },
          ];
        } else {
          // 如果不是认证点击下一步
          this.headerparameterTypeOptions = [
            {
              label: "基本类型",
              id: "fundamental",
            },
          ];
          this.parameterTypeOptions = [
            {
              label: "基本类型",
              id: "fundamental",
            },
            {
              label: "复杂类型",
              id: "complex",
            },
            {
              label: "基本列表",
              id: "fundamentallist",
            },
            {
              label: "复杂列表",
              id: "complexlist",
            },
          ];
          // 清空表格内带有认证的select
          this.clearTableData();
        }
      }
      this.$notify({
        title: "成功",
        message: "暂存成功！",
        type: "success",
      });
      this.active++;
    },
    clearTableData() {
      this.queryTableInfo.tableData = this.queryTableInfo.tableData.filter(
        (item) => {
          return item.parameterType != "authport";
        }
      );
      this.bodyEntTableInfo.tableData = this.bodyEntTableInfo.tableData.filter(
        (item) => {
          return item.parameterType != "authport";
        }
      );
      this.bodyExitTableInfo.tableData =
        this.bodyExitTableInfo.tableData.filter((item) => {
          return item.parameterType != "authport";
        });
      this.headersTableInfo.tableData = this.headersTableInfo.tableData.filter(
        (item) => {
          return item.parameterType != "authport";
        }
      );
    },
    //点击下一步如果有认证接口则请求
    async getAuthInfo(id) {
      const res = await getApiModuleApi(
        {
          tl: "appApiService",
          as: "appApi",
          dj: "queryEntity",
        },
        { id }
      );
      if (res.status == 200) {
        this.authQueryOut = JSON.parse(res.attribute.bodyOut);
      }
    },
    // 实时保存
    onJsonChange(value) {
      this.onJsonSave(value);
    },
    // json相关
    onJsonSave(value) {
      this.resultInfo = value;
      this.hasJsonFlag = true;
    },
    // json相关（不用管）
    onError(value) {
      this.hasJsonFlag = false;
    },
    // json相关（不用管）
    checkJson() {
      if (this.hasJsonFlag === false) {
        alert("json验证失败");
        return false;
      } else {
        return true;
      }
    },
  },
  components: {
    baseNewForm,
    baseTableForm,
    baseRightDialog,
    vueJsonEditor,
    baseCascader,
  },
  computed: {
    funWidth() {
      return this.funData.length * 80;
    },
    //
    // serviceAccessProtoco() {
    //   if (this.stepOneForm.serviceAccessProtocol) {
    //     return this.stepOneForm.serviceAccessProtocol === 1
    //       ? "^http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$"
    //       : "^https://([w-]+.)+[w-]+(/[w-./?%&=]*)?$";
    //   }
    // },
  },
  watch: {
    // 正则判断
    // "stepOneForm.serviceAccessProtocol": {
    //   deep: true,
    //   immediate: true,
    //   handler(newVal, oldVal) {
    //     if (newVal == 1) {
    //       this.stepOneformRow[1].elCol[0].pattern =
    //         "^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?";
    //     } else {
    //       this.stepOneformRow[1].elCol[0].pattern =
    //         "^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+.?";
    //     }
    //   },
    // },
  },
  mounted() {
    this.initSysSelect();
    this.initEnableAccessEntry();
    this.initServiceAccessProtocol();
    this.initRequestCoding();
    this.initRequestMethod();
    if (this.$route.query.id) {
      this.getEditInfo();
    }
  },
};
</script>

<style scoped lang='scss'>
.wrap {
  height: 100%;
  overflow: scroll;
  .step {
    margin: 10px;
    border-radius: 10px;
  }
  .formdata {
    padding: 30px 10px;
    margin: 10px;
    background-color: #fff;
    border-radius: 10px;
    .content {
      width: 50vw;
      margin: 10px auto;
    }
  }
  .nextbtn {
    padding: 30 10px;
    margin: 10px;
  }
  .method {
    margin: 10px;
    border-radius: 10px;
    background-color: #fff;
    padding: 30px 10px;
    .title {
      margin-bottom: 30px;
    }
  }
  .tableBox {
    margin: 10px;
    border-radius: 10px;
    background-color: #fff;
    padding: 30px 10px;
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    .add {
      margin-top: 30px;
      border: 1px dotted #ccc;
      text-align: center;
      height: 50px;
      line-height: 50px;
    }
  }
}
</style>
