<template>
  <div class="app-center" v-loading="loading">
    <div class="app-classify">
      <div class="app-classify-title">
        <span class="title-name">{{ title }}</span>
        <div class="title-icon">
          <i
            class="icon1 icon-zhankai2"
            @click="$refs.tree.handleExpandCollapse()"
          ></i>
          <i class="icon-shuaxin1" @click="loadMenuData()"></i>
        </div>
      </div>
      <div class="app-tree">
        <el-input
          v-model="searchTree"
          placeholder="请输入分类名称"
          clearable
          suffix-icon="el-icon-search"
        ></el-input>
        <ht-tree
          ref="tree"
          class="ht-tree"
          :tree-data="menus"
          node-key="id"
          default-expand-all
          highlight-current
          :show-checkbox="false"
          :expand-on-click-node="false"
          :props="{
            children: 'children',
            label: 'name',
          }"
          @node-click="menuNodeClick"
          @refresh="menuTreeRefresh"
        >
          <span slot-scope="{ node }">
            <span :title="node.label">
              {{ node.label }}
            </span>
          </span>
        </ht-tree>
      </div>
    </div>
    <div class="app-content">
      <div class="app-search">
        <el-input
          v-model="searchWord"
          class="search"
          placeholder="请输入应用名称"
          clearable
          @change="loadAppData"
          suffix-icon="el-icon-search"
        ></el-input>
        <i
          v-if="showClose"
          class="el-icon-close close"
          @click="$emit('close')"
        ></i>
      </div>

      <div v-if="currentMenuId" class="app-content__main-header">
        <span class="label">{{ currentMenuName }}:</span>
        <ul class="tag-wrap">
          <li
            class="tag-item all-tag"
            :class="{ 'tag-check': checkAll }"
            @click="allBtnClick"
          >
            <span class="tag-name">全部</span>
          </li>
          <li
            v-for="(tag, index) in curTagList"
            :key="index"
            class="tag-item"
            :class="{ 'tag-check': tag.check }"
            @click="tagClick(tag)"
          >
            <!-- <span class="tag-name">
              {{ tag.name }}
            </span> -->
            <el-tooltip
              placement="bottom"
              trigger="hover"
              :content="tag.name"
              effect="light"
            >
              <div class="tag-name">
                {{ tag.name | filterName }}
              </div>
            </el-tooltip>
          </li>
        </ul>
      </div>
      <div class="tab-container" :class="{ 'no-tags': !currentMenuId }">
        <div class="app-statistics">
          共
          <span class="app-total">{{ apps.length }}</span>
          个应用
        </div>
        <app-view
          v-if="apps && apps.length > 0"
          :open-type="openType"
          :apps="apps"
          @after-select="afterSelect"
        ></app-view>
        <el-empty
          v-else
          :image="noDataImg"
          :image-size="380"
          description="暂无应用哦~"
        ></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
  import AppView from './AppView.vue'
  import {
    getSysMenuByAlias,
    getSysMenuByAuthApp,
    getSysTag,
    queryByFilter,
  } from '@/api/appCenter.js'
  const MENU_ALIAS = 'app_menu'
  export default {
    name: 'AppSelector',
    components: { AppView },
    props: {
      openType: {
        type: String,
        default: 'window',
      },
      showClose: {
        type: Boolean,
        default: false,
      },
    },
    filters: {
      filterName(val) {
        if (val && val.length > 5) {
          return val.slice(0, 5) + '...'
        }

        return val
      },
    },
    data() {
      return {
        title: '应用分类',
        menus: [],
        searchTree: '',
        searchWord: '',
        menuAlias: MENU_ALIAS,
        currentMenuId: '',
        currentMenuName: '',
        checkAll: false,
        curTagList: [],
        rootMenuId: '',
        apps: [],
        pageResult: { page: 1, pageSize: -1 },
        noDataImg: require('@/assets/nodata_images/no-draft.png'),
        tagMap: {},
        loading: false,
      }
    },
    watch: {
      searchTree(newVal) {
        this.$refs.tree.$refs.elTree.filter(newVal)
      },
    },
    mounted() {
      this.loading = true
      this.loadMenuData()
    },
    methods: {
      loadMenuData(cb) {
        //重置
        this.currentMenuId = null
        this.curTagList.forEach((item) => {
          item.check = false
        })
        this.checkAll = true
        getSysMenuByAlias(this.menuAlias).then((response) => {
          this.rootMenuId = response.id
          if (!response) {
            response = {}
          }
          getSysMenuByAuthApp(this.menuAlias)
            .then((resp) => {
              response.children = resp.value
              this.menus = [response]
              this.loadAppData()
            })
            .finally(() => {
              cb && cb()
            })
        })
      },
      menuNodeClick(node) {
        if (node.id === this.rootMenuId) {
          this.currentMenuId = null
          this.currentMenuName = null
        } else {
          this.currentMenuId = node.id
          this.currentMenuName = node.name
        }
        this.checkAll = true
        this.curTagList.map((item) => {
          item.check = false
        })
        this.loadMenuTagsData()
        this.loadAppData()
      },
      loadMenuTagsData() {
        if (!this.currentMenuId) {
          return
        }
        if (this.tagMap[this.currentMenuId]) {
          this.curTagList = [...this.tagMap[this.currentMenuId]]
          return
        }
        let querys = [
          {
            property: 'type_id_',
            value: this.currentMenuId,
            group: 'main',
            operation: 'EQUAL',
            relation: 'AND',
          },
        ]
        getSysTag({ querys: querys }).then((resp) => {
          this.curTagList = [...resp.rows]
          this.tagMap[this.currentMenuId] = resp.rows
          this.$forceUpdate()
        })
      },
      loadAppData() {
        let query = { pageBean: this.pageResult, params: {} }
        //如果没选中标签，则按菜单查找
        if (this.checkAll) {
          query.params.menuId = this.currentMenuId
        } else {
          //选中的标签
          let checkedTags = this.curTagList.filter((e) => {
            if (e.check) {
              return e
            }
          })
          if (!checkedTags || checkedTags.length == 0) {
            query.params.menuId = this.currentMenuId
          } else {
            //如果有选中的标签，则按标签精确查找
            let tagIds = checkedTags.map((e) => {
              return e.id
            })
            query.params.tagIds = tagIds.join(',')
          }
        }
        if (this.searchWord) {
          query.params.searchWord = this.searchWord
        }
        queryByFilter(query).then((resp) => {
          this.apps = resp.rows || []
          this.pageResult.page = resp.page
          this.pageResult.pageSize = resp.pageSize
          this.pageResult.total = resp.total
          this.loading = false
        })
      },
      menuTreeRefresh(cb) {
        this.currentMenuId = null
        this.currentMenuName = null
        this.curTagList = []
        this.pageResult.page = 1
        this.loadMenuData(cb)
        this.loadAppData()
      },
      allBtnClick() {
        if (!this.checkAll) this.checkAll = true
        if (this.checkAll && this.curTagList.length > 0) {
          for (let i = 0; i < this.curTagList.length; i++) {
            const element = this.curTagList[i]
            element.check = !this.checkAll
            this.curTagList.splice(i, 1, element)
          }
        }
        this.loadAppData()
      },
      tagClick(tag) {
        let isCheck = false
        this.$set(tag, 'check', !tag.check)
        isCheck = this.curTagList.some((val) => val.check)
        isCheck ? (this.checkAll = false) : (this.checkAll = true)
        this.loadAppData()
      },
      afterSelect() {
        this.$emit('after-select')
      },
    },
  }
