<template>
  <div class="detail_contain">
    <p class="now_page_title">
      我的服务 /
      {{
        now_user == 0 || now_user == 4
          ? "注册发布的服务"
          : now_user == 1
          ? "组织服务管理"
          : "平台服务管理"
      }}
      /
      <span>服务详情</span>
    </p>
    <div class="info_contain">
      <service-header :data="service_header_arr"></service-header>
      <div class="type_box">
        <div class="type_title">
          <div
            v-for="(item, index) in service_arr[now_user]"
            :key="index + 1000"
            class="type_select"
            @click="now_service = index"
            :style="
              now_service == index ? { borderBottom: '4px solid #f5ab4c' } : {}
            "
          >
            {{ item }}
          </div>
        </div>
        <div class="type_box_select">
          <info-list
            :list_arr="now_service == 0 ? list_arr : servicead_arr"
            v-if="now_service == 0 || (now_service == 1&&!workflows_id)"
          >
            <table-um
              :headers="req_header_arr"
              :datas="req_data"
              :stripe="true"
              slot="req_table"
            ></table-um>
            <v-apaas-code :datas="req_code_arr" slot="req_code" :readOnly="true"></v-apaas-code>
            <table-um
              :headers="res_header_arr"
              :datas="res_data"
              :stripe="true"
              slot="res_table"
            ></table-um>
            <v-apaas-code :datas="res_code_arr" slot="res_code" :readOnly="true"></v-apaas-code>
          </info-list>
          <p v-if="now_service == 1&&workflows_id">
            流程服务接口说明见文档中心流程服务接口文档
          </p>
          <div v-show="now_service == 2">
            <p class="service_title"><span></span>服务运行概况</p>
            <div class="service_title_card">
              <nor-card title="服务状态" class="service_card">
                <template>
                  <div style="height:115px;padding-top:10px;">
                    <waveIcon
                      :state="yx_state.state"
                      style="margin:10px auto;"
                    ></waveIcon>
                    <p
                      style="color: #58617a;font-size: 16px;text-align:center;"
                    >
                      {{ yx_state.state }}
                    </p>
                  </div>
                </template>
              </nor-card>
              <nor-card title="平均响应时间" class="service_card">
                <template>
                  <div style="height:115px;" class="service_num">
                    <p>{{ yx_state.averageTime }}</p>
                    <p>最大响应时间：{{ yx_state.maxTime }}</p>
                  </div>
                </template>
              </nor-card>
              <nor-card title="吞吐率" class="service_card">
                <template>
                  <div style="height:115px;" class="service_num">
                    <p>{{ yx_state.averageTraffic }}</p>
                    <p>最大吞吐率：{{ yx_state.maxTraffic }}</p>
                  </div>
                </template>
              </nor-card>
              <nor-card title="资源使用" class="service_card">
                <template>
                  <div
                    style="height:115px;padding-top:30px;"
                    class="service_num"
                  >
                    <p>{{ yx_state.memory }}</p>
                  </div>
                </template>
              </nor-card>
            </div>
            <nor-card title="服务调用拓扑图" class="service_card_charts">
              <Topology :datas="datas" />
            </nor-card>
            <p class="service_title"><span></span>服务调用列表</p>
            <table-um
              :headers="header_use_arr"
              :datas="service_use_arr"
            ></table-um>
            <list-pagination
              :total="listTotal"
              :page-sizes="pageSizes"
              :page-size="pageSize"
              :current-page="currentPage"
              @size-change="changePageSize"
              @current-change="changeCurrentPage"
            ></list-pagination>
          </div>
          <div v-show="now_service == 3">
            <p style="color: #8890a7;">服务规格：</p>
            <table-um
              :stripe="true"
              :headers="service_size_arr"
              :datas="service_size_data"
            ></table-um>
            <p style="color: #8890a7;">购买方式：</p>
            <p style="color: #242c43;margin:10px 0px;">
              {{
                buy_type == 1
                  ? "按月购买"
                  : buy_type == 2
                  ? "按年购买"
                  : "按月购买&按年购买"
              }}
            </p>
            <div
              class="editbtn"
              v-if="now_user == 1"
              @click="sizeset_flag = true"
            >
              编辑
            </div>
            <p
              v-if="now_user == 1 && sizeset_flag"
              style="color: #8890a7;margin-bottom:10px;"
            >
              规格设置：
            </p>
            <table-um
              v-if="now_user == 1 && sizeset_flag"
              :headers="edit_size_arr"
              headerCellClassName="th_pink"
              :border="true"
              :autoAdd="true"
              :couldNotEdit="false"
              :radius="true"
              :isIndex="true"
              :datas="service_size_data"
              @changeTable="now_size_data"
            ></table-um>
            <p
              v-if="now_user == 1 && sizeset_flag"
              style="color: #8890a7;margin:10px 0;"
            >
              购买方式：
            </p>
            <el-button
              v-if="now_user == 1 && sizeset_flag"
              :type="buy_style.indexOf(1) !== -1 ? 'primary' : ''"
              @click="change_buy(1)"
              >按月购买</el-button
            >
            <el-button
              v-if="now_user == 1 && sizeset_flag"
              :type="buy_style.indexOf(2) !== -1 ? 'primary' : ''"
              @click="change_buy(2)"
              >按年购买</el-button
            >
            <div class="savebtn" v-if="now_user == 1 && sizeset_flag">
              <el-button @click="change_service_size">保存</el-button>
              <el-button @click="sizeset_flag = false">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <dialog-action ref="myConfirm"></dialog-action>
  </div>
