<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" style="width: 70%;">
              <div style="display: flex;width: 100%;">
                <el-input v-model="form.name"></el-input>
                <el-button @click="saveService" size="small" type="primary" plain style="margin-left: 1%;">文档模式</el-button>
                <el-button @click="saveService" size="small" type="warning" plain>调试模式</el-button>
              </div>
            </el-form-item>
            <el-form-item label="接口地址" prop="urlSuffix">
              <el-input v-model="form.url">
                <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>
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="请求参数" name="first">
              <p><label style="padding: 0 10px">地址</label>{{ url }}</p>
              <el-divider></el-divider>
              <service-param
                :srvId="srvId"
                :url="url"
                @forwardStep="forwardStep"
                @nextStep="nextStep"
              ></service-param>
            </el-tab-pane>
            <el-tab-pane label="返回值" name="second">
              <p><label style="padding: 0 10px">地址</label>{{ url }}</p>
              <el-divider></el-divider>
              <service-return
                :srvId="srvId"
                :url="url"
                @forwardStep="forwardStep"
                @nextStep="nextStep"
              ></service-return>
            </el-tab-pane>
          </el-tabs>
          <div class="app-container consult-list">
            <h3>
              数据集
              <el-tooltip
                content="数据集是存放服务的数据文件,支持JSON、EXCEL格式文件。用户可下载文件获取数据。"
                placement="top-start"
                effect="light"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
            </h3>
            <el-divider></el-divider>
            <el-row type="flex" justify="space-between">
              <el-col :span="18">
                <el-form :inline="true" :model="table.query.data">
                  <el-form-item>
                    <el-input
                      placeholder="数据集名称"
                      v-model="table.query.data.title"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      @click="getOpenDataList"
                      icon="Search"
                      size="small"
                    >
                      查询
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="2" style="text-align: right">
                <el-upload
                  ref="upload"
                  name="file"
                  :action="uploadUrl"
                  :headers="headers"
                  :before-upload="handleBeforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :data="uploadData"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">添加数据集</el-button>
                </el-upload>
              </el-col>
            </el-row>
            <el-row class="table_box">
              <el-table
                stripe
                :data="table.list"
                :height="table.height"
                style="width: 100%"
                size="small"
                :header-cell-style="{
                  background: '#ebf3fb',
                  color: '#333',
                  padding: '4px 0',
                  'border-right': '1px solid #fff',
                }"
              >
                <el-table-column type="index" align="center" label="序号" :index="1"/>
                <el-table-column
                  show-overflow-tooltip
                  v-for="(param, index) in table.params"
                  :key="index"
                  header-align="center"
                  :align="param.align ? param.align : 'center'"
                  :width="param.width ? param.width : 'auto'"
                  :prop="param.paramCode"
                  :label="param.paramName"
                >
                  <template #default="scope">
                    <span v-if="param.paramCode != 'viewNum'">
                      {{ scope.row[param.paramCode] }}
                    </span>
                    <span v-if="param.paramCode == 'viewNum'">
                      <el-tag disable-transitions>
                        {{
                          scope.row[param.paramCode] == null
                            ? "0"
                            : scope.row[param.paramCode]
                        }}
                      </el-tag>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" label="操作" width="auto">
                  <template #default="scope">
                    <!-- <el-button @click="handlerDoc('view', scope.row)">
                      预览
                    </el-button> -->
                    <el-button type="primary" @click="downloadFile(scope.row)">
                      下载
                    </el-button>
                    <el-button
                      type="danger"
                      @click="deleteServiceFile(scope.row.fileId)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="table.total > 0"
                :total="table.total"
                :page.sync="table.query.pageNum"
                :limit.sync="table.query.pageSize"
                @pagination="getOpenDataList"
              />
            </el-row>
            <el-row type="flex" justify="center">
              <!-- <el-button
                icon="ArrowLeft"
                @click="forwardStep"
                circle
              ></el-button>
              <el-button @click="exit">退出</el-button>
              <el-button
                icon="ArrowRight"
                @click="nextStep"
                disabled
                circle
              ></el-button> -->
            </el-row>
            <a ref="downloadTools" style="display: none" href="" download=""></a>
          </div>

        </div>
        <div class="box" v-show="step === 1">
          <param-and-file
            ref="paramAndFile"
            :srvId="paramsFile"
            :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'