</script>

<style lang="scss" scoped>
  .app-center {
    height: 760px;
    display: flex;
    width: 100% !important;

    .app-classify {
      background: #f9f9f9;
      width: 240px;
      border-right: 1px solid #ebebeb;
      flex-shrink: 0;

      .app-classify-title {
        display: flex;
        padding: 12px 24px;
        font-size: 16px;
        border-bottom: 1px solid #ebebeb;
        justify-content: space-between;

        .title-name {
          color: #222222;
        }

        .title-icon {
          .icon1 {
            margin-right: 8px;
          }

          i {
            cursor: pointer;
            font-weight: bold;
            font-size: 16px;
          }
        }
      }

      .app-tree {
        padding: 24px 16px;
        height: calc(100% - 44px - 24px - 24px);
        overflow: hidden;
        ::v-deep {
          .expanded {
            font-size: 16px;
            color: #262626;
          }
        }
        .ht-tree {
          margin-top: 16px;
          height: calc(100% - 32px - 16px) !important;
          overflow-y: auto;
        }
      }
    }

    .app-content {
      width: 100%;
      padding: 24px;

      .app-search {
        display: flex;
        font-size: 20px;
        justify-content: space-between;
        .search {
          width: 398px;
        }

        .close {
          cursor: pointer;
        }
      }

      .app-content__main-header {
        display: flex;
        align-items: flex-start;
        padding: 24px 0 12px;

        border-bottom: 1px solid #ebebeb;

        .label {
          padding-right: 24px;
          color: #262626;
          flex-shrink: 0;
          padding-top: 7px;
        }
        .tag-wrap {
          display: flex;
          margin: 0;
          min-height: 28px;
          overflow-x: auto;
          align-items: center;
          flex-wrap: wrap;
          .tag-item {
            display: inherit;
            color: #262626;
            cursor: pointer;
            margin-bottom: 12px;
            padding-right: 8px;
            flex-shrink: 0;
            .tag-name {
              padding: 7px 16px;
              position: relative;
              border-radius: 4px;

              .tag-check {
                width: 18px !important;
                height: 14px !important;
                color: var(--themeColor);

                position: absolute;
                right: 0;
                bottom: 0;
                span {
                  font-weight: 600;
                }
              }
            }
          }
          .all-tag {
            padding-right: 8px;
          }
          .tag-check {
            .tag-name {
              //border: 1px solid var(--themeColor);
              background: #e5f2ff;
              color: #0080fe;
            }
          }
        }
      }

      .tab-container {
        height: calc(100% - 84px);
        .app-statistics {
          padding: 24px 0 16px;
          color: #262626;
          .app-total {
            color: #0080fe;
          }
        }
        ::v-deep {
          .el-empty__description {
            margin-top: -38px;
            p {
              font-size: $base-font-size-big;
              color: $base-dark-title-color;
            }
          }
        }
      }

      .no-tags {
        height: calc(100% - 8px);
      }
    }
  }

  ::v-deep {
    .el-tree {
      background: #f9f9f9;
    }
  }

  ::-webkit-scrollbar {
    display: none;
  }

  ::v-deep {
    .el-icon-search {
      font-size: 16px;
      color: #262626;
    }

    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      color: #0080fe;

      background: #f9f9f9;
      border-radius: 6px 6px 6px 6px;
    }
    .el-tree-node__content {
      line-height: 22px;
      padding: 8px 40px;
      color: #262626;
      font-size: 14px;
    }
    .el-image {
      border-radius: 8px 8px 8px 8px;
    }
    .el-tree-node__content:hover {
      background: #f9f9f9;
    }
  }
</style>
