<template>
  <Module
    :loading="loading || comLoading"
    :error="error"
    :info="bsMeta && bsMeta['utilitiesDetail']"
    style="height: 30%"
  >
    <template #title class="facilityNumber">
      基础设施统计 - {{ activeBaseStructModel?.name }}
      <span class="business-detail-skip" @click="goBusinessDetail()">
        设施明细&nbsp;&nbsp;
        <i class="el-icon-caret-right"></i>
      </span>
    </template>
    <!-- <Ect
      :options="ectOpts"
      v-if="activeCom === 'list' && dataList?.length > 0"
    />-->
    <div style="width: 100%" v-if="dataList?.length > 0">
      <template
        v-if="activeBaseStructModel.name == '收费站' && selectLevel > 2"
      >
        <div class="s-table-head">
          <div class="flex-1 text-left pl-4">收费站名称</div>
          <div class="flex-1">ETC车道数量</div>
          <div class="flex-1">混合车道数量</div>
        </div>
        <div class="serveinfo-box">
          <vue-seamless-scroll :data="serveInfo">
            <div
              v-for="(item, index) in serveInfo"
              :key="index"
              class="s-table-th"
            >
              <div class="flex-1 flex items-center">
                <div class="jcsstj-num-top flex-shrink-0">
                  {{ index + 1 }}
                </div>
                <div
                  class="flex-1 whitespace-nowrap overflow-visible text-left"
                >
                  {{ item.stationName }}
                </div>
              </div>
              <div class="flex-1 text-white">{{ item.etcCount }}</div>
              <div class="flex-1 text-white">{{ item.mixCount }}</div>
            </div>
            <div class="serveinfo-box-list"></div>
          </vue-seamless-scroll>
        </div>
      </template>
      <template
        v-else-if="activeBaseStructModel.name == '服务区' && selectLevel > 2"
      >
        <div class="s-table-head">
          <div class="flex-1 text-left pl-4">服务区名称</div>
          <div class="flex-1">桩号</div>
        </div>
        <div class="serveinfo-box">
          <vue-seamless-scroll :data="serveInfo">
            <div
              v-for="(item, index) in serveInfo"
              :key="index"
              class="s-table-th"
            >
              <div class="flex-1 flex items-center">
                <div class="jcsstj-num-top flex-shrink-0">
                  {{ index + 1 }}
                </div>
                <div
                  class="flex-1 whitespace-nowrap overflow-visible text-left"
                >
                  {{ item.areaName }}
                </div>
                <div class="flex-1 text-white">{{ item.pegk }}</div>
              </div>
            </div>
            <div class="serveinfo-box-list"></div>
          </vue-seamless-scroll>
        </div>
      </template>
      <template v-else-if="activeBaseStructModel.name == '隧道' && selectLevel > 2">
        <div class="s-table-head">
          <div class="flex-1 text-left pl-4">隧道名称</div>
          <div class="flex-1">隧道类型</div>
          <div class="flex-1">隧道等级</div>
        </div>
        <div class="serveinfo-box">
          <vue-seamless-scroll :data="serveInfo">
            <div
              v-for="(item, index) in serveInfo"
              :key="index"
              class="s-table-th"
            >
              <div class="flex-1 flex items-center">
                <div class="jcsstj-num-top flex-shrink-0">
                  {{ index + 1 }}
                </div>
                <div
                  class="flex-1 whitespace-nowrap overflow-visible text-left"
                >
                  {{ item.tunnelName }}
                </div>
              </div>
              <div class="flex-1 text-white">{{ item.tunnelType }}</div>
              <div class="flex-1 text-white">{{ item.tunnelGrade }}</div>
            </div>
            <div class="serveinfo-box-list"></div>
          </vue-seamless-scroll>
        </div>
      </template>
      <div v-else style="width: 100%; overflow: auto">
        <div
          v-for="(item, index) in dataList"
          :key="index"
          class="jcsstj-outline flex justify-between items-center"
        >
          <div :class="index > 2 ? 'jcsstj-num' : 'jcsstj-num-top'">
            {{ index + 1 }}
          </div>
          <div class="jcsstj-text">
            {{ item.orgName ? item.orgName : item.orgname }}
          </div>
          <div :class="index > 0 ? 'jcsstj-blout' : 'jcsstj-blout-top'">
            <div
              :class="index > 0 ? 'jcsstj-bl' : 'jcsstj-bl-top'"
              :style="{
                width:
                  (maxCount
                    ? item[activeBaseStructModel.countKey] / maxCount
                    : 0) *
                    100 +
                  '%',
              }"
            ></div>
          </div>
          <div class="jcsstj-cont">
            {{ item[activeBaseStructModel.countKey] }}
          </div>
        </div>
      </div>
    </div>
    <Empty v-else />
  </Module>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { useStore } from "vuex";
