<template>
  <div class="organization_cloud_resource">
    <apass-list
      ref="list"
      search-placeholder="请输入关键字"
      :other-filter="otherFilter"
      :list-header="listHeader"
      :list-data="listData"
      :list-total="listTotal"
      @list-action="init"
      :list-padding-left="0"
    >
      <el-breadcrumb separator="/" slot="breadcrumb">
        <el-breadcrumb-item :to="`/fwgl/${level}`">
          我的服务
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="`/fwgl/${level}/${type}`">
          云资源管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          组织云资源详情
        </el-breadcrumb-item>
      </el-breadcrumb>

      <template slot="main-top">
        <div
          class="dashboard_contaner"
          v-if="dashboardList && dashboardList.length > 1"
        >
          <div
            class="dashborad_list"
            v-for="(item, index) in dashboardList"
            :key="index"
          >
            <chart
              :options="getDashboardOption(item)"
              class="dashboard_chart"
            />
            <p class="dashboard_info">
              <span>物理总量</span>
              <span v-text="item.total + item.unit"></span>
            </p>
            <p class="dashboard_info">
              <span>剩余量</span>
              <span v-text="item.value + item.unit"></span>
            </p>
          </div>
        </div>
      </template>
    </apass-list>

    <apass-dialog
      ref="dialog"
      :title="dialogInfo.title"
      :msg="dialogInfo.msg"
      :cancel-hide="dialogInfo.cancelHide"
      :submit="dialogInfo.submit"
    ></apass-dialog>
  </div>
</template>

<script>
import { graphic } from "echarts/lib/export";
import helper from "@/services/helper.js";
import apassList from "@/components/apass-list";
import apassDialog from "@/components/apass-dialog";

