<template>
  <el-dialog
    fullscreen
    :visible.sync="dialogVisible"
    @destroy-on-close="true"
    class="fullheight setting-dialog"
  >
    <el-container class="container">
      <el-aside class="aside">
        <div class="title">
          <i class="el-icon-back" @click="goBack"></i>
          <img
            v-if="data.icon && data.icon.indexOf('data:image') !== -1"
            :src="data.icon"
            alt=""
            srcset=""
          />
          <div
            class="app-icon__wrap"
            v-else
            :style="{background: data.iconColor}"
          >
            <i :class="data.icon || 'el-icon-s-home'" class="app-icon"></i>
          </div>
          <div class="app-name">{{ data.name }}</div>

          <el-dropdown @command="handleCommand">
            <i class="icon-daohanglan-gengduo"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{node: null, data, action: 'modify'}"
                >修改应用信息</el-dropdown-item
              >
              <el-dropdown-item :command="{node: null, data, action: 'appAuth'}"
                >应用授权</el-dropdown-item
              >
              <el-dropdown-item
                :command="{node: null, data, action: 'menuAuth'}"
                >资源授权</el-dropdown-item
              >
              <el-dropdown-item
                :command="{node: null, data, action: 'appExport'}"
                >导出</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="menu">
          <div class="button-group">
            <el-button
              class="import"
              @click="
                handleCommand({node: null, data: {id: '0'}, action: 'import'})
              "
              icon="icon-xiazai1"
              >导入</el-button
            >
            <el-button
              class="add"
              type="primary"
              @click="addMenu('0', 1)"
              icon="el-icon-plus"
              >添加</el-button
            >
          </div>

          <el-input
            placeholder="请输入关键字"
            v-model="searchContent"
            suffix-icon="el-icon-search"
          ></el-input>

          <sys-app-menu-tree
            highlight-current
            ref="sysAppMenuTree"
            :support-filter="false"
            :default-expand-all="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            @clearRightMeun="clearRightMeun"
            :id="data.id"
          >
            <span
              class="custom-tree-node"
              slot-scope="{node, data}"
              :style="{'padding-left': (node.level - 1) * 10 + 'px'}"
            >
              <span
                :class="node.level === 1 ? data.icon : ''"
                class="menu-icon"
                v-show="node.level === 1 && data.icon"
              ></span>
              <span class="show-ellipsis" :title="node.label">{{
                node.label
              }}</span>
              <span class="drag">
                <i class="icon-drag2" style="margin-right: 8px"></i>
              </span>
              <el-dropdown @command="handleCommand">
                <span>
                  <i class="icon-more" title="更多操作" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-if="
                      data.id && data.menuType === 'category' && node.level <= 2
                    "
                    :command="{node: node, data, action: 'add'}"
                    >添加下级菜单</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="
                      data.id && data.menuType === 'category' && node.level <= 2
                    "
                    :command="{node: node, data, action: 'import'}"
                    >导入</el-dropdown-item
                  >
                  <el-dropdown-item
                    :command="{node: node, data, action: 'export'}"
                    >导出</el-dropdown-item
                  >
                  <el-dropdown-item
                    v-if="data.id"
                    :command="{node: node, data, action: 'delete'}"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </sys-app-menu-tree>
        </div>
      </el-aside>
      <el-main class="main">
        <div class="main-content">
          <app-menu-form
            v-if="menu"
            :app-alias="data.alias"
            :app-name="data.name"
            :data="menu"
            :show-save="true"
            @after-save="loadTree"
            :level="level"
            style="padding-top: 96px"
          ></app-menu-form>
          <el-empty
            style="padding-top: 96px"
            v-else
            :image="emptyImage"
            :image-size="380"
            description="暂无内容，请在左侧菜单添加"
          ></el-empty>
        </div>
      </el-main>
    </el-container>

    <app-menu-dialog
      ref="appMenuDialog"
      :app-alias="data.alias"
      :app-name="data.name"
      @refresh="loadTree"
    ></app-menu-dialog>
    <app-info-dialog ref="appInfoDialog" @refresh="refresh"></app-info-dialog>
    <file-upload-dialog
      ref="fileUploadDialog"
      @refresh="loadTree"
    ></file-upload-dialog>
    <eip-auth-dialog
      @onConfirm="authConfirm"
      ref="appAuthRef"
      :is-tip="false"
    />
    <app-menu-auth-dialog ref="appMenuAuthDialog" />
  </el-dialog>