import { key } from "@/store";
import { baseStructInfo, comInfo } from "@/store/state";
import { genConfig } from "@/utils/request";
import { useRequest } from "vue-request";
import { watch, defineProps } from "vue";
import { useGradient } from "@/utils/color";
import * as businessApi from "@/api/businessOverview";
import { getSideslopeCount, sideslopeCountChild } from "@/api/curingManage";
import { getLinke } from "@/api/chargeInfo";
import { generateKey } from "@/api/operation";
import vueSeamlessScroll from "@/components/vueSeamlessScroll/index.vue";
import ele from "../../store/modules/ele";
const store = useStore(key);

const emit = defineEmits(["goBusinessDetail"]);

const goBusinessDetail = async () => {
  let routeName = store.state.activeBaseStruct;
  // console.log("231行，暂时没有跳转");
  const ResData = await getLinke();
  const arr = ResData.msgContent.filter((item) => item.sysCode == "HY");
  const link = arr[0].url;
  generateKey().then((res) => {
    // console.log(101,routeName);
    // console.log("102y设施明细tok",res.data);
    // http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=sectionManagement

    if (routeName === "route") {
      return window.open(
        `http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=sectionManagement`
      );
    } //路段
    if (routeName === "brg") {
      return window.open(
        `http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=bridgeManagement`
      );
    } //桥梁
    if (routeName === "tunnel") {
      return window.open(
        `http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=tunnelManagement`
      );
    } //隧道
    if (routeName === "sideslope") {
      return window.open(
        `http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=sideSlopeManagement`
      );
    } //边坡
    if (routeName === "culvert") {
      return window.open(
        `http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=culvertManagement`
      );
    } //涵洞
    if (routeName === "huTong" || "stat" || "area") {
      let roadId = "";
      let companylds = "";
      if (selectLevel.value == 1 || selectLevel.value == 2) {
        companylds = selectRoadId.value[selectLevel.value - 1];
      }
      if (selectLevel.value == 3) {
        roadId = selectRoadId.value[selectLevel.value - 1];
      }
      let type = 1;
      if (routeName === "huTong") {
        type = 1;
      } else if (routeName === "stat") {
        type = 3;
      } else {
        type = 4;
      }
      return window.open(
        `http://183.64.175.153:8888/fvue/login?tokenKey=${res.data}&routerName=roadsideFacilitiesManagement&type=${type}&roadSegmentId=${roadId}&companylds=${companylds}`
      );
    } //沿路设施（收费站，服务区，互通）
  });
  //  window.open("//"+"192.168.10.240/ROUTE_STRUCT/manager-web-crcc/tree/master/src/components")
  //   emit("goDetail") // 发送事件
};

const activeCom = computed(() => store.state.activeCom);
const activeBaseStruct = computed(() => store.state.activeBaseStruct);
const bsMeta = computed(() => store.getters.bsMeta);

const activeBaseStructModel = computed(() => {
  const data = baseStructInfo.find((e) => e.code === activeBaseStruct.value);
  return data;
});

const modelKeys = computed(() => {
  if (!activeBaseStructModel.value?.children) {
    return new Array<any>({
      key: activeBaseStructModel.value?.key,
      name: activeBaseStructModel.value?.name,
    });
  } else {
    return activeBaseStructModel.value?.children?.map(({ key, name }: any) => ({
      key,
      name,
    }));
  }
});
const compare = (properties: any) => {
  return function (m: any, n: any) {
    var a = m[properties];
    var b = n[properties];
    return b - a; //降序
  };
};

const selectLevel = computed(() => store.state.road?.selectLevel);
const selectRoadId = computed(() => store.state.road?.selectRoadId);
const params = computed(() => selectLevel.value + "&" + selectRoadId.value);