export default {
  components: {
    apassList,
    apassDialog,
  },
  data: () => ({
    level: 0, // 用户等级
    type: 0, // 访问的页面
    otherFilter: [],
    listHeader: [],
    listData: [],
    listTotal: 0,
    dashboardList: [],
    dialogInfo: {
      msg: "",
      cancelHide: false,
      submit: null,
    },
    tempFilter: null,
  }),
  computed: {},
  methods: {
    init(filter) {
      // console.log(filter);

      this.tempFilter = filter;

      this.$http
        .get("/apaas/service/v3/resource/user/apply/list", {
          params: {
            search: filter.keyword,
            page: filter.page,
            limit: filter.size,
            depart: filter.depart,
          },
        })
        .then(({ data }) => {
          this.listTotal = data.total;
          this.listData = data.data.cloud_apply_list;

          const cloud = data.data.cloud_resource_count;
          this.dashboardList = [
            {
              name: "CPU使用量",
              value: cloud.cpu_use,
              total: cloud.cpu_total,
              unit: "（核）",
            },
            {
              name: "内存使用量",
              value: cloud.memory_use,
              total: cloud.memory_total,
              unit: "（GB）",
            },
            /* {
              name: "数据盘使用量",
              value: cloud.disk_use,
              total: cloud.disk_total,
              unit: "（GB）",
            }, */
            {
              name: "容器组使用量",
              value: cloud.containers_use,
              total: cloud.containers_total,
              unit: "（个）",
            },
          ];
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getOrganizations() {
      this.$http
        .get("/apaas/backmgt/department/list")
        .then(({ data }) => {
          if (data.success == 1) {
            let organizations = data.data || [];

            this.otherFilter = [
              {
                name: "组织名称",
                prop: "depart",
                default: this.$route.params.id,
                options: organizations.map((item) => ({
                  name: item.department_name,
                  value: item.department_id,
                })),
              },
            ];
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getDashboardOption(item) {
      let percent = Math.round((item.value / item.total) * 100) || 0;
      let colors = ["#515fe7", "#e7ecfd"];

      if (percent >= 80) {
        colors = ["#e3606d", "#f6d0d0"];
      }

      return {
        title: {
          text: percent + "%",
          subtext: item.name,
          x: "center",
          y: "center",
          textVerticalAlign: "auto",
          textStyle: {
            fontSize: 34,
            fontWeight: "100",
            color: ["#0d1847"],
          },
          subtextStyle: {
            fontSize: 12,
            fontWeight: "100",
            color: "#707693",
          },
        },
        angleAxis: {
          axisLine: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          min: 0,
          max: 138,
          boundaryGap: ["0", "100"],
          startAngle: 220,
          endAngle: -40,
        },
        radiusAxis: {
          type: "category",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            show: false,
          },
        },
        polar: {
          radius: "110%",
        },
        series: [
          {
            type: "bar",
            data: [, percent],
            coordinateSystem: "polar",
            barMaxWidth: 10,
            z: 1,
            name: "B",
            roundCap: true,
            itemStyle: {
              normal: {
                color: new graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: colors[0] },
                  { offset: 1, color: colors[1] },
                ]),
              },
            },
            barGap: "-100%",
          },
          {
            type: "bar",
            data: [, 100],
            z: 0,
            silent: true,
            coordinateSystem: "polar",
            barMaxWidth: 10,
            name: "C",
            roundCap: true,
            color: "#ddd",
            barGap: "-100%",
          },
          {
            type: "gauge",
            radius: "70%",
            min: 0, //最小刻度
            max: 100, //最大刻度
            splitNumber: 10, //刻度数量
            startAngle: 220,
            endAngle: -40,
            axisLabel: {
              show: false,
            },
            axisLine: {
              show: true,
              lineStyle: {
                width: 0.5,
                color: [[1, "rgba(0,0,0,0)"]],
              },
            }, //仪表盘轴线
            axisLabel: {
              show: false,
            }, //刻度标签。
            axisTick: {
              show: true,
              splitNumber: 5,
              lineStyle: {
                color: "#e3e4ea",
                width: 0.5,
              },
              length: 3,
            }, //刻度样式
            splitLine: {
              show: true,
              length: 4,
              lineStyle: {
                color: "#e3e4ea",
                width: 0.5,
              },
            }, //分隔线样式
            detail: {
              show: false,
            },
            pointer: {
              show: false,
            },
          },
          {
            name: "point",
            type: "scatter",
            coordinateSystem: "polar",
            barGap: "-100%",
            zlevel: 0,
            symbol: "circle",
            symbolSize: 6,
            itemStyle: {
              normal: {
                show: true,
                color: "#fff",
              },
            },

            data: [, percent],
          },
        ],
      };
    },
    showDialog() {
      this.$refs.dialog.show();
    },
    detailAction(item) {
      this.$router.push({
        path: `/fwgl/${this.level}/${this.type}/cloud_detail/${item.id}`,
        query: {
          apply_id: item.apply_id,
          apply_type: item.apply_type,
          use_uid: item.use_uid,
          user_id: item.user_id,
        },
      });
    },
    stateAction(item) {
      let action = (type, cb) => {
        this.$http
          .put("/apaas/service/v3/resource/apply/disable", null, {
            params: {
              id: item.id,
              type,
            },
          })
          .then(({ data }) => {
            if (data.success == 1) {
              typeof cb == "function" && cb();
              this.init(this.tempFilter);
            } else {
              this.$message({
                message: data.errMsg || "操作失败",
                type: "warning",
              });
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message({
              message: "操作失败",
              type: "warning",
            });
          });
      };

      if (item.state == 1) {
        this.dialogInfo.msg = "您确认要禁用该工作区域吗？";
        this.dialogInfo.cancelHide = false;
        this.dialogInfo.submit = () => {
          action(0, () => {
            this.dialogInfo.msg = `该工作区域已被禁用，普通用户与组织管理员依旧能查看该工作区域，但无法做任何操作。`;
            this.dialogInfo.cancelHide = true;
            this.dialogInfo.submit = null;
            this.showDialog();
          });
        };
        this.showDialog();
      } else {
        this.dialogInfo.msg = "您确认要启用该工作区域吗？";
        this.dialogInfo.cancelHide = false;
        this.dialogInfo.submit = () => {
          action(1, () => {
            this.$message({
              message: "该工作区域已被启用",
              type: "success",
            });
          });
        };
        this.showDialog();
      }
    },
    deleteAction(item) {
      this.dialogInfo.msg = `
        您确认要移除该工作区域吗？</br>
        <span style='color: #e15260;'>移除操作无法撤销</span>，您还要继续吗？
      `;
      this.dialogInfo.cancelHide = false;
      this.dialogInfo.submit = () => {
        this.$http
          .delete("/apaas/service/v3/resource/apply/remove", {
            params: {
              id: item.id,
              name_space: item.name_space,
              use_uid: item.use_uid,
            },
          })
          .then(({ data }) => {
            if (data.success) {
              this.$message({
                message: data.errMsg || `删除${item.name_space}成功.`,
                type: "success",
              });
              this.init(this.tempFliter);
            } else {
              this.$message({
                message: data.errMsg,
                type: "warning",
              });
            }
          })
          .catch((error) => {
            this.$message({
              message: `删除${item.name}失败.`,
              type: "warning",
            });
          });
      };
      this.showDialog();
    },
  },
  created() {
    this.level = parseInt(this.$route.params.level);
    this.type = parseInt(this.$route.params.type);

    this.getOrganizations();

    this.listHeader = [
      {
        label: "运行状态",
        align: "center",
        type: "image",
        getImage(item) {
          return item.state == 1
            ? require("@/assets/imgs/ic_true.png")
            : require("@/assets/imgs/ic_failed.png");
        },
      },
      {
        label: "工作区域名称",
        prop: "name_space",
        type: "button",
        callback: this.detailAction,
      },
      {
        label: "CPU（核）",
        prop: "cpu",
        align: "center",
      },
      {
        label: "内存（GB）",
        prop: "memory",
        align: "center",
      },
      {
        label: "容器组（个）",
        prop: "containers",
        align: "center",
      },
      {
        label: "数据盘（块/GB）",
        type: "tooltip",
        align: "center",
        getLength(item) {
          let disks = (item.disk && item.disk.trim().split(" ")) || [];
          return disks.length;
        },
        getText(item) {
          let disks = (item.disk && item.disk.trim().split(" ")) || [];
          return disks[0];
        },
        getContent(item) {
          let disks = (item.disk && item.disk.trim().split(" ")) || [];
          let htmlStr = `<span>数据盘（块/GB）</span><br />`;

          disks.forEach((v) => {
            htmlStr += `<span>数据盘：${v}</span><br />`;
          });

          return htmlStr;
        },
      },
      {
        label: "申请用户",
        prop: "user_name",
        align: "center",
      },
      {
        label: "业务系统名",
        prop: "system_name",
        align: "center",
      },
      {
        label: "用户申请时间",
        prop: "apply_time",
        align: "center",
      },
      {
        label: "操作",
        type: "buttons",
        align: "center",
        width: 160,
        actionList: [
          {
            getLabel(item) {
              return item.state == 1 ? "禁用" : "启用";
            },
            callback: this.stateAction,
          },
          {
            label: "移除",
            class: "warn",
            callback: this.deleteAction,
          },
        ],
      },
    ];
  },
};
</script>

<style scoped>
.organization_cloud_resource {
  height: 100%;
}
.dashboard_contaner {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 20px;
}
.dashborad_list {
  text-align: center;
  margin: 0 25px;
  font-size: 18px;
}
.dashboard_chart {
  width: 136px;
  height: 136px;
}
.dashboard_info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  line-height: 30px;
  color: #8890a7;
}
.dashboard_info:nth-of-type(1) {
  margin-top: -10px;
}
.dashboard_info > span:nth-of-type(2) {
  color: #0d1847;
}
</style>