</template>

<script>
const SysAppMenuTree = () => import('@/components/portal/SysAppMenuTree')
const FileUploadDialog = () => import('@/components/dialog/FileUploadDialog')
const AppMenuDialog = () => import('./AppMenuDialog')
const AppMenuForm = () => import('./AppMenuForm')
const AppInfoDialog = () => import('./AppInfoDialog')
const EipAuthDialog = () => import('@/components/dialog/EipAuthDialog.vue')
const AppMenuAuthDialog = () =>
  import('@/views/portal/appcenter/AppMenuAuthDialog.vue')
import {mapState} from 'vuex'
import portal from '@/api/portal'
import req from '@/request'
const EMPTY_IMAGE = require('@/assets/nodata_images/no-data.png')

export default {
  name: 'AppSettingDialog',
  components: {
    AppInfoDialog,
    SysAppMenuTree,
    AppMenuDialog,
    AppMenuForm,
    FileUploadDialog,
    EipAuthDialog,
    AppMenuAuthDialog,
  },
  data() {
    return {
      dialogVisible: false,
      data: {},
      searchContent: '',
      emptyImage: EMPTY_IMAGE,
      menu: null,
      uploadDialogVisible: false,
      level: 1,
    }
  },
  computed: mapState({
    appMenus: (state) => {
      return state.menu.appMenus || []
    },
  }),
  watch: {
    searchContent(newVal) {
      this.$refs.sysAppMenuTree.$refs.htMenuTree.$refs.elTree.filter(newVal)
    },
  },
  methods: {
    clearRightMeun() {
      this.menu = ''
    },
    open(data, isAddMenu) {
      this.dialogVisible = true
      this.data = {...data}
      this.menu = null
      this.$nextTick(() => {
        this.$refs.sysAppMenuTree.load()
      })
      if (isAddMenu) {
        this.$nextTick(() => {
          this.addMenu('0', 1)
        })
      }
    },
    goBack() {
      this.dialogVisible = false
    },
    handleNodeClick(data, node) {
      this.menu = {...data}
      this.level = node.level
    },
    handleCommand({data, action, node}) {
      switch (action) {
        case 'add':
          this.addMenu(data.id, node.level + 1)
          break
        case 'import':
          this.importMenu(data)
          break
        case 'export':
          this.exportMenu(data)
          break
        case 'delete':
          this.deleteMenu(data)
          break
        case 'modify':
          this.openInfoDialog()
          break
        case 'appAuth':
          this.appAuth()
          break
        case 'menuAuth':
          this.menuAuth()
          break
        case 'appExport':
          this.appExport()
          break
        default:
          break
      }
    },
    addMenu(parentId, level) {
      let data = {
        menuType: parentId === '0' ? 'category' : 'page',
        parentId: parentId,
        appId: this.data.id,
        name: '',
        alias: '',
        sn: 0,
        content: '',
        type: 0,
      }
      this.level = level
      this.$refs.appMenuDialog.open(data, level)
    },
    deleteMenu(menu) {
      this.$confirm('是否确认删除该菜单？', '提示', {})
        .then(() => {
          req
            .remove(`${window.context.portal}/portal/sysAppMenu/v1/${menu.id}`)
            .then((resp) => {
              if (resp.data.state) {
                this.$message.success('删除成功')
                this.loadTree()
                if (this.menu.id === menu.id) {
                  this.menu = null
                }
              }
            })
        })
        .catch(() => {})
    },
    exportMenu(menu) {
      let url = `${window.context.portal}/portal/sysAppMenu/v1/export?appId=${this.data.id}&parentMenuId=${menu.id}`
      req.download(url)
    },
    importMenu(menu) {
      this.$refs.fileUploadDialog.open(
        `${window.context.portal}/portal/sysAppMenu/v1/import?parentMenuId=${menu.id}&appId=${this.data.id}`
      )
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
        isDefaultExpanded: false,
      }
    },
    openInfoDialog() {
      this.$refs.appInfoDialog.open(this.data)
    },
    loadTree() {
      this.$refs.sysAppMenuTree.load()
      this.refresh()
    },
    refresh() {
      this.$emit('refresh')
    },
    appAuth() {
      portal.getRights(this.data.id, 'app').then((resp) => {
        if (resp.data) {
          let conf = {
            right: resp.data.right,
            permissionList: resp.data.type,
            autoClose: false,
          }
          this.$refs.appAuthRef.showDialog(conf)
        }
      })
    },
    authConfirm(data) {
      this.saveRight(data)
    },
    saveRight(data) {
      let param = {
        id: this.data.id,
        objType: 'app',
        ownerNameJson: JSON.stringify(data),
      }
      let _this = this
      this.$http
        .post('${portal}/sys/authUser/v1/saveRights', param)
        .then((resp) => {
          _this.showResponse(resp)
        })
    },
    showResponse(resp) {
      if (resp.data) {
        if (resp.data.state) {
          this.$message.success('授权成功')
          this.$refs.appAuthRef.closeDialog()
        } else {
          this.$message.error(resp.data.message)
        }
      }
    },
    appExport() {
      let url = `${window.context.portal}/portal/sysApp/v1/export?ids=${this.data.id}&status=check`
      req.download(url).catch((error) => {
        const decoder = new TextDecoder('utf-8')
        const text = decoder.decode(error.response.data)
        if (text) {
          let data = JSON.parse(text)
          if (data.message.includes('是否继续导出')) {
            this.$confirm(data.message, '提示', {
              type: 'warning',
              closeOnClickModal: false,
            })
              .then(() => {
                let url = `${window.context.portal}/portal/sysApp/v1/export?ids=${this.data.id}&status=none`
                req.download(url).catch(() => {
                  this.$message('导出失败，请联系管理员')
                })
              })
              .catch(() => {})
          }
        }
      })
    },
    menuAuth() {
      this.$refs.appMenuAuthDialog.open(this.data.id, this.data.name)
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  .aside {
    width: 256px !important;

    .title {
      display: flex;
      font-size: 16px;
      padding: 14px 24px 15px 24px;
      border-bottom: 1px #f6f6f6 solid;
      align-items: center;
      gap: 10px;

      .el-icon-back {
        cursor: pointer;

        &:hover {
          color: #00a0e9;
        }
      }

      img {
        width: 40px;
        height: 40px;
      }

      .app-icon__wrap {
        width: 28px;
        height: 28px;
        position: relative;
        border-radius: 8px;

        .app-icon {
          color: #fff;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .app-name {
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        width: 100px;
      }

      .el-icon-setting {
        margin-left: auto;
      }

      .icon-daohanglan-gengduo {
        cursor: pointer;
      }
    }

    .menu {
      padding: 24px;
      height: calc(100% - 190px);

      .button-group {
        display: flex;
        width: 208px;
        margin-bottom: 16px;

        .import {
          width: 84px;
          height: 32px;
        }

        .add {
          width: 116px;
          height: 32px;
        }
      }

      .el-input {
        margin-bottom: 16px;
      }
    }
  }

  .main {
    background: #f6f6f6;
    padding: 24px !important;

    .main-content {
      background: #ffffff;
      height: 100%;
      width: 100%;
    }
  }
}

div.setting-dialog {
  ::v-deep {
    & > .el-dialog {
      .el-dialog__header {
        display: none;
        height: 100%;
        padding: 0;
      }

      .el-dialog__body {
        height: 100%;
        padding: 0;
      }

      .el-tree .el-tree__empty-block {
        margin: 20px 0;
      }

      .el-tree-node__content {
        height: 32px;
      }
    }

    .el-button [class*='icon-'] + span {
      margin-left: 8px;
    }

    .el-button--small {
      border-radius: 4px;
    }

    .el-dropdown {
      margin-left: auto;
    }
  }
}

.custom-tree-node {
  align-items: baseline;

  .menu-icon {
    padding-right: 8px;
    width: 14px;
  }

  .menu-drag-bar {
    font-size: 12px;
  }

  .el-dropdown,
  .drag {
    i {
      color: #333333;
    }

    i:hover {
      color: #409eff;
    }
  }
}

.custom-tree-node i {
  visibility: hidden;
  font-weight: bold;
}

.custom-tree-node:hover i {
  visibility: visible;
}
</style>