// 收费站
const { data: stationCount, refresh: stationCountRefresh } = useRequest<any>(
  () =>
    selectLevel.value > 2
      ? businessApi.getStationCount(
          selectLevel.value,
          selectRoadId.value[selectLevel.value - 1]
        )
      : businessApi.stationCountQueryChild(
          selectLevel.value,
          selectRoadId.value[selectLevel.value - 1]
        )
);

// 收费站具体某条路的详情
const { data: stationLaneInfo, refresh: stationLaneInfoRefresh } =
  useRequest<any>(() =>
    businessApi.stationLaneInfo(
      selectLevel.value,
      selectRoadId.value[selectLevel.value - 1]
    )
  );

// 路段
const { data: sectionCount, refresh: sectionCountRefresh } = useRequest<any>(
  () =>
    selectLevel.value > 2
      ? businessApi.getSectionCount(
          selectLevel.value,
          selectRoadId.value[selectLevel.value - 1]
        )
      : businessApi.sectionCountlevelChild(
          selectLevel.value,
          selectRoadId.value[selectLevel.value - 1]
        )
);

// 服务区
const { data: serviceAreaCount, refresh: serviceAreaCountRefresh } =
  useRequest<any>(() =>
    selectLevel.value > 2
      ? businessApi.getServiceAreaCount(
          selectLevel.value,
          0,
          selectRoadId.value[selectLevel.value - 1]
        )
      : businessApi.serviceAreaCountQueryChild(
          selectLevel.value,
          0,
          selectRoadId.value[selectLevel.value - 1]
        )
  );

// 服务区具体某条路的详情
const { data: serviceAreaInfo, refresh: serviceAreaInfoRefresh } =
  useRequest<any>(() =>
    businessApi.serviceAreaInfo(
      selectLevel.value,
      selectRoadId.value[selectLevel.value - 1]
    )
  );

// 互通
const { data: hutongCount, refresh: huTongRefrese } = useRequest<any>(() =>
  selectLevel.value > 2
    ? businessApi.getHuTongCount(
        selectLevel.value,
        selectRoadId.value[selectLevel.value - 1]
      )
    : businessApi.hutongCountChild(
        selectLevel.value,
        selectRoadId.value[selectLevel.value - 1]
      )
);

// 隧道
const { data: tunnelCount, refresh: tunnelCountRefresh } = useRequest<any>(() =>
  selectLevel.value > 2
    ? businessApi.getTunnelCount(
        selectLevel.value,
        0,
        selectRoadId.value[selectLevel.value - 1]
      )
    : businessApi.tunnelCountQueryChild(
        selectLevel.value,
        selectRoadId.value[selectLevel.value - 1]
      )
);
// 隧道具体某条路的详情
const { data: tunnelInfo, refresh: tunnelInfoRefresh } = useRequest<any>(() =>
  businessApi.tunnelInfo(
    selectLevel.value,
    selectRoadId.value[selectLevel.value - 1]
  )
);

// 桥梁
const { data: bridgeCount, refresh: bridgeCountRefresh } = useRequest<any>(() =>
  selectLevel.value > 2
    ? businessApi.getBridgeCount(
        selectLevel.value,
        0,
        selectRoadId.value[selectLevel.value - 1]
      )
    : businessApi.bridgeCountQueryChild(
        selectLevel.value,
        selectRoadId.value[selectLevel.value - 1]
      )
);
// 边坡
const { data: sideslopeApiData, refresh: sideslopeApiRefresh } =
  useRequest<any>(() =>
    selectLevel.value > 2
      ? getSideslopeCount(
          selectLevel.value,
          0,
          selectRoadId.value[selectLevel.value - 1]
        )
      : sideslopeCountChild(
          selectLevel.value,
          0,
          selectRoadId.value[selectLevel.value - 1]
        )
  );

watch(params, () => {
  stationCountRefresh();
  stationLaneInfoRefresh();
  sectionCountRefresh();
  serviceAreaCountRefresh();
  serviceAreaInfoRefresh();
  tunnelCountRefresh();
  tunnelInfoRefresh();
  bridgeCountRefresh();
  sideslopeApiRefresh();
  huTongRefrese();
});

