<template>
  <div class="app_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="initDatas"
    >
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>我的应用</el-breadcrumb-item>
        <el-breadcrumb-item>{{ pathName }}</el-breadcrumb-item>
      </el-breadcrumb>

      <app-list
        v-if="listType === 'card'"
        slot="list"
        :data="listData"
        :card-type="cardType"
        @deployment-action="deploymentAction"
        @delete-action="deleteAction"
        :details-url="detailsUrl"
      ></app-list>
    </apass-list>

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

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

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

      if (this.type == 0) {
        url = `/yygl/${this.level}/${this.type}/detail/`;
      } else if (this.type == 1) {
        url = `/yygl/${this.level}/${this.type}/deploydetail/`;
      } else {
        if (this.level === 0) {
          url = `/yygl/${this.level}/${this.type}/applydetail/`;
        } else {
          url = `/yygl/${this.level}/${this.type}/approvaldetail/`;
        }
      }

      return url;
    },
  },
  methods: {
    initHeader() {
      let level = this.level;
      let type = this.type;
      let _self = this;

      // 普通用户 --- 应用仓库 card列表形式
      if (level === 0 && type === 0) {
        this.listType = "card";
        this.cardType = 0;
        this.otherFilter1 = [
          {
            name: "在线状态",
            prop: "online_state",
            data: [
              {
                name: "平台应用",
                value: 1,
              },
              {
                name: "开发者应用",
                value: 2,
              },
              {
                name: "未上架",
                value: 0,
              },
            ],
          },
        ];
        this.otherFilter2 = [
          {
            name: "是否支持开发",
            prop: "developable",
            data: [
              {
                name: "支持开发",
                value: 1,
              },
              {
                name: "不支持开发",
                value: 0,
              },
            ],
          },
          {
            name: "应用来源",
            prop: "appSource",
            data: [
              {
                name: "创建的应用",
                value: 0,
              },
              {
                name: "申请的应用",
                value: 1,
              },
            ],
          },
        ];
      }
      // 普通用户 --- 我部署的应用
      else if (level === 0 && type === 1) {
        this.listType = "card";
        this.cardType = 1;
        this.otherFilter1 = [
          {
            name: "部署来源",
            prop: "online_state",
            data: [
              {
                name: "应用商店",
                value: 0,
              },
              {
                name: "开发者应用",
                value: 1,
              },
            ],
          },
        ];
        this.otherFilter2 = [
          {
            name: "是否支持开发",
            prop: "developable",
            data: [
              {
                name: "支持开发",
                value: 1,
              },
              {
                name: "不支持开发",
                value: 0,
              },
            ],
          },
          {
            name: "应用来源",
            prop: "appSource",
            data: [
              {
                name: "创建的应用",
                value: 0,
              },
              {
                name: "申请的应用",
                value: 1,
              },
            ],
          },
        ];
      }
      // 普通用户 --- 申请的应用 card列表形式
      else if (level === 0 && type === 2) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "在线区域",
            prop: "online_state_name",
            align: "center",
          },
          {
            label: "申请类型",
            prop: "apply_type_name",
            align: "center",
          },
          {
            label: "申请时间",
            prop: "time",
            getText(item) {
              let time = item.time || "";
              return time.substring(0, 10);
            },
            align: "center",
          },
          {
            label: "申请状态",
            prop: "apply_status",
            align: "center",
          },
        ];
        this.otherFilter1 = [
          {
            name: "在线区域",
            prop: "online_state",
            data: [
              {
                name: "平台应用",
                value: 1,
              },
              {
                name: "开发者应用",
                value: 2,
              },
            ],
          },
        ];
        this.otherFilter2 = [
          {
            name: "申请类型",
            prop: "apply_type",
            data: [
              {
                name: "申请部署",
                value: 1,
              },
              {
                name: "申请开发",
                value: 2,
              },
            ],
          },
          {
            name: "申请状态",
            prop: "apply_state",
            data: [
              {
                name: "审批中",
                value: 1,
              },
              {
                name: "审批通过",
                value: 2,
              },
              {
                name: "审批未通过",
                value: 2,
              },
            ],
          },
          {
            name: "应用来源",
            prop: "appSource",
            data: [
              {
                name: "创建的应用",
                value: 0,
              },
              {
                name: "申请的应用",
                value: 1,
              },
            ],
          },
        ];
      }
      /* // 普通用户 --- 审批的应用
      else if (level === 0 && type === 3) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称", prop: "name", type: "href", align: "left" },
          {
            label: "应用版本", prop: "date", align: "center" },
          {
            label: "应用类型", prop: "address", align: "center" },
          {
            label: "业务领域", prop: "address", align: "center" },
          {
            label: "在线区域", prop: "address", align: "center" },
          {
            label: "申请类型", prop: "address", align: "center" },
          {
            label: "审批时间", prop: "address", align: "center" },
          {
            label: "审批状态", prop: "address", align: "center" },
          {
            label: "操作",
            type: "Button",
            align: "center",
            width: 160,
            btnList: [
              {
                type: "action-approval",
                label: "审批",
                line: "|",
              },
              {
                type: "action-delete",
                label: "删除",
              },
            ],
          },
        ];
      } */

      // 组织管理员 --- 应用仓库管理
      else if (level === 1 && type === 0) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "在线状态",
            prop: "online_state",
            align: "center",
          },
          {
            label: "创建时间",
            prop: "create_date",
            getText(item) {
              let time = item.create_date || "";
              return time.substring(0, 10);
            },
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                getLabel(item) {
                  return item.online_state == 0 ? "上架" : "下架";
                },
                callback(item) {
                  item.online_state == 0
                    ? _self.soldUpItem(item)
                    : _self.soldOutItem(item);
                },
                disabledRule(item) {
                  return item.online_state == 2;
                },
              },
            ],
          },
        ];
      }
      // 组织管理员 --- 部署的应用
      else if (level === 1 && type === 1) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "上架区域",
            prop: "address",
            align: "center",
          },
          {
            label: "部署时间",
            prop: "address",
            align: "center",
          },
          {
            label: "部署区域",
            prop: "address",
            align: "center",
          },
        ];
      }
      // 组织管理员 --- 应用审批管理
      else if (level === 1 && type === 2) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "在线区域",
            prop: "online_state_name",
            align: "center",
          },
          {
            label: "申请类型",
            prop: "apply_type_name",
            align: "center",
          },
          {
            label: "审批时间",
            prop: "apply_date",
            align: "center",
          },
          {
            label: "申请状态",
            prop: "apply_status",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                label: "审批",
                callback: this.approvalItem,
              },
              {
                label: "删除",
                class: "warn",
                callback: this.deleteItem,
              },
            ],
          },
        ];
      }

      // 超级管理员 --- 平台应用管理
      else if (level === 2 && type === 0) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "在线状态",
            prop: "online_state",
            align: "center",
          },
          {
            label: "所属组织",
            prop: "address",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 240,
            actionList: [
              {
                label: "编辑",
                callback: _self.editItem,
              },
              {
                label: "下线",
                callback: _self.offLine,
              },
              {
                label: "删除",
                callback: _self.deleteItem,
              },
            ],
          },
        ];
      }
      // 超级管理员 --- 应用部署管理
      else if (level === 2 && type === 1) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "上架区域",
            prop: "address",
            align: "center",
          },
          {
            label: "所属组织",
            prop: "address",
            align: "center",
          },
          {
            label: "部署时间",
            prop: "address",
            align: "center",
          },
          {
            label: "部署区域",
            prop: "address",
            align: "center",
          },
        ];
      }
      // 超级管理员 --- 应用审批管理
      else if (level === 2 && type === 2) {
        this.listType = "table";
        this.listHeader = [
          {
            label: "应用名称",
            prop: "app_name",
            type: "button",
            callback: this.detailItem,
          },
          {
            label: "应用版本",
            prop: "version",
            align: "center",
          },
          {
            label: "应用类型",
            prop: "type_name",
            align: "center",
          },
          {
            label: "业务领域",
            prop: "ywly_name",
            align: "center",
          },
          {
            label: "在线区域",
            prop: "online_state_name",
            align: "center",
          },
          {
            label: "申请类型",
            prop: "apply_type_name",
            align: "center",
          },
          {
            label: "审批时间",
            prop: "apply_date",
            align: "center",
          },
          {
            label: "申请状态",
            prop: "apply_status",
            align: "center",
          },
          {
            label: "操作",
            type: "buttons",
            align: "center",
            width: 160,
            actionList: [
              {
                label: "审批",
                callback: this.approvalItem,
              },
              {
                label: "删除",
                class: "warn",
                callback: this.deleteItem,
              },
            ],
          },
        ];
      }

      // Error
      else {
        throw Error("The page doesn't exist");
      }
    },
    initFilter() {
      let level = this.level;
      let type = this.type;
      let urls = [
        {
          path: "/apaas/hubApi/market/appTypes",
          callback(response) {
            let datas = [];

            datas = response.body.data.map((v) => ({
              name: v.name,
              value: v.id,
            }));

            return {
              name: "应用类型",
              prop: "appTypes",
              data: datas,
            };
          },
        },
        {
          path: "/apaas/hubApi/market/businessAreas",
          callback(response) {
            let datas = [];

            datas = response.body.data.map((v) => ({
              name: v.name,
              value: v.id,
            }));

            return {
              name: "业务领域",
              prop: "businessArea",
              data: datas,
            };
          },
        },
      ];

      Promise.all(urls.map((url) => this.$http.get(url.path)))
        .then((responses) => {
          let filterList = responses.map((response, index) => {
            return urls[index].callback(response);
          });

          this.filterList = [
            ...this.otherFilter1,
            ...filterList,
            ...this.otherFilter2,
          ];
        })
        .catch((error) => {
          console.log(error);
        });
    },
    initDatas(filter) {
      let listUrl = [
        "/apaas/hubApi/market/list",
        "/apaas/hubApi/market/deployList",
        "/apaas/hubApi/market/applyList",
      ];
      let params = {};

      if (filter.online_state) {
        params.online_state = filter.online_state
          .map((item) => {
            return item.value;
          })
          .join(",");
      } // 在线状态
      if (filter.appTypes) {
        params.appTypes = filter.appTypes
          .map((item) => {
            return item.value;
          })
          .join(",");
      } // 应用类型
      if (filter.businessArea) {
        params.businessArea = filter.businessArea
          .map((item) => {
            return item.value;
          })
          .join(",");
      } // 业务领域
      if (filter.developable) {
        params.developable = filter.developable
          .map((item) => {
            return item.value;
          })
          .join(",");
      } // 是否支持开发
      if (filter.appSource) {
        params.appSource = filter.appSource
          .map((item) => {
            return item.value;
          })
          .join(",");
      } // 应用来源

      this.tempFliter = filter;

      this.$http
        .get(listUrl[this.type], {
          params: {
            ...params,
            search: filter.keyword,
            page: filter.page,
            limit: filter.size,
          },
        })
        .then(({ data }) => {
          this.listTotal = data.total;
          this.listData = data.data || [];
        })
        .catch((error) => {
          console.log(error);
        });
    },
    showDialog() {
      this.$refs.dialog.show();
    }, // 唤醒弹窗
    deleteAction(item) {
      if (this.cardType === 0) {
        if (item.online_state == 0) {
          this.dialogInfo.title = "";
          this.dialogInfo.msg = "是否删除该条应用？";
          this.dialogInfo.cancelText = "";
          this.dialogInfo.sunbmitText = "";
          this.dialogInfo.submit = () => {
            this.$http
              .delete(`/apaas/hubApi/market/del/${item.app_id}`)
              .then(({ data }) => {
                if (data.success) {
                  this.$message({
                    message: `删除${item.app_name}成功.`,
                    type: "success",
                  });
                  this.initDatas(this.tempFliter);
                } else {
                  this.$message({
                    message: `删除${item.app_name}失败.`,
                    type: "warning",
                  });
                }
              })
              .catch((error) => {
                this.$message({
                  message: `删除${item.app_name}失败.`,
                  type: "warning",
                });
              });
          };
        } else {
          this.dialogInfo.title = "删除提示";
          this.dialogInfo.msg =
            "您需要先进行应用商店下架申请，应用处于下架状态时才能进行删除操作。";
          this.dialogInfo.cancelText = "";
          this.dialogInfo.sunbmitText = "";
          this.dialogInfo.submit = () => {
            if (item.up_deploy_status === 3) {
              this.$message({
                message: `${item.app_name}正在申请下架中.`,
                type: "warning",
              });
            } else {
              this.$http
                .put(`/apaas/hubApi/market/deployStatus/${item.app_id}/3`)
                .then(({ data }) => {
                  if (data.success) {
                    this.$message({
                      message: `申请下架${item.app_name}成功.`,
                      type: "success",
                    });
                    this.initDatas(this.tempFliter);
                  } else {
                    this.$message({
                      message: `申请下架${item.app_name}失败.`,
                      type: "warning",
                    });
                  }
                })
                .catch((error) => {
                  this.$message({
                    message: `申请下架${item.app_name}失败.`,
                    type: "warning",
                  });
                });
            }
          };
        }
      } else if (this.cardType === 1) {
        this.dialogInfo.title = "是否删除部署的应用";
        this.dialogInfo.msg =
          "该操作会导致正在调用该应用的用户被迫终止对应用的调用，删除前需向正在调用该应用的用户发送通知，自通知发送之日起，2日后应用将被删除。";
        this.dialogInfo.cancelText = "";
        this.dialogInfo.sunbmitText = "发送通知";
        this.dialogInfo.submit = () => {
          this.$http
            .delete(`/apaas/hubApi/market/deploy/${item.deploy_name}`, {
              params: {
                deployId: item.deploy_id,
              },
            })
            .then(({ data }) => {
              if (data.success) {
                this.$message({
                  message: `删除${item.deploy_name}成功.`,
                  type: "success",
                });
                this.initDatas(this.tempFliter);
              } else {
                this.$message({
                  message: `删除${item.deploy_name}失败.`,
                  type: "warning",
                });
              }
            })
            .catch((error) => {
              this.$message({
                message: `删除${item.deploy_name}失败.`,
                type: "warning",
              });
            });
        };
      }

      this.$refs.dialog.show();
    },
    deploymentAction(item) {
      console.log("deployment " + item.app_name);
      console.log("一键部署功能设计中···");
    }, // TODO: 一键部署功能设计中
    changePageSize(value) {
      this.pageSize = value;
      this.currentPage = 1;
    },
    changeCurrentPage(value) {
      this.currentPage = value;
    },
    approvalItem(item) {
      console.log("approval --- " + item.id);
    },
    deleteItem(item) {
      console.log("delete --- " + item.id);
    },
    detailItem(item) {
      this.$router.push(
        `${this.detailsUrl + (this.type === 1 ? item.deploy_id : item.app.id)}`
      );
    },
    soldUpItem(item) {
      this.dialogInfo.title = "提示";
      this.dialogInfo.msg = "确认上架此服务吗？";
      this.dialogInfo.submit = () => {
        console.log(`上架${item.app_name}`);
        /* 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 = "确认下架此服务吗？";
      this.dialogInfo.submit = () => {
        console.log(`下架${item.app_name}`);
        /* 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();
    },
    editItem(item) {
      this.$router.push(`/yygl/${this.level}/${this.type}/edit/${item.id}`);
    },
    offLine(item) {
      console.log("off line --- " + item.id);
    },
    goodsShelf(item) {
      console.log("goods shelf", item.state);
    },
  },
  created() {
    this.level = parseInt(this.$route.params.level);
    this.type = parseInt(this.$route.params.type);
    this.initHeader();
    this.initFilter();
  },
};
</script>

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