</template>

<script>
import infoList from "@/components/infoList";
import tableUm from "@/components/table/table-um";
import codes from "@/components/general/codes";
import norCard from "@/components/card";
import waveIcon from "@/components/general/wave_icon";
import Topology from "@/components/topology.vue";
import serviceHeader from "@/components/service-header";
import ListPagination from "@/components/comments-pagination";
import dialogAction from "@/components/dialog-action";
import { getRole, formatDateTime_date } from "@/utils/common";
import { mapGetters, mapState } from "vuex";
export default {
  components: {
    infoList,
    tableUm,
    "v-apaas-code": codes,
    norCard,
    waveIcon,
    Topology,
    serviceHeader,
    dialogAction,
    ListPagination,
  },
  data() {
    return {
      now_user: 0, //0：普通用户，1：组织管理员，2：超级管理员
      buy_style: [1],
      listTotal: 0,
      currentPage: 1,
      pageSize: 10,
      pageSizes: [10, 50, 100],
      responseParamUrl: "",
      codeExampleUrl: "",
      yx_state: {
        state: "",
        averageTime: "",
        maxTime: "",
        averageTraffic: "",
        maxTraffic: "",
        memory: "",
      },
      service_use_arr: [],
      req_header_arr: [
        {
          prop: "name",
          label: "字段编码",
          align: "left",
          width: 200,
        },
        {
          prop: "label",
          label: "字段名称",
          align: "center",
          width: 200,
        },
        {
          prop: "show_type",
          label: "字段类型",
          align: "center",
          width: 240,
        },
        {
          prop: "descript",
          label: "字段说明",
          align: "left",
        },
        {
          prop: "is_must",
          label: "是否必须",
          align: "center",
          width: 240,
        },
      ], // 请求参数-header
      req_data: [], // 请求参数
      req_code_arr: "", // 请求示例
      res_header_arr: [
        {
          prop: "name",
          label: "字段编码",
          align: "left",
          width: 200,
        },
        {
          prop: "label",
          label: "字段名称",
          minWidth: "20%",
          align: "center",
          width: 200,
        },
        {
          prop: "show_type",
          label: "字段类型",
          width: "100px",
          align: "center",
          width: 240,
        },
        {
          prop: "descript",
          label: "字段说明",
          minWidth: "30%",
          align: "left",
        },
        {
          prop: "example",
          label: "字段示例数值",
          width: "120px",
          align: "center",
          width: 240,
        },
      ], // 响应参数-header
      res_data: [], // 响应参数
      res_code_arr: "", // 响应示例
      buy_type: "",
      workflows_id:'',//判断是否是流程服务
      sizeset_flag: false, //规格设置是否显示
      service_arr: [
        ["服务基本信息", "接口详细信息", "服务运行状态"],
        ["服务基本信息", "接口详细信息", "服务运行状态", "服务计费规则"],
        ["服务基本信息", "接口详细信息", "服务运行状态", "服务规格"],
      ],
      service_size_data: [], //服务规格数组
      service_header_arr: {
        id: "",
        isMap: false,
        url: "",
        name: "",
        first: [
          {
            name: "服务类型",
            text: "",
          },
          {
            name: "申请次数",
            text: "",
          },
          {
            name: "调用次数",
            text: "",
          },
          {
            name: "服务状态",
            text: "",
          },
        ],
        second: [
          {
            name: "服务接口地址",
            text: "",
          },
        ],
        fixed: true,
        fixedurl: this.$route.path.replace("servicedetail", "serviceedit"),
      },
      now_service: 0,
      datas: {},
      header_use_arr: [
        {
          prop: "dydw",
          label: "调用单位",
          minWidth: "20%",
          align: "left",
        },
        {
          prop: "dyr",
          label: "调用人",
          width: "100px",
          align: "center",
        },
        {
          prop: "dyyw",
          label: "调用业务系统",
          minWidth: "20%",
          align: "left",
        },
        {
          prop: "ywxt",
          label: "业务系统网址",
          minWidth: "20%",
          align: "left",
        },
        {
          prop: "cjms",
          label: "场景描述",
          minWidth: "40%",
          align: "left",
        },
        {
          prop: "sqgg",
          label: "申请规格",
          minWidth: "40%",
          align: "center",
        },
        {
          prop: "sqsc",
          label: "申请时长",
          minWidth: "40%",
          align: "center",
        },
        {
          prop: "sqsj",
          label: "申请调用时间",
          width: "160px",
          align: "right",
        },
      ],
      service_size_arr: [
        {
          prop: "count",
          label: "访问次数（次/日）",
          minWidth: "33.33%",
          align: "center",
        },
        {
          prop: "pv",
          label: "访问量（PV/日）",
          minWidth: "33.33%",
          align: "center",
        },
        {
          prop: "des",
          label: "规格说明",
          minWidth: "33.33%",
          align: "left",
        },
      ],
      edit_size_arr: [
        {
          prop: "count",
          label: "访问次数（次/日）",
          minWidth: "33.33%",
          align: "center",
          type: "inputNumber",
        },
        {
          prop: "pv",
          label: "访问量（PV/日）",
          minWidth: "33.33%",
          align: "center",
          type: "inputNumber",
        },
        {
          prop: "des",
          label: "规格说明",
          minWidth: "33.33%",
          align: "left",
          type: "input",
        },
        {
          label: "操作",
          type: "Button",
          align: "center",
          width: 140,
          btnList: [
            {
              type: "action-delete",
              label: "删除",
              local: true,
            },
          ],
        },
      ],
      size_arr_down: [],
      servicead_arr: [
        {
          title: "请求方式：",
          info: "",
        },
        {
          title: "请求参数：",
          info: "",
          type: "solt",
          solt_name: "req_table",
        },
        {
          title: "请求示例：",
          info: "",
          type: "solt",
          solt_name: "req_code",
        },
        {
          title: "编码格式：",
          info: "",
        },
        {
          title: "响应参数：",
          info: "",
          type: "solt",
          solt_name: "res_table",
        },
        {
          title: "响应示例：",
          info: "",
          type: "solt",
          solt_name: "res_code",
        },
      ],
      service_type_arr: [
        "数据服务",
        "时空服务",
        "视频服务",
        "感知服务",
        "综合应用",
      ],
      scrvice_area_arr: [
        "经济建设",
        "城市建设",
        "道路交通",
        "环境资源",
        "服务民生",
        "空间地理",
        "文化休闲",
        "社会团体",
        "教育机构",
        "其他",
      ],
      open_arr: ["共享", "受限", "敏感"],
      service_state_arr: ["已下架", "已上架", "审核中", "审核中"],
      request_arr: ["GET", "POST", "PUT", "DELETE"],
      list_arr: [
        {
          title: "服务描述：",
          info: "",
        },
        {
          title: "服务领域：",
          info: "",
        },
        {
          title: "所属组织：",
          info: "",
        },
        {
          title: "开放程度：",
          info: "",
        },
        {
          title: "接口编码：",
          info: "",
        },
        {
          title: "注册发布时间：",
          info: "",
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["level"]),
    ...mapState(["userInfo"]),
  },
  watch: {
    now_service(n, o) {
      if (n == 2) {
        this.getData();
      }
    },
  },
  created() {
    if (this.userInfo) {
      this.now_user = this.level;
    } else {
      this.getCurrentUser();
    }
    this.getServiceInfo();
    this.getServiceyxztInfo();
    this.get_use_list();
  },
  mounted() {},
  methods: {
    changePageSize(value) {
      this.pageSize = value;
      this.currentPage = 1;
      this.get_use_list();
    },
    changeCurrentPage(value) {
      this.currentPage = value;
      this.get_use_list();
    },
    get_use_list() {
      this.service_use_arr = [];
      this.$http
        .get(
          `/apaas/service/v3/service/manager/service/applys?service_id=${this.$route.params.id}&page=${this.currentPage}&size=${this.pageSize}`
        )
        .then((response) => {
          console.log(response);
          if (response.data.success) {
            this.listTotal = response.data.data.total;
            let data = response.data.data.data || [];

            data.forEach((e) => {
              this.service_use_arr.push({
                dydw: e.apply_org_name,
                dyr: e.apply_user_info.user_name,
                dyyw: e.business_name,
                ywxt: e.business_url,
                cjms: e.scene,
                sqsj: e.apply_time.split("+")[0].replace("T", " "),
                sqgg: e.request_spcs
                  ? `访问次数：${e.request_spcs.count}/日 访问量：${e.request_spcs.pv}/日`
                  : "",
                sqsc: e.duration + ["", "个月", "年"][e.duration_unit || 0],
              });
            });
          }
        })
        .catch(function(response) {});
    },
    change_buy(val) {
      if (this.buy_style.indexOf(val) !== -1) {
        this.buy_style.splice(this.buy_style.indexOf(val), 1);
      } else {
        this.buy_style.push(val);
      }
    },
    getCurrentUser() {
      this.$api.user.getNowUser().then(({ data }) => {
        if (data.success == 1) {
          this.$store.commit("userInfofun", data.data);
          this.now_user = this.level;
          console.log(this.level);
        } else {
          console.log(data.errMsg);
        }
      });
    },
    getData() {
      console.log(this.namespace)
      this.$api.workbench.getServiceRunningTopology({ namespace: this.namespace }).then((response) => {
        this.datas = response.data.elements;
      });
    },
    getServiceInfo() {
      this.$http
        .get(
          "/apaas/service/v3/service/manager?service_id=" +
            this.$route.params.id
        )
        .then((response) => {
          if (response.data.success === 1) {
            let data = response.data.data;
            this.namespace = data.namespace;
            if(data.workflows_id){
              this.workflows_id = data.workflows_id
            }
            this.$set(this.service_header_arr, "portal_id", data.portal_id); // 时空服务id
            this.$set(
              this.service_header_arr,
              "isMap",
              data.data_service_type1 === 6
            );
            this.$set(this.service_header_arr, "name", data.name);
            this.$set(
              this.service_header_arr["first"][0],
              "text",
              data.data_service_type1_name
            );
            this.$set(
              this.service_header_arr["first"][1],
              "text",
              data.apply_num
            );
            this.$set(
              this.service_header_arr["first"][2],
              "text",
              data.request_count
            );
            this.$set(
              this.service_header_arr["first"][3],
              "text",
              this.service_state_arr[data.state]
            );
            this.$set(
              this.service_header_arr["second"][0],
              "text",
              data.req_url
            );
            this.$set(this.service_header_arr, "url", data.cover);
            if (this.now_user == 1) {
              this.$set(this.service_header_arr, "fixed", false);
            }
            this.$set(
              this.service_header_arr,
              "fixedurl",
              this.$route.path.replace("servicedetail", "serviceedit")
            );
            this.$set(this.list_arr[0], "info", data.descript);
            this.$set(this.list_arr[1], "info", data.sectors_name);
            this.$set(this.list_arr[2], "info", data.organization_name);
            this.$set(this.list_arr[3], "info", data.openness_name);
            this.$set(this.list_arr[4], "info", data.encode_method);
            this.$set(
              this.list_arr[5],
              "info",
              data.create_time.replace("T", " ").split("+")[0]
            );

            // 接口详情信息
            this.$set(
              this.servicead_arr[0],
              "info",
              this.request_arr[data.req_type - 1]
            ); // 请求方式
            this.req_data = JSON.parse(
              data.req_fields || data.req_query || "[]"
            ); // 请求参数
            if (this.req_data && this.req_data.length === 0) {
              this.$set(this.servicead_arr[1], "type", "");
              this.$set(this.servicead_arr[1], "info", "无请求参数");
            }
            this.req_code_arr =
              data.req_fields_example || data.req_query_example || ""; // 请求示例
            if (!this.req_code_arr) {
              this.$set(this.servicead_arr[2], "type", "");
              this.$set(this.servicead_arr[2], "info", "无请求示例");
            }
            this.$set(this.servicead_arr[3], "info", data.encode_method); // 编码格式
            this.res_data = JSON.parse(data.res_fields || "[]"); // 响应参数
            if (this.res_data && this.res_data.length === 0) {
              this.$set(this.servicead_arr[4], "type", "");
              this.$set(this.servicead_arr[4], "info", "无响应参数");
            }
            console.log(data.res_fields_example)
            this.res_code_arr = data.res_fields_example || ""; // 响应示例
            console.log(this.res_code_arr)
            if (!this.res_code_arr) {
              this.$set(this.servicead_arr[5], "type", "");
              this.$set(this.servicead_arr[5], "info", "无响应示例");
            }
            // 接口详情信息 end

            this.service_size_data = data.request_spcs_info;
            this.size_arr_down = data.request_spcs_info;
            this.buy_type = data.request_spcs_info[0].type;
            if (this.buy_type == 3) {
              this.buy_style = [1, 2];
            } else {
              this.buy_style = [this.buy_type];
            }
          } else {
            this.$message({
              message: response.data.errMsg,
              type: "warning",
            });
          }
        })
        .catch(function(response) {});
    },
    now_size_data(val) {
      console.log(val);
      this.size_arr_down = val;
    },
    getsize_arr() {
      this.$http
        .get(
          "/apaas/service/v3/service/manager/request/spcs/list?service_id=" +
            this.$route.params.id
        )
        .then((response) => {
          let data = response.data.data;
          console.log(data);
          this.service_size_data = data.data;
          this.buy_type = data.data[0].type;
          if (this.buy_type == 3) {
            this.buy_style = [1, 2];
          } else {
            this.buy_style = [this.buy_type];
          }
        })
        .catch(function(response) {});
    },
    change_service_size() {
      let temp = [];
      this.size_arr_down.forEach((e) => {
        if (e.pv && e.count) {
          if (e.flag) {
            e.id = 0;
          }
          if (this.buy_style.length == 0) {
            this.$message.error("请选择申请时长");
            return;
          } else if (this.buy_style.length == 2) {
            e.type = 3;
          } else {
            e.type = this.buy_style[0];
          }
          delete e.undefined;
          delete e.flag;
          e.pv = parseInt(e.pv);
          e.count = parseInt(e.count);
          temp.push(e);
        }
      });
      this.$http
        .post("/apaas/service/v3/service/manager/request/spcs/save", {
          service_id: parseInt(this.$route.params.id),
          data: temp,
        })
        .then((response) => {
          console.log(response);
          if (response.data.success) {
            this.$message.success("保存成功");
            this.sizeset_flag = false;
            this.getsize_arr();
          } else {
            this.$message.error("保存失败");
          }
        });
    },

    getServiceyxztInfo() {
      this.$http
        .get(
          `/apaas/istio/service/apaas-proxy/overview/apaas-proxy-${this.$route.params.id}`
        )
        .then((response) => {
          if (response.data.success) {
            let data = response.data.data;
            this.yx_state = {
              state: data.appState == "running" ? "运行中" : "等待中",
              averageTime: data.respTime.avg + "ms",
              maxTime: data.respTime.max + "ms",
              averageTraffic: data.throughput.avg + "dps",
              maxTraffic: data.throughput.max + "dps",
              memory: data.resource.memory + "MB",
            };
          }
        })
        .catch((response) => {
          this.yx_state = {
            state: "停止",
            averageTime: "0ms",
            maxTime: "0ms",
            averageTraffic: "0dps",
            maxTraffic: "0dps",
            memory: "0MB",
          };
        });
    },
  },
};
</script>

<style>
.savebtn .el-button {
  float: right;
  margin-left: 20px;
  letter-spacing: 2px;
}
.savebtn .el-button:nth-of-type(1) {
  background-color: #0f2683;
  color: #f8f9fd;
}
.savebtn .el-button:nth-of-type(2) {
  background-color: #c3caf8;
  color: #0f2683;
}
</style>
<style scoped>
.detail_contain {
  width: 100%;
  padding: 0 20px;
  height: calc(100% - 55px);
}
.info_contain {
  padding: 25px 20px;
  background-color: #fff;
  width: 100%;
  box-shadow: 0px 3px 6px 0px #f4f7fc;
  border-radius: 12px;
  min-height: calc(100% - 20px);
  margin-bottom: 20px;
}
.now_page_title {
  margin: 15px 0;
  color: #898d9e;
}
.now_page_title span {
  color: #242c43;
}
.type_box {
  width: 100%;
}
.type_title {
  width: 100%;
  height: 65px;
  line-height: 65px;
  border-bottom: 2px solid #f4f7fc;
}
.type_select {
  float: left;
  width: auto;
  margin-right: 40px;
  height: 65px;
  cursor: pointer;
}
.type_box_select {
  padding: 30px 10px 10px 10px;
  width: 100%;
}
.type_box_select >>> .outlist .list p {
  word-wrap: break-word;
}
.service_title {
  font-size: 16px;
  font-weight: bold;
  color: #58617a;
  text-align: left;
  height: 40px;
  line-height: 40px;
  margin-top: -10px;
  margin-bottom: 20px;
}
.service_title span {
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #515fe7;
  border-radius: 2px;
  float: left;
  margin-top: 13px;
  margin-right: 15px;
}
.service_title_card {
  width: 100%;
  overflow: hidden;
}
.service_card {
  width: calc((100% - 120px) / 4);
  margin-right: 40px;
  float: left;
}
.service_title_card .service_card:nth-last-of-type(1) {
  margin-right: 0px;
}
.service_num {
  text-align: center;
  padding-top: 10px;
}
.service_num p:nth-of-type(1) {
  font-size: 36px;
  color: #3f4f9c;
  margin-bottom: 10px;
}
.service_num p:nth-of-type(2) {
  font-size: 16px;
  color: #58617a;
}
.service_card_charts {
  width: 100%;
  margin-top: 30px;
  margin-bottom: 30px;
}
.editbtn {
  width: 124px;
  height: 44px;
  line-height: 44px;
  background-color: #0f2683;
  border-radius: 8px;
  font-size: 16px;
  color: #f8f9fd;
  text-align: center;
  cursor: pointer;
  margin-bottom: 30px;
}
.savebtn {
  margin-top: 50px;
  overflow: hidden;
}
</style>