const serveInfo = computed(() => {
  switch (activeBaseStructModel.value?.name) {
    case "收费站":
      return stationLaneInfo.value?.msgContent;
    case "服务区":
      return serviceAreaInfo.value?.msgContent;
    case "隧道":
      return tunnelInfo.value?.msgContent;
  }
});
const dataList = computed(() => {
  let list = new Array();
  switch (activeBaseStructModel.value?.name) {
    case "收费站":
      list = stationCount.value?.msgContent;
      break;
    case "服务区":
      list = serviceAreaCount.value?.msgContent;
      break;
    case "隧道":
      list = tunnelCount.value?.msgContent;
      break;
    case "桥梁":
      list = bridgeCount.value?.msgContent;
      break;
    case "边坡":
      list = sideslopeApiData.value?.msgContent;
      break;
    case "互通":
      list = hutongCount.value?.msgContent;
      break;
    case "路段":
      list = sectionCount.value?.msgContent;
      break;
    default:
      break;
  }
  const countKey = activeBaseStructModel.value?.countKey;
  list && (list as Array<any>).sort(compare(countKey));
  // console.log("list", list, countKey);
  return list;
});
const totalCount = computed(() => {
  let total = dataList.value
    .map((e: any) => Number(e[activeBaseStructModel.value?.countKey]))
    ?.reduce((a: number, b: number) => a + b);
  // console.log(total);
  return total;
});

const maxCount = computed(() => {
  const counts = dataList.value.map((e: any) =>
    Number(e[activeBaseStructModel.value?.countKey])
  );
  const maxCount = counts.length ? Math.max(...counts) : 0;
  return maxCount;
});

const staticOptions = {
  color: [
    useGradient("blue"),
    useGradient("red"),
    useGradient("yellow"),
    useGradient("green"),
  ],
  tooltip: {
    trigger: "axis",
    backgroundColor: "rgba(0,0,0,0.8)",
    borderColor: "#000",
    axisPointer: {
      type: "shadow",
    },
    textStyle: {
      fontSize: 12,
      color: "#fff",
    },
  },
  xAxis: {
    splitNumber: 3,
    splitLine: {
      show: true,
      lineStyle: {
        color: "rgba(0, 154, 248,.5)",
        width: "1",
      },
    },
    axisLine: {
      lineStyle: {
        color: "#009EFF",
      },
    },
    axisLabel: {
      show: true,
      fontSize: 10,
    },
  },
  yAxis: {
    type: "category",
    inverse: true,
    axisLine: {
      lineStyle: {
        color: "#01A3FF",
        width: "1",
      },
    },
    axisTick: {
      alignWithLabel: true,
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: "rgba(0, 154, 248,.5)",
        width: "1",
      },
    },
    axisLabel: {
      fontSize: 12,
      fontWeight: "400",
    },
  },
};

const staticSeriesOptions = {
  type: "bar",
  stack: "总量",
  barWidth: "40%",
  itemStyle: {
    opacity: 1,
    shadowColor: "rgba(0, 0, 0, .8)",
    shadowBlur: 4,
    shadowOffsetY: 1,
    shadowOffsetX: 2,
    borderColor: "#fff",
    borderWidth: 1,
  },
};

const ectOpts = computed(() => {
  const labelPos = modelKeys.value?.length > 1 ? "bottom" : "right";
  const options: any = {
    legend: {
      show: modelKeys.value?.length > 1,
      itemGap: 20,
      x: 90,
      y: 10,
      textStyle: {
        color: "#ffffff",
      },
    },
    grid: {
      top: modelKeys.value?.length > 1 ? 50 : 12,
      left: 90,
      bottom: 30,
      right: 40,
    },
    dataset: {
      source: dataList.value,
      dimensions: ["orgName", ...modelKeys.value?.map((e) => e.key)],
    },
    series: modelKeys.value?.map(({ name, key }: any) => {
      return {
        name,
        encode: {
          x: key,
          y: "orgName",
        },
        label: {
          show: true,
          position: labelPos,
          color: "#fff",
          lineHeight: 12,
          fontSize: 12,
          fontFamily: "sans-serif",
          verticalAlign: "middle",
          borderRadius: 2,
          offset: labelPos === "bottom" ? [0, 10] : [0, 0],
          backgroundColor: "rgba(0,0,0,0.2)",
          padding: [2, 4],
        },
        ...staticSeriesOptions,
      };
    }),
    ...staticOptions,
  };
  return options;
});