import ServiceParam from "./serviceParam.vue";
import ServiceReturn from "./serviceReturn.vue";
import {
  getServiceFile,
  updateServiceFile,
  deleteServiceFile,
} from "@/api/service/serviceFile.js";
import {getToken} from "@/utils/auth";
export default {
  props: ["service", "serviceVisible"],
  components: {ParamAndFile, ServiceFile,ServiceParam, ServiceReturn},
  dicts: ["service_data_field"],
  data() {
    return {
      uploadUrl: "/pt/service/file/add",
      headers: {Authorization: "Bearer " + getToken()},
      fileSize: "100",
      uploadData: {},
      fileTypes: [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel",
        "application/pdf",
        "text/xml, application/xml",
        "application/xml",
        "text/xml",
        "application/json",
        "text/csv",
      ],
      table: {
        height: window.innerHeight - 430,
        list: [],
        params: [
          {
            paramCode: "fileViewname",
            paramName: "数据集名称",
            align: "left",
            width: "200",
          },
          {
            paramCode: "fileType",
            paramName: "数据集类型",
            width: "100",
          },
          {
            paramCode: "fileSize",
            paramName: "数据集大小",
            width: "100",
          },
          {paramCode: "viewNum", paramName: "访问数量/次", width: "90"},
          {paramCode: "fileTime", paramName: "提交时间", width: "120"},
        ],
        total: 0,
        query: {
          pageNum: 1,
          pageSize: 20,
          orderBy: "",
          data: {
            name: "",
          },
        },
      },
      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",
      },
      paramsFile:[],
      cascader: {
        orgListUrl: "/pt/map/countNum",
        orgPidName: "catePcode",
        orgIdName: "cateCode",
        topValue: "0",
        props: {
          emitPath: false,
          checkStrictly: true,
          children: "children",
          label: "cateName",
          value: "cateCode",
        },
        options: [],
      },
      activeName: "first",
      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()
    this.getOpenDataList();
  },
  methods: {
    
    // 前进一步
    forwardStep() {
      this.$emit("forwardStep");
    },
    // 后退一步
    nextStep() {
      this.$emit("nextStep");
    },
    // 查询帮助数据集表
    async getOpenDataList() {
      if (!this.srvId) {
        return;
      }
      await getServiceFile(this.table.query, this.srvId).then((r) => {
        this.table.list = r.rows;
        this.table.total = r.total;
      });
    },
    // 下载文件
    downloadFile(file) {
      if (file) {
        this.$refs.downloadTools.href = "/doc/files" + file.path;
        this.$refs.downloadTools.download = file.name;
        this.$refs.downloadTools.click();
      }
    },
    // 删除文件
    deleteServiceFile(id) {
      deleteServiceFile(id)
        .then(() => {
          this.$message.success("文件删除成功");
          this.getOpenDataList();
        })
        .catch(() => {
          this.$message.error("文件删除失败");
        });
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      if (!this.srvId) {
        return;
      }
      this.headers.srvId = this.srvId;
      this.uploadData = {srvId: this.srvId};
      const pattern = /\.{1}[A-Za-z]{1,}$/;
      let fileExt = pattern.exec(file.name);
      const checkType = this.fileTypes.includes(file.type);
      debugger;
      if (!checkType) {
        this.$message.warning(
          "只能上传 .xls、.xlsx、.json、.xml、.csv 格式的文件!"
        );
        return false;
      }
      if (![".xls", ".xlsx"].includes(fileExt[0].toLowerCase())) {
        this.$message.warning(
          "只能上传 .xls、.xlsx、.json、.xml、.csv 格式的文件!"
        );
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传成功后
    handleUploadSuccess(res, file) {
      this.getOpenDataList();

      // // 获取富文本组件实例
      // let quill = this.Quill;
      // // 如果上传成功
      // if (res.code == 200) {
      //   // 获取光标所在位置
      //   let length = quill.getSelection().index;
      //   // 插入图片  res.url为服务器返回的图片地址
      //   quill.insertEmbed(
      //     length,
      //     "image",
      //     process.env.VUE_APP_BASE_API + res.fileName
      //   );
      //   // 调整光标到最后
      //   quill.setSelection(length + 1);
      // } else {
      //   this.$message.error("文件上传成功");
      // }
    },
    // 文件上传失败
    handleUploadError() {
      this.$message.error("文件上传失败");
    },
    // 退出
    exit() {
      this.$nextTick(() => {
        this.$router.replace({
          query: {isClose: "true"},
        });
      });
    },
  
    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
        );
      });
    },
    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 = "修改";
          this.paramsFile = this.form.params
          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>
