<template>
  <el-row :gutter="10" class="ae-service">
    <el-col :span="24">
      <el-card class="header-card">
        <el-steps :active="step" finish-status="success">
          <el-step title="基本信息" @click="onStep(0)"></el-step>
          <el-step title="参数/返回值" @click="onStep(1)"></el-step>
          <el-step title="数据集" @click="onStep(2)"></el-step>
        </el-steps>
      </el-card>
    </el-col>
    <el-col :span="24" class="service-body">
      <el-card>
        <div class="box" v-show="step === 0">
          <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-width="120px"

          >
            <el-form-item label="服务分类" prop="cateCode">
              <el-cascader
                  v-model="form.cateCode"
                  :options="cascader.options"
                  :props="cascader.props"
                  :show-all-levels="false"
                  filterable
                  clearable
              />
            </el-form-item>
            <el-form-item label="服务名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="接口地址" prop="url">
              <el-input v-model="form.url">
                <template #prepend>
                  <el-select v-model="form.proxyPath" style="width:200px;" @change="handleGatewayChange">
                    <el-option v-for="item in gatewayList" :key="item.id" :label="item.serviceName"
                               :value="item.predicates" :data-service-name="item.serviceName"></el-option>
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-row>
              <el-col :span="11">
                <el-form-item label="开放等级">
                  <el-select v-model="form.openCndtn">
                    <el-option label="申请开放" value="0"></el-option>
                    <el-option label="登录开放" value="1"></el-option>
                    <el-option label="完全开放" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="请求方式">
                  <el-select v-model="form.rqtype">
                    <el-option label="GET" value="get"></el-option>
                    <el-option label="POST" value="post"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="接口格式">
                  <el-select v-model="form.type">
                    <el-option label="RESTful" value="RESTful"></el-option>
                    <el-option label="WebService" value="WebService"></el-option>
                    <el-option label="HTTP" value="HTTP"></el-option>
                    <el-option label="WebSocket" value="WebSocket"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="返回格式">
                  <el-select v-model="form.rptype">
                    <el-option label="json" value="json"></el-option>
                    <el-option label="html" value="html"></el-option>
                    <el-option label="xml" value="xml"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 隐藏所属业务系统选项 -->
            <el-row v-show="false">
              <el-col :span="24">
                <el-form-item label="所属业务系统">
                  <el-input v-model="form.serviceSource"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="所属业务部门">
                  <el-input v-model="form.serviceDept"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="业务部门管理人">
                  <el-input v-model="form.manageName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="开发单位">
                  <el-input v-model="form.developUnit"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="开发单位联系人">
                  <el-input v-model="form.developContacter"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="运维单位">
                  <el-input v-model="form.maintainUnit"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="运维单位联系人">
                  <el-input v-model="form.maintainContacer"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="服务说明">
              <el-input v-model="form.intro" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="返回说明">
              <el-input
                  v-model="form.rpcontent"
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 8 }"
              ></el-input>
            </el-form-item>
            <el-row type="flex" justify="center">
              <el-button
                  icon="ArrowLeft"

                  disabled
                  @click="forwardStep"
                  circle
              ></el-button>
              <el-button type="primary" @click="onSubmit"> 保存</el-button>
              <el-button @click="exit">退出</el-button>
              <el-button
                  icon="ArrowRight"
                  @click="nextStep"
                  circle
              ></el-button>
            </el-row>
          </el-form>
        </div>
        <div class="box" v-show="step === 1">
          <param-and-file
              ref="paramAndFileRef"
              :srvId="form.srvId"
              :url="form.url"
              @forwardStep="forwardStep"
              @nextStep="nextStep"
              @close="exit"
          ></param-and-file>
        </div>
        <div class="box" v-show="step === 2">
          <service-file
              ref="serviceFileRef"
              :srvId="form.srvId"
              @forwardStep="forwardStep"
              @nextStep="nextStep"
              @close="exit"
          ></service-file>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue';
import {saveServiceInfo} from "@/api/service/info";
import {getCatalog} from "@/api/service/catalog";
import {handleTree} from "@/utils/ruoyi"; // 使用 handleTree 替代 handleTree2
import ParamAndFile from "./paramAndFile.vue";
import ServiceFile from "./serviceFile.vue";
import {useRoute} from 'vue-router';
import {getGatewayRouters} from "@/api/gateway/gatewayRouters.js";
import {ElMessage} from "element-plus";