// 公司基础设施列表
const {
  run: comRun,
  data: comData,
  loading: comLoading,
  error: comError,
} = useRequest<any>(
  () =>
    genConfig(
      `/http-server-yygl/publish/jsc/baseStructDetail?com=${activeCom.value}&type=${activeBaseStruct.value}`
    ),
  {
    manual: true,
  }
);

const baseStructDetail = computed(() => comData.value?.msgContent);

watch(
  [activeCom, activeBaseStruct],
  () => {
    if (activeCom.value !== "list") {
      comRun();
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="scss" scoped>
.serveinfo-box {
  width: 100%;
  height: 240px;
}
.s-table-head {
  display: flex;
  padding: 4px 0;
  //   border-right: 1px solid #2f64a5;
  border-bottom: 1px dashed #2f64a5;
  font-size: 13px;
  font-weight: bold;
  color: #C2DEFD;
  text-align: center;
  background: center url(./images/sub-title-bg.png);
  background-size: 100% 100%;
}
.s-table-th {
  display: flex;
  border-top: 1px dashed #2f64a5;
  padding: 4px 0;
  font-size: 13px;
  color: #c4cfdb;
  text-align: center;
  &:first-child {
    border-top: none;
  }
  &:nth-child(2n) {
    background-color: rgba(0,132,251, 0.05);
  }
}
.serveinfo-box-list {
  width: 100%;

  /* overflow: auto; */
}
.s-table-head .s-table-head-top {
  width: 99%;
  //   border-top: 1px solid #2f64a5;
}
.sth-t1 {
  width: 34%;
}
.sth-t2 {
  width: 33%;
}
.sth-t3 {
  width: 33%;
}
.facilityNumber {
  position: relative;
}
.business-detail-skip {
  position: absolute;
  right: 20px;
  cursor: pointer;
}
.com-data-list {
  @apply absolute inset-0 overflow-x-hidden overscroll-y-auto flex flex-col p-0.5;
}

.com-data-item {
  @apply p-0.5;
}

.item {
  background: linear-gradient(
    to left top,
    rgba(0, 59, 88, 0.3),
    rgba(0, 70, 105, 1)
  );
  border: 1px solid rgba(7, 133, 196, 0.4);

  @apply w-full rounded-sm flex items-center px-2 py-2;

  & .svg-icon {
    font-size: 25px;
    color: rgba(255, 255, 255, 0.5);
  }
}

.dataWarp {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-end;
  text-shadow: none;
  margin-left: auto;
  font-size: 14px;
}

.prop + .prop {
  margin-top: 5px;
}

.prop:nth-child(2) {
  color: rgb(0, 180, 224);
}
.jcsstj-outline {
  margin-top: 10px;
  margin-bottom: 8px;
}
.jcsstj-num-top {
  width: 20px;
  height: 24px;
  font-size: 13px;
  font-weight: bold;
  color: #ff9a00;
  background: url("@/assets/images/jcsstj-top-num.png");
  background-size: 100% 100%;
  text-align: center;
  line-height: 24px;
  font-style: oblique;
  margin-right: 10px;
  padding-right: 2px;
}
.jcsstj-num {
  width: 20px;
  height: 24px;
  font-size: 13px;
  font-weight: bold;
  color: #badeff;
  width: 20px;
  height: 24px;
  text-align: center;
  line-height: 24px;
  font-style: oblique;
  margin-right: 10px;
  padding-right: 2px;
}
.jcsstj-text {
  font-size: 14px;
  color: #909fac;
  width: 90px;
}
.jcsstj-blout-top {
  width: calc(100% - 170px);
  height: 12px;
  padding: 3px;
  /* border: 1px solid red; */
  border: 1px solid rgba(255, 154, 0, 0.15);
  background: rgba(255, 154, 0, 0.1);
}
.jcsstj-blout {
  width: calc(100% - 180px);
  height: 12px;
  padding: 3px;
  border: 1px solid rgba(0, 132, 251, 0.25);
  background: rgba(0, 132, 251, 0.1);
}
.jcsstj-bl-top {
  height: 4px;
  background: #ff9a00;
}
.jcsstj-bl {
  height: 4px;
  background: #0084fb;
}
.jcsstj-cont {
  font-size: 16px;
  color: #ffdaa5;
  width: 50px;
  margin-left: 10px;
}
</style>
