<template>
  <div class="service_management_list">
    <apass-list
      ref="list"
      search-placeholder="请输入关键字"
      :list-total="listTotal"
      :list-filter="filterList"
      :list-header="listHeader"
      :list-data="listData"
      :list-padding-left="35"
      @list-action="init"
    >
      <el-breadcrumb separator="/" slot="breadcrumb">
        <el-breadcrumb-item :to="`/fwgl/${level}`">我的服务</el-breadcrumb-item>
        <el-breadcrumb-item>{{ pathName }}</el-breadcrumb-item>
      </el-breadcrumb>
    </apass-list>

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

<script>
import { mapState } from "vuex";
import apassList from "@/components/apass-list";
import apassDialog from "@/components/apass-dialog";

export default {
  components: { apassList, apassDialog },
  data: () => ({
    level: 0, // 用户等级
    type: 0, // 访问的页面
    listTotal: 0,
    listHeader: [],
    listData: [],
    filterList: [],
    otherFilter: [],
    dialogInfo: {
      title: "",
      msg: "",
      submit: null,
    },
    listUrl: "",
    deleteUrl: "",
    tempFliter: null,
  }),
  computed: {
    ...mapState({
      fwglNav: "fwglNav",
    }),
    pathName() {
      return this.fwglNav[this.level][this.type];
    },
    detailsUrl() {
      let url = "";

      if (this.level == 0 && this.type == 1) {
        url = `/fwgl/${this.level}/${this.type}/applyserviceedit/`;
      } else {
        url = `/fwgl/${this.level}/${this.type}/servicedetail/`;
      }

      return url;
    },
  },
  methods: {
    initFilter() {
      Promise.all([
        this.$http.get("/apaas/service/v3/service/manager/servtype"),
        this.$http.get("/apaas/service/v3/service/manager/servarea"),
      ])
        .then((response) => {
          let data = response.map((item) => {
            return {
              name: item.body.data[0].type_name,
              prop: item.body.data[0].type_code,
              data: item.body.data.map((v) => ({
                name: v.name,
                value: v.id,
              })),
            };
          });

          this.filterList = [...data, ...this.otherFilter];
        })
        .catch((error) => {
          console.log(error);
        });
    },
    initHeader() {
      let _self = this;
      let level = this.level;
      let type = this.type;

      // 普通用户 --- 注册发布的服务
      if (level == 0 && type == 0) {
        this.listUrl = "/apaas/service/v3/service/manager/list";
        this.deleteUrl = "/apaas/service/v3/service/manager";
        this.listHeader = [
          {
            label: "服务名称",
            prop: "name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "服务领域",
            prop: "sectors_name",
            type: "",
            align: "center",
          },
          {
            label: "开放程度",
            prop: "openness_name",
            type: "",
            align: "center",
          },
          {
            label: "服务描述",
            prop: "descript",
          },
          {
            label: "注册发布时间",
            prop: "create_time",
            type: "",
            align: "center",
          },
          {
            label: "服务类型",
            prop: "data_service_type1_name",
            type: "",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 300,
            actionList: [
              {
                label: "编辑",
                callback: this.editItem,
              },
              {
                getLabel(item) {
                  return (
                    ["申请上架", "申请下架", "申请上架中"][item.state] || "-"
                  );
                },
                callback(item) {
                  if (item.state == 0) {
                    _self.applyForSoldUpItem(item);
                  } else if (item.state == 1) {
                    _self.applyForSoldOutItem(item);
                  }
                },
                disabledRule(item) {
                  return item.state == 2;
                },
              },
              {
                label: "删除",
                callback: this.deleteItem,
                class: "warn",
                disabledRule(item) {
                  return item.state != 2;
                },
              },
            ],
          },
        ];
        this.otherFilter = [
          {
            name: "开放程度",
            prop: "openness",
            data: [
              {
                name: "共享",
                value: 1,
              },
              {
                name: "受限",
                value: 2,
              },
              {
                name: "敏感",
                value: 3,
              },
            ],
          },
          {
            name: "服务状态",
            prop: "state",
            data: [
              {
                name: "上架中",
                value: 1,
              },
              {
                name: "已下架",
                value: 2,
              },
            ],
          },
        ];
      }
      // 普通用户 --- 申请的服务
      else if (level == 0 && type == 1) {
        this.listUrl = "/apaas/service/v3/service/apply/service/list";
        this.deleteUrl = "/apaas/service/v3/service/apply/service";
        this.listHeader = [
          {
            label: "服务名称",
            prop: "name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "服务领域",
            prop: "sectors_name",
            align: "center",
          },
          {
            label: "开放程度",
            prop: "openness_name",
            align: "center",
          },
          {
            label: "服务描述",
            prop: "descript",
          },
          {
            label: "申请时间",
            prop: "service_apply_info",
            getText(item) {
              return (
                (item.service_apply_info &&
                  item.service_apply_info.apply_time) ||
                ""
              );
            },
            align: "center",
          },
          {
            label: "服务类型",
            prop: "data_service_type1_name",
            align: "center",
          },
          {
            label: "申请状态",
            prop: "service_apply_info",
            getText(item) {
              return ["-", "待审批", "审批中", "审批通过", "审批未通过"][
                (item.service_apply_info &&
                  item.service_apply_info.approval_status) ||
                  0
              ];
            },
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            actionList: [
              {
                label: "删除",
                callback: this.deleteItem,
                disabledRule(item) {
                  return item.service_apply_info.approval_status === 1;
                },
              },
            ],
          },
        ];
        this.otherFilter = [
          {
            name: "开放程度",
            prop: "openness",
            data: [
              {
                name: "共享",
                value: 1,
              },
              {
                name: "受限",
                value: 2,
              },
              {
                name: "敏感",
                value: 3,
              },
            ],
          },
          {
            name: "申请状态",
            prop: "state",
            data: [
              {
                name: "待审批",
                value: 1,
              },
              {
                name: "审批中",
                value: 2,
              },
              {
                name: "审批通过",
                value: 3,
              },
              {
                name: "审批未通过",
                value: 4,
              },
            ],
          },
        ];
      }
      // TODO: 普通用户 --- 云资源服务
      else if (level == 0 && type == 2) {
        this.listUrl = "xxxxxx";
        this.listHeader = [
          {
            label: "工作区域",
            prop: "name",
          },
          {
            label: "网络环境",
            prop: "name",
            align: "center",
          },
          {
            label: "CPU（核）",
            prop: "name",
            align: "center",
          },
          {
            label: "内存（GB）",
            prop: "name",
            align: "center",
          },
          {
            label: "资源总量（GB）",
            prop: "name",
            align: "center",
          },
          {
            label: "实例数（个）",
            prop: "name",
            align: "center",
          },
          {
            label: "申请时间",
            prop: "name",
            align: "center",
          },
          {
            label: "申请状态",
            prop: "name",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                label: "查看详情",
                callback: this.detailItem,
              },
            ],
          },
        ];
      }

      // 组织管理员 --- 组织服务管理
      else if (level == 1 && type == 0) {
        this.listUrl = "/apaas/service/v3/service/manager/list";
        this.listHeader = [
          {
            label: "服务名称",
            prop: "name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "服务领域",
            prop: "sectors_name",
            align: "center",
          },
          {
            label: "开放程度",
            prop: "openness_name",
            align: "center",
          },
          {
            label: "请求方式",
            prop: "req_type",
            getText(item) {
              return ["-", "GET", "POST", "PUT", "DELETE"][item.req_type || 0];
            },
            align: "center",
          },
          {
            label: "服务描述",
            prop: "descript",
          },
          {
            label: "注册发布时间",
            prop: "create_time",
            align: "center",
          },
          {
            label: "服务类型",
            prop: "data_service_type1_name",
            align: "center",
          },
          {
            label: "服务状态",
            prop: "state",
            getText(item) {
              return ["已下架", "已上架", "上架中"][item.state];
            },
            align: "center",
          },
        ];
        this.otherFilter = [
          {
            name: "开放程度",
            prop: "openness",
            data: [
              {
                name: "共享",
                value: 1,
              },
              {
                name: "受限",
                value: 2,
              },
              {
                name: "敏感",
                value: 3,
              },
            ],
          },
          {
            name: "服务状态",
            prop: "state",
            data: [
              {
                name: "上架中",
                value: 1,
              },
              {
                name: "已下架",
                value: 2,
              },
            ],
          },
        ];
      }
      // 组织管理员 --- 服务审批管理
      else if (level == 1 && type == 1) {
        this.listUrl = "/apaas/service/v3/service/approval/applied/list";
        this.deleteUrl = "/apaas/service/v3/service/approval/applied";
        this.listHeader = [
          {
            label: "服务名称",
            prop: "name",
          },
          {
            label: "服务领域",
            prop: "sectors_name",
            align: "center",
          },
          {
            label: "开放程度",
            prop: "openness_name",
            align: "center",
          },
          {
            label: "请求方式",
            prop: "req_type",
            getText(item) {
              return ["-", "GET", "POST", "PUT", "DELETE"][item.req_type || 0];
            },
            align: "center",
          },
          {
            label: "服务描述",
            prop: "descript",
          },
          {
            label: "审批时间",
            prop: "service_apply_info",
            getText(item) {
              return (
                (item.service_apply_info &&
                  item.service_apply_info.approval_time) ||
                ""
              );
            },
            align: "center",
          },
          {
            label: "服务类型",
            prop: "data_service_type1_name",
            align: "center",
          },
          {
            label: "审批状态",
            prop: "service_apply_info",
            getText(item) {
              return ["-", "已审批", "待审批"][
                (item.service_apply_info &&
                  item.service_apply_info.approval_status) ||
                  0
              ];
            },
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                label: "审批",
                callback: this.approvalItem,
                disabledRule(item) {
                  return item.service_apply_info.approval_status === 1;
                },
              },
              {
                label: "删除",
                class: "warn",
                callback: this.deleteItem,
              },
            ],
          },
        ];
        this.otherFilter = [
          {
            name: "开放程度",
            prop: "openness",
            data: [
              {
                name: "共享",
                value: 1,
              },
              {
                name: "受限",
                value: 2,
              },
              {
                name: "敏感",
                value: 3,
              },
            ],
          },
          {
            name: "审批状态",
            prop: "state",
            data: [
              {
                name: "已审批",
                value: 1,
              },
              {
                name: "待审批",
                value: 2,
              },
            ],
          },
        ];
      }
      // TODO:组织管理员 --- 云资源管理
      else if (level == 1 && type == 2) {
        this.listUrl = "xxxxxx";
        this.listHeader = [
          {
            label: "工作区域",
            prop: "name",
          },
          {
            label: "网络环境",
            prop: "name",
            align: "center",
          },
          {
            label: "CPU（核）",
            prop: "name",
            align: "center",
          },
          {
            label: "内存（GB）",
            prop: "name",
            align: "center",
          },
          {
            label: "资源总量（GB）",
            prop: "name",
            align: "center",
          },
          {
            label: "实例数（个）",
            prop: "name",
            align: "center",
          },
          {
            label: "使用用户",
            prop: "name",
            align: "center",
          },
          {
            label: "用户申请时间",
            prop: "name",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                label: "分配",
                callback: this.allotItem,
              },
            ],
          },
        ];
      }

      // 超级管理员 --- 平台服务管理
      else if (level == 2 && type == 0) {
        this.listUrl = "/apaas/service/v3/service/manager/list";
        this.deleteUrl = "/apaas/service/v3/service/manager";
        this.listHeader = [
          {
            label: "服务名称",
            prop: "name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "服务领域",
            prop: "sectors_name",
            align: "center",
          },
          {
            label: "开放程度",
            prop: "openness_name",
            align: "center",
          },
          {
            label: "请求方式",
            prop: "req_type",
            getText(item) {
              return ["-", "GET", "POST", "PUT", "DELETE"][item.req_type || 0];
            },
            align: "center",
          },
          {
            label: "服务描述",
            prop: "descript",
          },
          {
            label: "注册发布时间",
            prop: "create_time",
            align: "center",
          },
          {
            label: "服务类型",
            prop: "data_service_type1_name",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 300,
            actionList: [
              {
                label: "编辑",
                callback: this.editItem,
              },
              {
                getLabel(item) {
                  return item.state == 1 ? "下架" : "上架";
                },
                callback(item) {
                  item.state == 1
                    ? _self.soldOutItem(item)
                    : _self.soldUpItem(item);
                },
                disabledRule(item) {
                  return item.state === 0;
                },
              },
              {
                label: "删除",
                class: "warn",
                callback: this.deleteItem,
              },
            ],
          },
        ];
        this.otherFilter = [
          {
            name: "开放程度",
            prop: "openness",
            data: [
              {
                name: "共享",
                value: 1,
              },
              {
                name: "受限",
                value: 2,
              },
              {
                name: "敏感",
                value: 3,
              },
            ],
          },
        ];
      }
      // 超级管理员 --- 服务审批管理
      else if (level == 2 && type == 1) {
        this.listUrl = "/apaas/service/v3/service/approval/applied/list";
        this.deleteUrl = "/apaas/service/v3/service/approval/applied";
        this.listHeader = [
          {
            label: "服务名称",
            prop: "name",
          },
          {
            label: "服务领域",
            prop: "sectors_name",
            align: "center",
          },
          {
            label: "开放程度",
            prop: "openness_name",
            align: "center",
          },
          {
            label: "请求方式",
            prop: "req_type",
            getText(item) {
              return ["-", "GET", "POST", "PUT", "DELETE"][item.req_type || 0];
            },
            align: "center",
          },
          {
            label: "服务描述",
            prop: "descript",
          },
          {
            label: "审批时间",
            prop: "service_apply_info",
            getText(item) {
              return (
                (item.service_apply_info &&
                  item.service_apply_info.approval_time) ||
                ""
              );
            },
            align: "center",
          },
          {
            label: "服务类型",
            prop: "data_service_type1_name",
            align: "center",
          },
          {
            label: "审批状态",
            prop: "service_apply_info",
            getText(item) {
              return ["-", "已审批", "待审批"][
                (item.service_apply_info &&
                  item.service_apply_info.approval_status) ||
                  0
              ];
            },
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                label: "审批",
                callback: this.approvalItem,
                disabledRule(item) {
                  return item.service_apply_info.approval_status === 1;
                },
              },
              {
                label: "删除",
                class: "warn",
                callback: this.deleteItem,
              },
            ],
          },
        ];
        this.otherFilter = [
          {
            name: "开放程度",
            prop: "openness",
            data: [
              {
                name: "共享",
                value: 1,
              },
              {
                name: "受限",
                value: 2,
              },
              {
                name: "敏感",
                value: 3,
              },
            ],
          },
          {
            name: "审批状态",
            prop: "state",
            data: [
              {
                name: "已审批",
                value: 1,
              },
              {
                name: "待审批",
                value: 2,
              },
            ],
          },
        ];
      }
      // TODO:超级管理员 --- 云资源管理
      else if (level == 2 && type == 2) {
        this.listUrl = "xxxxxx";
        this.listHeader = [
          {
            label: "所属组织",
            prop: "name",
          },
          {
            label: "CPU使用量",
            prop: "name",
            align: "center",
          },
          {
            label: "内存使用量",
            prop: "name",
            align: "center",
          },
          {
            label: "工作区域数量",
            prop: "name",
            align: "center",
          },
          {
            label: "创建时间",
            prop: "name",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            actionList: [
              {
                label: "删除",
                callback: this.deleteItem,
              },
            ],
          },
        ];
      }

      // Error
      else {
        throw Error("The page doesn't exist");
      }
    },
    init(filter) {
      this.tempFliter = filter;

      this.$http
        .get(this.listUrl, {
          params: {
            data_service_type:
              (filter.service_type_1 &&
                filter.service_type_1.map((item) => item.value).join(",")) ||
              "", // 服务类型
            sectors:
              (filter.service_area &&
                filter.service_area.map((item) => item.value).join(",")) ||
              "", // 服务领域
            openness:
              (filter.openness &&
                filter.openness.map((item) => item.value).join(",")) ||
              "", // 开放程度
            state:
              (filter.state &&
                filter.state.map((item) => item.value).join(",")) ||
              "", // 服务状态
            keyword: filter.keyword,
            page: filter.page,
            size: filter.size,
          },
        })
        .then(({ data }) => {
          // console.log(data.data);
          this.listTotal = data.data.total;
          this.listData = data.data.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    showDialog() {
      this.$refs.dialog.show();
    }, // 唤醒弹窗
    applyForSoldUpItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = "确认申请上架此服务吗？";
      this.dialogInfo.cancelText = "取消";
      this.dialogInfo.sunbmitText = "发送通知";
      this.dialogInfo.submit = () => {
        this.$http
          .post(`/apaas/service/v3/service/manager/send/upnotice`, {
            id: item.id,
          })
          .then(({ data }) => {
            if (data.success) {
              this.$message({
                message: data.errMsg,
                type: "success",
              });
              this.init(this.tempFliter);
            } else {
              this.$message({
                message: data.errMsg,
                type: "warning",
              });
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message({
              message: `申请${item.name}失败`,
              type: "warning",
            });
          });
      };
      this.showDialog();
    }, // 服务上架申请
    applyForSoldOutItem(item) {
      this.dialogInfo.title = "是否确定下架服务";
      this.dialogInfo.msg =
        "下架此服务会导致用户被迫暂停对服务的调用，下架前需向超级管理员发送通知，超级管理员通过后此服务将会从服务超市中下架。";
      this.dialogInfo.cancelText = "取消";
      this.dialogInfo.sunbmitText = "发送通知";
      this.dialogInfo.submit = () => {
        this.$http
          .post(`/apaas/service/v3/service/manager/send/downnotice`, {
            id: item.id,
          })
          .then(({ data }) => {
            if (data.success) {
              this.$message({
                message: data.errMsg,
                type: "success",
              });
              this.init(this.tempFliter);
            } else {
              this.$message({
                message: data.errMsg,
                type: "warning",
              });
            }
          })
          .catch((error) => {
            console.log(error);
            this.$message({
              message: `申请${item.name}失败`,
              type: "warning",
            });
          });
      };
      this.showDialog();
    }, // 服务下架申请
    soldUpItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = "确认上架此服务吗？";
      this.dialogInfo.cancelText = "";
      this.dialogInfo.sunbmitText = "确定";
      this.dialogInfo.submit = () => {
        this.$http
          .post(`/apaas/service/v3/service/manager/up`, {
            id: item.id,
          })
          .then(({ data }) => {
            if (data.success) {
              this.$message({
                message: data.errMsg,
                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();
    }, // 上架服务(超级管理员)
    soldOutItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg =
        "下架此服务会导致调用该服务的<br />用户被迫暂停对服务的调用";
      this.dialogInfo.cancelText = "";
      this.dialogInfo.sunbmitText = "确定";
      this.dialogInfo.submit = () => {
        this.$http
          .post(`/apaas/service/v3/service/manager/down`, {
            id: item.id,
          })
          .then(({ data }) => {
            if (data.success) {
              this.$message({
                message: data.errMsg,
                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();
    }, // 下架服务(超级管理员)
    deleteItem(item) {
      this.dialogInfo.title = "";
      this.dialogInfo.msg = "是否删除该条服务？";
      this.dialogInfo.cancelText = "";
      this.dialogInfo.sunbmitText = "";
      this.dialogInfo.submit = () => {
        this.$http
          .delete(this.deleteUrl, {
            params: {
              id: this.type == 1 ? item.service_apply_info.id : item.id,
            },
          })
          .then(({ data }) => {
            if (data.success) {
              this.$message({
                message: data.errMsg,
                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();
    }, // 删除服务
    detailItem(item) {
      this.$router.push(`${this.detailsUrl + item.id}`);
    }, // 查看服务
    editItem(item) {
      this.$router.push(
        `/fwgl/${this.level}/${this.type}/serviceedit/${item.id}`
      );
    }, // 编辑服务
    approvalItem(item) {
      this.$router.push(
        `/fwgl/${this.level}/${this.type}/approvalserviceedit/${item.service_apply_info.id}`
      );
    }, // 审批服务
    allotItem(item) {
      console.log("allotItem - " + item.name);
    }, // TODO: 云资源分配
  },
  created() {
    this.level = parseInt(this.$route.params.level);
    this.type = parseInt(this.$route.params.type);
    this.initHeader();
    this.initFilter();
  },
};
</script>

<style scoped>
.service_management_list {
  height: 100%;
}
</style>