const {proxy} = getCurrentInstance();

// 定义 props
const props = defineProps(["service", "serviceVisible"]);

// 定义 emits
const emit = defineEmits(['close', 'refreshTable']);

// 响应式数据
const step = ref(0);
const type = ref("添加");
const route = useRoute();

const formRef = ref();
const paramAndFileRef = ref();
const serviceFileRef = ref();

const gatewayList = ref([]);

const form = reactive({
  srvId: "",
  cateCode: "",
  name: "",
  url: "",
  urlSuffix: "",
  rqtype: "GET",
  rptype: "JSON",
  type: "RESTful",
  serviceSource: "",
  serviceDept: "",
  manageName: "",
  developUnit: "",
  developContacter: "",
  maintainUnit: "",
  maintainContacer: "",
  intro: "",
  openCndtn: "0",
});

const cascader = reactive({
  orgListUrl: "/pt/map/countNum",
  orgPidName: "catePcode",
  orgIdName: "cateCode",
  topValue: "0",
  props: {
    emitPath: false,
    checkStrictly: true,
    children: "children",
    label: "cateName",
    value: "cateCode",
  },
  options: [],
});

const rules = reactive({
  name: [
    {
      required: true,
      message: "请填写信息，该属性为必填项",
      trigger: "blur",
    },
  ],
  urlSuffix: [
    {
      required: true,
      message: "请填写信息，该属性为必填项",
      trigger: "blur",
    },
  ],
  cateCode: [
    {
      type: "string",
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
});

// 方法定义

const getGatewayList = () => {
  getGatewayRouters().then(res => {
    gatewayList.value = res.data
  })
};
getGatewayList();

// 接口地址选择器变化事件
const handleGatewayChange = (value) => {
  // 根据选中的 predicates 找到对应的 gateway 项目
  const selectedGateway = gatewayList.value.find(item => item.predicates === value);
  if (selectedGateway && selectedGateway.serviceName) {
    // 将选中项的 serviceName 赋值给所属业务系统
    form.serviceSource = selectedGateway.serviceName;
  }
};

const exit = () => {
  emit('close');
};

// 前进一步
const forwardStep = () => {
  if (step.value === 0) {
    return;
  }
  step.value--;
};

// 切换步数
const onStep = (stepVal) => {
  if (stepVal != 0 && !form.srvId) {
    proxy.$modal.msgWarning("请先添加服务")
    return;
  }
  step.value = stepVal;
};

const nextStep = () => {
  if (!form.srvId) {
    proxy.$modal.msgWarning("请先添加服务")
    return;
  }

  if (step.value === 2) {
    return;
  }
  step.value++;
};

// 服务提交
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      saveServiceInfo(form).then((r) => {
        form.srvId = r.data.srvId;
        proxy.$modal.msgSuccess(type.value + "成功")
        nextStep();
        emit('refreshTable');
      });
      return true;
    }
    return false;
  });
};

const fetchData = () => {
  getCatalog().then((r) => {
    cascader.options = handleTree(
        r.data,
        "catePcode",
        "cateCode",
        "0"
    );
  });
};

const addParam = () => {
  paramAndFileRef.value.addParam();
};

const submitForm = (name) => {
  paramAndFileRef.value.submitForm(name);
};

// 监听器
watch(() => route.query.isClose, (val) => {
  if (val === "true") {
    this.$router.replace({query: {isClose: "false"}});
    exit();
  }
}, {immediate: true});

watch(() => props.serviceVisible, (val) => {
  if (!val) {
    return;
  }
  type.value = "添加";
  step.value = 0;
  Object.assign(form, {
    srvId: "",
    cateCode: "",
    name: "",
    url: "",
    urlSuffix: "",
    rqtype: "GET",
    type: "REST",
    serviceSource: "",
    serviceDept: "",
    manageName: "",
    developUnit: "",
    developContacter: "",
    maintainUnit: "",
    maintainContacer: "",
    intro: "",
    openCndtn: "0",
  });

  if (props.service && props.service.srvId) {
    type.value = "修改";
    Object.assign(form, props.service);
  }
}, {immediate: true, deep: true});

// 生命周期钩子
onMounted(() => {
  fetchData();
});
</script>
<style scoped>
.header-card ::v-deep(.el-card__body) {
  padding: 15px 20px;
}

.box {
  height: calc(100vh - 201px);
  display: inline;
}

/* 增加表单项之间的间距 */
.ae-service ::v-deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>
