<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.native="onStep(0)"></el-step>
          <el-step title="参数/返回值" @click.native="onStep(1)"></el-step>
          <el-step title="数据集" @click.native="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"
            size="small"
          >
            <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="urlSuffix">
              <el-input v-model="form.urlSuffix">
                <template #prepend>
                  <el-select v-model="form.urlPrepend" style="width: 100px">
                    <el-option label="http://" value="http://"></el-option>
                    <el-option label="https://" value="https://"></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-col :span="11">
                <el-form-item label="数据领域">
                  <el-select v-model="form.dataField">
                    <el-option
                      v-for="dict in optionsDataField"
                      :key="dict.value"
                      :label="dict.dictLabel"
                      :value="dict.dictCode"
                    ></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>
              <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"
                size="small"
                disabled
                @click="forwardStep"
                circle
              ></el-button>
              <el-button type="primary" @click="onSubmit"> 保存</el-button>
              <el-button @click="exit">退出</el-button>
              <el-button
                icon="ArrowRight"
                size="small"
                @click="nextStep"
                circle
              ></el-button>
            </el-row>
          </el-form>
        </div>
        <div class="box" v-show="step === 1">
          <param-and-file
            ref="paramAndFile"
            :srvId="form.srvId"
            :url="form.url"
            @forwardStep="forwardStep"
            @nextStep="nextStep"
          ></param-and-file>
        </div>
        <div class="box" v-show="step === 2">
          <service-file
            ref="serviceFile"
            :srvId="form.srvId"
            @forwardStep="forwardStep"
            @nextStep="nextStep"
          ></service-file>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import {saveServiceInfo} from "@/api/service/info";
import {getCatalog} from "@/api/service/catalog";
import ParamAndFile from "./paramAndFile.vue";
import ServiceFile from "./serviceFile.vue";
import { getDicts } from "@/api/system/dict/data";
import useDictStore from '@/store/modules/dict'

export default {
  props: ["service", "serviceVisible"],
  components: {ParamAndFile, ServiceFile},
  dicts: ["service_data_field"],
  data() {
    return {
      step: 0,
      type: "添加",
      optionsDataField:[],
      form: {
        srvId: "",
        cateCode: "",
        name: "",
        url: "",
        urlSuffix: "",
        urlPrepend: "http://",
        rqtype: "GET",
        rptype: "JSON",
        type: "RESTful",
        serviceSource: "",
        serviceDept: "",
        manageName: "",
        developUnit: "",
        developContacter: "",
        maintainUnit: "",
        maintainContacer: "",
        intro: "",
        dataField: "",
        openCndtn: "0",
      },
      cascader: {
        orgListUrl: "/pt/map/countNum",
        orgPidName: "catePcode",
        orgIdName: "cateCode",
        topValue: "0",
        props: {
          emitPath: false,
          checkStrictly: true,
          children: "children",
          label: "cateName",
          value: "cateCode",
        },
        options: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: "请填写信息，该属性为必填项",
            trigger: "blur",
          },
        ],
        urlSuffix: [
          {
            required: true,
            message: "请填写信息，该属性为必填项",
            trigger: "blur",
          },
        ],
        cateCode: [
          {
            type: "string",
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.fetchData();
    this.getDicts()
  },
  methods: {
    getDicts(){
      getDicts('service_data_field').then((r) => {
        for(var i =0;i<r.data.length;i++){
          r.data[i].dictCode = r.data[i].dictCode.toString()
        }
        this.optionsDataField = r.data
      });
    },
    exit() {
      this.$emit("close");
    },
    // 前进一步
    forwardStep() {
      if (this.step === 0) {
        return;
      }
      this.step--;
    },
    // 切换步数
    onStep(step) {
      if (step != 0 && !this.form.srvId) {
        this.$message({
          message: "请先添加服务",
          type: "warning",
        });
        return;
      }
      this.step = step;
    },
    nextStep() {
      console.log(this.form.srvId)
      if (!this.form.srvId) {
        this.$message({
          message: "请先添加服务",
          type: "warning",
        });
        return;
      }

      if (this.step === 2) {
        return;
      }
      this.step++;
    },
    // 服务提交
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.url = this.form.urlPrepend + this.form.urlSuffix;
          saveServiceInfo(this.form).then((r) => {
            this.form.srvId = r.data.srvId;
            this.$message({
              message: this.type + "成功",
              type: "success",
            });
            this.nextStep();
            this.$emit("refreshTable");
          });
          return true;
        }
        return false;
      });
    },
    buildTree(flatData, rootValue = '0') {
      // 1. 创建哈希映射和结果集
      const nodeMap = new Map();
      const tree = [];

      // 2. 构建初始映射（浅拷贝节点，避免污染原数据）
      flatData.forEach(item => {
        nodeMap.set(item.cateCode, { ...item, children: [] });
      });

      // 3. 构建树结构
      for (const [code, node] of nodeMap) {
        const parentCode = node.catePcode;
        
        // 根节点直接加入结果集
        if (parentCode === rootValue || !parentCode) {
          tree.push(node);
          continue;
        }

        // 非根节点：挂载到父节点
        const parent = nodeMap.get(parentCode);
        if (parent) {
          parent.children.push(node);
        } else {
          // 处理孤儿节点（可选：也可选择忽略）
          console.warn(`Orphan node detected: ${code}. Parent ${parentCode} not found`);
        }
      }

      return tree;
    },
    fetchData() {
      getCatalog().then((r) => {
        this.cascader.options = this.buildTree(
          r.data
        );
        console.log(this.cascader.options)
      });
    },
    addParam() {
      this.$refs.paramAndFile.addParam();
    },
    submitForm(name) {
      this.$refs.paramAndFile.submitForm(name);
    },
  },
  watch: {
    "$route.query.isClose": {
      handler(val) {
        if (val == "true") {
          this.exit();
        }
      },
      immediate: true,
    },
    serviceVisible: {
      handler(val) {
        if (!val) {
          return;
        }
        this.type = "添加";
        this.step = 0;
        this.form = {
          srvId: "",
          cateCode: "",
          name: "",
          url: "",
          urlSuffix: "",
          urlPrepend: "http://",
          rqtype: "GET",
          type: "REST",
          serviceSource: "",
          serviceDept: "",
          manageName: "",
          developUnit: "",
          developContacter: "",
          maintainUnit: "",
          maintainContacer: "",
          intro: "",
          dataField: "",
          openCndtn: "0",
        };
        if (this.service) {
          this.type = "修改";
          const httpsReg = new RegExp("https://", "i");
          const httpReg = new RegExp("http://", "i");
          this.form = this.service;
          if (this.form.url) {
            let isHas = this.form.url.match(httpsReg);
            if (isHas) {
              this.form.urlPrepend = "https://";
              this.form.urlSuffix = this.form.url.replace(httpsReg, "");
            } else {
              this.form.urlPrepend = "http://";
              this.form.urlSuffix = this.form.url.replace(httpReg, "");
            }
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>
<style scoped>
.header-card ::v-deep.el-card__body {
  padding: 15px 20px;
}

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