<template>
  <div class="layout-no-cols right-list-toolbar">
    <el-toolbar>
      <el-row style="width:100%">
        <el-col :span="10">
          <el-button @click="createIndex" title="生成全站索引">
            <i class="fa fa-flash"></i> 生成全站索引
          </el-button>
        </el-col>
        <el-col :span="14" align="right">
          维度视图：<el-select placeholder="请选择维度" v-model="dimensionID" @change="changeClickHandler">
            <el-option v-for="dimension in dimensions" :key="dimension.ID" :label="dimension.name" :value="dimension.ID">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
    </el-toolbar>

    <div v-loading="treeLoading">
      <tree-table :data="catalogTree" :expanded-level="2" :lazy="true" :load="loadSubCatalogs" row-key="ID" class="indexes-catalog-tree-table">
        <tree-table-column label="名称">
          <template slot-scope="scope">
            <a class="list-card-title" href="javascript:void(0)" @click.stop="gotoDetailPage(scope.row)">
              <i :class="scope.row.ID === 0 ? 'fa fa-globe f18' : scope.row.icon" aria-hidden="true"></i> {{scope.row.name}}
            </a>
          </template>
        </tree-table-column>
        <el-table-column prop="alias" label="别名" width="220" show-overflow-tooltip></el-table-column>
        <el-table-column prop="typeName" label="栏目类型" width="130"></el-table-column>
        <el-table-column prop="path" label="路径" width="250" show-overflow-tooltip></el-table-column>
        <el-table-column label="索引设置" width="100" align="center">
          <template slot-scope="scope" v-if="scope.row.ID">
            <el-button @click.stop="indexesConfigSetting(true,scope.row)" v-if="checkedIds.includes(scope.row.ID)"
            type="text" title="未开放前台索引" class="table-operate-icon" priv="ContentCore.IndexMenu">
              <i class="fa fa-times icon-danger f16"></i>
            </el-button>
            <el-button @click.stop="indexesConfigSetting(false,scope.row)"  v-else
            type="text" title="已开放前台索引" class="table-operate-icon" priv="ContentCore.IndexMenu">
              <i class="fa fa-check icon-success f16"></i>
            </el-button>
          </template>
        </el-table-column>
      </tree-table>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import TreeTable from '@src/components/treeTable/TreeTable.vue'
import TreeTableColumn from '@src/components/treeTable/TreeTableColumn.vue'
export default {
  components: {
    'tree-table': TreeTable,
    'tree-table-column': TreeTableColumn
  },
  data() {
    return {
      treeLoading: false,
      catalogTree: [], //  左侧站点栏目树
      checkedIds: [], //   已选中的索引设置
      dimensions: [{ID: 1, code: 'default', name: '默认分类'}],
      dimensionID: 1
    }
  },
  created() {
    this.getDimensions()
  },
  methods: {
    async getDimensions() {
      let res = await axios.get('/ui/dimensions')
      this.dimensions = res.data.data
      let lsTmp = localStorage['user_' + localStorage.userName + '_sid_' + this.$root.siteID + '_ewdid']
      if (lsTmp && lsTmp !== '-1') {
        this.dimensionID = parseInt(lsTmp)
      } else {
        this.dimensionID = this.dimensions[0].ID
      }
      await this.loadCatalogTree()
      await this.loadCheckedCatalog()
    },
    async changeClickHandler(value) {
      this.dimensionID = value
      await this.loadCatalogTree()
      await this.loadCheckedCatalog()
    },
    //  生成全站索引
    async createIndex() {
      try {
        await this.$confirm('将重建全站索引，是否重建全站索引？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      try {
        let res = await axios.get('/ui/indexlist/createindex')
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '正在重建索引')
        } else {
          util.showMessage(res)
        }
      } catch (e) {
        util.showErrorNotification(e)
      }
    },
    async loadCatalogTreeData(parentID) {
      this.treeLoading = true
      let res = await axios.get('/ui/catalog/admintree', {
        params: {
          dimensionID: this.dimensionID,
          parentID
        }
      })
      this.treeLoading = false
      return res.data.data
    },
    // 加载栏目树
    async loadCatalogTree() {
      try {
        let catalogData = await this.loadCatalogTreeData(0)
        const currentSite =　await this.$root.getCurrentSite()
        this.catalogTree = [{
          ID: 0,
          name: currentSite.siteName,
          children: catalogData,
          alias: '',
          typeName: '',
          path: ''
        }]
      } catch (e) {
        console.log(e)
      }
    },
    async loadCheckedCatalog() {
      let res = await axios.get('/ui/indexconfig', {
        params: {
          dimensionID: this.dimensionID
        }
      })
      this.checkedIds = res.data.data.checkedIDs
    },
    gotoDetailPage(row) {
      this.$router.push({path: `/settings/indexes/${row.ID}`})
    },
    async indexesConfigSetting(flag, row) {
      if (!row || !row.ID) {
        return
      }
      if (row.type !== 'Default') {
        this.$alert('请选择普通类型的栏目进行操作', '系统提示', {
          type: 'warning'
        })
        return
      }
      let ids = this.checkedIds.concat()
      if (flag) {
        if (ids.length) {
          ids = ids.filter(id => {
            return id !== row.ID
          })
        }
      } else {
        ids.push(row.ID)
      }
      if (row.children && row.children.length) {
        try {
          await this.$confirm('修改本栏目的状态，子栏目的状态也会被改变，确认要执行此操作吗？', '系统提示', {
            confirmButtonText: '确定',
            showCancelButton: '取消',
            type: 'warning'
          })
        } catch (e) {
          return
        }
        const childrenNodeKeys = tmp => {
          if (!tmp.children || tmp.children.length === 0) {
            return
          }
          tmp.children.forEach(childrenNode => {
            if (childrenNode.type === 'Default') {
              keys.push(childrenNode.ID)
            }
            if (childrenNode.children && childrenNode.children.length) {
              childrenNodeKeys(childrenNode)
            }
          })
        }
        let keys = []
        childrenNodeKeys(row)
        if (!flag) {
          keys.forEach(id => {
            if (!ids.includes(id)) {
              ids.push(id)
            }
          })
        } else {
          ids = ids.filter(id => {
            return ![...keys].includes(id)
          })
        }
      }
      try {
        let res = await axios.put(`/ui/indexconfig/${ids.length ? ids.join() : 0}`)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.checkedIds = ids.length <= 1 && flag ? [] : ids.concat()
          await this.loadCheckedCatalog()
        }
      } catch (e) {

      }
    },
    loadSubCatalogs(row, resolve, reject) {
      resolve(this.loadCatalogTreeData(row.ID))
    }
  }
}
</script>

<style scoped>
.indexes-page {
  padding: 10px;
}
.indexes-page .title {
  font-weight: 600;
}
.indexes-page .title i {
  color: #28b06e;
}
.indexes-catalog-tree-table .list-card-title {
  font-size: 14px;
}
</style>
