<template>
  <div class="layout-row-main">

    <el-container class="mainpage-wrap">
      <el-aside width="200px" class="mainpage-col-side">
        <div class="m-profile">
          <div class="u-img-avator">
            <img :src="avatorPath" class="img-circle b-a b-lter" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';" />
          </div>
          <div class="u-user-name">{{userName}}</div>
          <div class="u-real-name">{{realName}}</div>
        </div>
        <div class="m-side-links" >
          <div class="m-side-box" v-show="hasPrivs(`com.zving.cms.Catalog.Content.Add.${contentParams.catalogID}`)">
            <div class="m-side-box__header">
              <h3>创建</h3>
            </div>
            <ul class="m-side-box__body">
              <li class="u-btn-link-item" v-for="(value,key) in contentTypes" :key="key">
                <a :href="key==='Special'?`#/special/${contentParams.catalogID}/new`:`contentEditor.html#/contentEditor/new?type=${key}&cid=${contentParams.catalogID}`" :target="key==='Special'?'_self':'_blank'">
                  <i :class="key|fixIcon"></i> 创建{{value}}
                </a>
              </li>
            </ul>
          </div>
          <div class="m-side-box" v-show="hasPrivs('Platform.Menu')">
            <div class="m-side-box__header">
              <h3>常用菜单
                <el-button @click="showMenuListDialog" class="u-btn-oprate" type="text" style="" priv="Platform.Menu">
                  <i class="fa fa-plus"></i>
                </el-button>
              </h3>
            </div>
            <ul class="m-side-box__body">
              <li class="u-btn-link-item" v-for="shortcut in shortcuts" v-bind:key="shortcut.ID">
                <a v-if="hasPrivs(shortcut.ID)" :href="'#'+shortcut.URL" target="_self">
                  <i v-bind:class="shortcut.icon"></i> {{ shortcut.name }}
                </a>
                <span v-else style="color:#d2c9c9"><i v-bind:class="shortcut.icon"></i> {{ shortcut.name }}</span>
              </li>
            </ul>
          </div>

          <div class="m-side-box">
            <div class="m-side-box__header">
              <h3>一键转载工具</h3>
            </div>
            <div class="m-side-box__body m-side-box__tools_extends">
              <p>一键转载工具是一个书签工具栏按钮，能帮助您快捷转载其他网站的文章。请将下面的链接拖动到您的书签工具栏，或在链接上按右键然后“添加到收藏夹”中。</p>
              <div class="reprint-key-wrap">
                <a class="reprint-key" @click.prevent="openArticeOrignial"
                  :href="reprintScript" title="请将此链接拖到浏览器书签栏或右键添加到收藏夹。">
                  <i class="fa fa-star"></i> 一键转载
                </a>
              </div>
            </div>
          </div>

        </div>
      </el-aside>
      <el-main>
        <div class="m-main-blocks-wrap" >
          <div class="m-main-block-item" v-if="hasPrivs('MainMenus.Stat')">
            <h3 class="m-block-item-title">
              <span class="u-block-item-tite-CN f30">统计数据</span>
              <span class="u-block-item-tite-EN f30">Statistical Data</span>
            </h3>
            <div class="m-block-item-body" v-loading="stasticDataLoading" >
              <stastic-slider :datas="stasticData"></stastic-slider>
            </div>
          </div>
          <div class="m-main-block-item" >
            <h3 class="m-block-item-title">
              <span class="u-block-item-tite-CN f30">最近文档列表</span>
              <span class="u-block-item-tite-EN f30">Documents</span>
            </h3>
            <div class="m-block-item-body" >
              <el-table v-loading="contentsLoading" :data="documents" style="width: 100%">
                <el-table-column type="index" align="center" width="60" label="序号"></el-table-column>
                <el-table-column prop="title" label="标题">
                  <template slot-scope="scope">
                    <a @click="editRow(scope.row)">{{scope.row.title}}</a>
                  </template>
                </el-table-column>
                <el-table-column prop="catalogName" width="100" label="栏目" />
                <el-table-column prop="addTime" width="140" label="添加日期">
                  <template slot-scope="scope">
                    {{scope.row.addTime | fixDateTime}}
                  </template>
                </el-table-column>
                <el-table-column prop="statusName" width="100" label="当前状态" />
                <el-table-column width="140" label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" class="btn-text-oprate" @click="previewDetail(scope.row)">
                      <i class="fa fa-search"></i>&nbsp;预览</el-button>
                    <el-button type="text" class="btn-text-oprate" :priv="'com.zving.cms.Catalog.Content.Edit.'+scope.row.catalogID" @click="editRow(scope.row)">
                      <i class="fa fa-share-square-o"></i>&nbsp;编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="m-main-block-item" >
            <h3 class="m-block-item-title">
              <span class="u-block-item-tite-CN f30">消息列表</span>
              <span class="u-block-item-tite-EN f30">Messages</span>
            </h3>
            <div class="m-block-item-body">
              <el-table v-loading="messagesLoading" :data="messages" style="width: 100%">
                <el-table-column show-overflow-tooltip min-width="5%">
                  <template slot-scope="scope">
                    <i :class="scope.row.readFlag ? 'fa fa-envelope-open-o' : 'fa fa-envelope'"></i>
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip min-width="47%" label="标题">
                  <template slot-scope="scope">
                     <a @click.stop="showMessage(scope.row)"><div v-html="scope.row.subject" class="subject-div"></div></a>
                  </template>
                </el-table-column>
                <el-table-column prop="fromUser" show-overflow-tooltip min-width="15%" label="发送人"></el-table-column>
                <el-table-column prop="addTime" show-overflow-tooltip min-width="20%" label="发送时间">
                  <template slot-scope="scope">
                    {{scope.row.addTime | fixDateTime}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <div class="m-main-block-item" v-if="userName === adminUserName">
            <h3 class="m-block-item-title">
              <span class="u-block-item-tite-CN f30">系统信息</span>
              <span class="u-block-item-tite-EN f30">System Information</span>
            </h3>
            <div class="m-block-item-body" >
              <system-info></system-info>
            </div>
          </div>
          <div class="m-main-block-item" v-if="hasPrivs('ContentCore.SiteMenu')">
            <h3 class="m-block-item-title">
              <span class="u-block-item-tite-CN f30">站内搜索</span>
              <span class="u-block-item-tite-EN f30">Search</span>
            </h3>
            <div class="m-block-item-body">
              <el-input placeholder="请输入关键字" class="m-search-input" size="large" v-model="keywords" @keyup.enter.native="search('')">
                <el-select v-model="contentColumn" slot="prepend" placeholder="请选择">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="标题" value="title"></el-option>
                  <el-option label="作者" value="author"></el-option>
                  <el-option label="编辑" value="editor"></el-option>
                  <el-option label="来源" value="source"></el-option>
                  <el-option label="关键词" value="keyword"></el-option>
                </el-select>
                <i slot="suffix" class="el-input__icon fa fa-search" @click="search('')" title="搜索"></i>
              </el-input>
              <div class="m-search-history" v-if="(searchWords && searchWords.length) || (searchHotWords && searchHotWords.length)">
                <el-row>
                  <el-col :span="2" class="gray f16">{{searchWords.length?'搜索记录':'搜索热词'}}</el-col>
                  <el-col :span="22" class="u-history-history__list f16">
                    <template v-if="searchWords.length">
                      <a href="javascript:void(0)" @click.stop="search(word)" v-for="word in searchWords" v-text="word" :key="word"></a>
                    </template>
                    <template v-else>
                      <a href="javascript:void(0)" @click.stop="search(word)" v-for="word in searchHotWords" v-text="word" :key="word"></a>
                    </template>
                  </el-col>
                </el-row>
              </div>
              <div v-show="searchBlock" class="search-result-list">
          <el-table  ref="searchResult" :data-read-url="getSearchResult" :auto-get-data="false" tooltip-effect="dark" style="width:100%" :page-size="10" @selection-change="onSelectionChange" :multi-operates="multiOperates">
            <el-table-column type="index" label=" " width="50"></el-table-column>
            <el-table-column type="selection" width="60" align="center" ></el-table-column>
            <el-table-column prop="ID" label="内容ID" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="contentTypeName" label="内容类型 " width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="catalogName" label="所属栏目" width="120" show-overflow-tooltip></el-table-column>
            <el-table-column prop="title" label="标题" show-overflow-tooltip>
              <template slot-scope="scope">
                <span style="cursor: pointer;" @click.stop="editRow(scope.row)" v-html="scope.row.title"></span>
              </template>
            </el-table-column>
            <el-table-column width="80" label="操作">
              <template slot-scope="scope">
                <el-button @click.native.prevent="editRow(scope.row)" type="text" title="编辑">
                  <i class="fa fa-pencil"></i>
                </el-button>
                <el-dropdown>
                    <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
                    <el-dropdown-menu slot="dropdown" class="button-dropdown">
                      <el-dropdown-item>
                        <el-button type="text" @click.stop="offLineContents([scope.row])">
                          <i class="fa fa-arrow-down" aria-hidden="true"></i>下线
                        </el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-button type="text" @click.stop="deleteContents([scope.row])">
                          <i class="fa fa-remove" aria-hidden="true"></i> 删除
                        </el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
            </template>
            </el-table-column>
          </el-table>
        </div>
              <div class="m-quick-oprations">
                <el-row>
                  <el-col :span="8">
                    <el-button class="btn-quick-oprate" :disabled="typeof site.URL !== 'string'" @click="browser">
                      <i class="fa fa-search-plus"></i> 浏览首页</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button class="btn-quick-oprate" @click="preview">
                     <i class="fa fa-eye"></i> 预览首页</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="pubIndex" class="btn-quick-oprate" :priv="`com.zving.cms.Site.${siteID}`">
                      <i class="fa fa-paper-plane-o"></i> 发布首页</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="createSiteIndexes" class="btn-quick-oprate" :priv="`com.zving.cms.Site.${siteID}`">
                      <i class="fa fa-refresh"></i> 重建索引</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="allSiteAddedPub('N')" class="btn-quick-oprate" :priv="`com.zving.cms.Site.${siteID}`">
                      <i class="fa fa-paper-plane"></i> 发布全站</el-button>
                  </el-col>
                  <el-col :span="8">
                    <el-button @click="allSiteAddedPub('Y')" class="btn-quick-oprate" :priv="`com.zving.cms.Site.${siteID}`">
                      <i class="fa fa-telegram"></i> 增量发布</el-button>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
          <!-- <div class="m-main-block-item" v-if="!hasPrivs('MainMenus.Stat')&&!hasPrivs('ContentCore.SiteMenu')&&!hasPrivs('Platform.SystemInfo')">
            <span>因为您没有权限，这儿没有内容显示 </span>
          </div> -->
        </div>
      </el-main>
    </el-container>

    <el-dialog title="菜单列表" :visible.sync="showMenuList" append-to-body width="80%">
      <div class="menu-list" v-loading="menuDataLoading">
        <tree-grid ref="menuList" :columns="columns" :tree-structure="true" :strict="true" :data-source="menus" @selection-change="onSelectionChange">
        </tree-grid>
      </div>
      <div slot="footer">
        <el-button @click="showMenuList = false">取 消</el-button>
        <el-button type="primary" @click="selectMenu">确 定</el-button>
      </div>
    </el-dialog>

     <message-detail-dialog :showLookMessageShow.sync="messageDetail.show" :tmpMessageDetail="messageDetail.detail" :userType="messageDetail.type"></message-detail-dialog>
  </div>
</template>
<script>

import util from '@src/common/util.js'
import Privilege from '@src/common/privilege.js'
import StasticSlider from './components/StasticSlider.vue'
import SystemInfo from './components/SystemInfo.vue'
import TreeGrid from '@src/components/TreeGrid.vue'
import messageDetailDialog from '../platform/message/messageDetailDialog.vue'
let localStorageSearchHistoryKey = 'main_search_history'
export default {
  components: {
    StasticSlider,
    SystemInfo,
    TreeGrid,
    messageDetailDialog
  },
  filters: {
    fixIcon: function(val) {
      switch (val) {
        case 'Image':
          return 'fa fa-image'
        case 'Audio':
          return 'fa fa-music'
        case 'Video':
          return 'fa fa-video-camera'
        case 'File':
          return 'fa fa-file-archive-o'
        case 'VideoGroup':
          return 'fa fa-film'
        case 'Special':
          return 'fa fa-id-card-o'
        default:
          return 'fa fa-file-text-o'
      }
    },
    fixDateTime: function(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      userName: localStorage.userName || 'anonymous',
      realName: localStorage.realName || 'anonymous',
      adminUserName: localStorage.adminUserName || 'admin',
      siteID: this.$root.siteID,
      site: {},
      shortcuts: [],
      stasticData: [],
      documents: [],
      messages: [],
      stasticDataLoading: false,
      contentsLoading: true,
      messagesLoading: true,
      keywords: '',
      contentColumn: '',
      searchWords: [],
      searchHotWords: [],
      showMenuList: false,
      menuDataLoading: false,
      columns: [
        {
          text: '菜单名称',
          render: function(row) {
            return '<i class="' + row.icon + '">&nbsp;' + row.name + '</i>'
          },
          minwidth: 100
        },
        {
          text: '是否启用',
          render: function(row) {
            if (row.status === 'Y') {
              return '<i class="fa fa-check icon-success"></i>'
            } else {
              return '<i class="fa fa-times icon-danger"></i>'
            }
          },
          width: 90,
          isAlignCenter: true
        },
        {
          text: 'ID',
          dataIndex: 'ID'
        },
        {
          text: 'URL',
          dataIndex: 'URL'
        },
        {
          text: '来源插件',
          dataIndex: 'pluginName',
          width: 130
        }
      ],
      menus: [],
      selectedRows: [],
      contentParams: {},
      contentTypes: [],
      searchBlock: false,
      visibleTips: false,
      reprintScript: '',
      messageDetail: {
        show: false,
        detail: {
          toUser: '',
          fromUser: '',
          addTime: '',
          subject: '',
          content: ''
        },
        type: 'FromUser'
      },
      defaultMenus: [
        { ID: 'Workspace.Draft', URL: '/workspace/' },
        { ID: 'ContentCore.Catalog', URL: '/catalogIndex/' },
        { ID: 'ContentCore.EditWorkSpace', URL: '/editorWorkspace' },
        { ID: 'MainMenus.AdminWorkspace', URL: '/settings/' }
      ],
      multiOperates: [
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteContents(rows)
          }
        },
        {
          label: '下线',
          value: 'offline',
          fn: rows => {
            this.offLineContents(rows)
          }
        }
      ]
    }
  },
  computed: {
    selectedMenuIDs() {
      let selectedMenuIDs = []
      this.shortcuts.forEach(item => selectedMenuIDs.push(item.ID))
      return selectedMenuIDs.join(',')
    },
    avatorPath() {
      return './ui/avatar/' + this.userName
    }
  },
  created() {
    localStorageSearchHistoryKey += '_' + this.$root.siteID
    this.init()

    // 监听更新事件
    let self = this
    window.updateMainShortcutEvent = document.createEvent('Event')
    window.updateMainShortcutEvent.initEvent('updatemainshortcutevent', true, true)
    document.addEventListener('updatemainshortcutevent', function() {
      self.getShortcutList()
    })
  },
  methods: {
    previewDetail(row) {
      if (!row || !row.ID) {
        return
      }
      window.open(`preview.html?id=${row.ID}&type=${(row.contentTypeID === 'Special' ? 'special' : 'content')}&catalogID=${row.catalogID}`)
    },
    // 批量删除内容
    async deleteContents(rows) {
      let titleStr = _.map(rows, 'title').join(',')
      if (titleStr.length > 30) {
        titleStr = titleStr.replace(/<\/?.+?>/g, '')
        titleStr = titleStr.substring(0, 30) + '...'
      }
      this.$confirm(`确认删除选择的<span class='icon-danger'>${rows.length}条</span>内容：<span class='icon-danger'>${titleStr}</span>？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let data = {}
          rows.forEach(item => {
            if (Privilege.hasPriv(`com.zving.cms.Catalog.Content.Delete.${item.catalogID}`) === true) {
              if (data[item.catalogID] && Array.isArray(data[item.catalogID])) {
                data[item.catalogID].push(item.ID - 0)
              } else {
                data[item.catalogID] = [item.ID - 0]
              }
            }
          })

          let resp = await axios.delete(`/ui/contentcore/contents/delete`, {params: {data}})
          await util.showProgress(resp.data.taskID, resp.data.message)
          this.$refs.searchResult.getData()
        })
        .catch(err => { console.error(err) })
    },

    // 批量下线内容
    async offLineContents(rows) {
      let titleStr = _.map(rows, 'title').join(',')
      if (titleStr.length > 30) {
        titleStr = titleStr.replace(/<\/?.+?>/g, '')
        titleStr = titleStr.substring(0, 30) + '...'
      }
      this.$confirm(`确认下线选择的<span class='icon-danger'>${rows.length}条</span>内容：<span class='icon-danger'>${titleStr}</span>？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async res => {
          let data = {}
          rows.forEach(item => {
            if (Privilege.hasPriv(`com.zving.cms.Catalog.Content.Publish.${item.catalogID}`) === true) {
              if (data[item.catalogID] && Array.isArray(data[item.catalogID])) {
                data[item.catalogID].push(item.ID - 0)
              } else {
                data[item.catalogID] = [item.ID - 0]
              }
            }
          })

          let resp = await axios.put(`/ui/contentcore/contentpublish/offline`, { data })
          util.showResponseMessage(resp.data)
          this.$refs.searchResult.getData()
        })
        .catch(err => { console.error(err) })
    },

    init() {
      try {
        this.getStasticData()
        this.getShortcutList()
        this.getDocuments()
        this.getMessages()
        this.getSearchHistory()
        this.getSiteInfo()
        this.initContentParams()
        this.showOneKeyReprintTool()
      } catch (e) {
        console.error(e)
      }
    },
    showOneKeyReprintTool() {
      let oneKeyReprintSheet = function() {
        if (window.oneKeyReprint) {
          window.oneKeyReprint()
          return
        }
        if (window._clipToken === '') return
        let e = document.createElement('script')
        e.id = '_oneKeyReprintSheet'
        e.type = 'text/javascript'
        e.charset = 'UTF-8'
        e.src = 'http://www.zving.com/oneKeyReprint.js?r=' + Math.random()
        e.onerror = function() {
          alert('不能访问到服务器http://www.zving.com')
        }
        e.onload = function() {
          window._clipToken = ''
        }
        document.getElementsByTagName('HEAD')[0].appendChild(e)
      }
      let href = location.href
      let splitStr = '#'
      if (href.indexOf('app.html') > 1) {
        splitStr = 'app.html' + '#'
      }
      let frontConxtPath = href.split(splitStr)[0]
      let js = oneKeyReprintSheet
        .toString()
        .replace(/[\n\r]/gm, '')
        .replace(/\t/g, ' ')
        .replace(/ +/g, ' ')
        .replace(/ *([({}=;]) */g, '$1')
        .replace(/ *([)}=;]) */g, '$1')
        .replace(/"/g, "'")
        .replace('http://www.zving.com/', frontConxtPath)
        .replace('http://www.zving.com', frontConxtPath)

      this.reprintScript = 'javascript:void((' + js + ')());'
    },
    openArticeOrignial() {
      alert('请将此链接拖到浏览器书签栏或右键添加到收藏夹。')
    },
    /* openTips() {
        this.visibleTips = true
      }, */
    async initContentParams() {
      let resp = await axios.get('/ui/workspace/nocatalog/init')
      if (resp.data.status === 1) {
        this.contentParams = resp.data.data
        let res = await axios.get(`/ui/catalogs/${this.contentParams.catalogID}/contenttypes`)
        if (res.data.status === 1) {
          this.contentTypes = res.data.data
        }
      }
    },
    async getSiteInfo() {
      let resp = await axios.get(`/ui/sites/${this.siteID}`)
      if (resp.data.status === 1) {
        this.site = resp.data.data
      }
    },
    async getShortcutList() {
      let shortcutRes = await axios.get('/ui/users/shortcuts')
      this.shortcuts = shortcutRes.data.data
    },
    async getStasticData() {
      // 为了首页第一屏能尽快展现，缓存一下统计数据
      if (localStorage.cache_main_stastic) {
        this.stasticData = JSON.parse(localStorage.cache_main_stastic)
      }
      let ajaxData = await axios.get('/ui/main/stasticData')
      if (ajaxData.data.status === 1) {
        localStorage.cache_main_stastic = JSON.stringify(ajaxData.data.data)
        this.stasticData = ajaxData.data.data
      }
    },
    async getDocuments() {
      this.contentsLoading = true
      let ajaxData = await axios.get('/ui/main/recentdocs')
      if (ajaxData.data.status === 1) {
        this.documents = ajaxData.data.data
        this.contentsLoading = false
      }
    },
    async getMessages() {
      this.messagesLoading = true
      let ajaxData = await axios.get('/ui/message?sortField=addTime&pageIndex=0&pageSize=10')
      if (ajaxData.data.status === 1) {
        this.messages = ajaxData.data.data
        this.messagesLoading = false
      }
    },
    async getSearchHistory() {
      var localData = []
      if (window.localStorage) {
        const storage = window.localStorage
        localData = storage.getItem(localStorageSearchHistoryKey) ? storage.getItem(localStorageSearchHistoryKey).split(',') : localData
      }
      if (Array.isArray(localData) && localData.length) {
        this.searchWords = [...new Set(localData)].splice(0, 10)
        return
      }

      let ajaxData = await axios.get('/ui/main/searchlist')
      if (ajaxData.data.status === 1) {
        this.searchHotWords = ajaxData.data.data
      }
    },
    browser() {
      window.open(this.site.URL)
    },
    preview() {
      window.open('preview.html?id=' + this.siteID + '&type=site')
    },
    async pubIndex() {
      try {
        await this.$confirm('本次生成的静态页面将覆盖原有页面，确认生成所有静态页面吗？', '发布首页', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let res = await axios.put(`/ui/sites/${this.siteID}/publishindex`)
      util.showResponseMessage(res.data)
    },
    async allSiteAddedPub(incrementPublishFlag) {
      let publishTitle = incrementPublishFlag === 'Y' ? '增量发布' : '发布全站'
      try {
        await this.$confirm('本次生成的静态页面将覆盖原有页面，确认生成所有静态页面吗？', publishTitle, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let res = await axios.put(`/ui/sites/${this.siteID}/publish`, {
        increment: incrementPublishFlag,
        publishStatus: -1
      })
      if (res.data.status === 1) {
        await util.showProgress(res.data.taskID, `正在${publishTitle} . . .`)
      } else {
        util.showErrorMessageBox(res.data.message)
      }
    },
    async createSiteIndexes() {
      // 生成全站索引
      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) {

      }
    },
    formatDate(row, column, cellValue) {
      return cellValue === null || cellValue === '' ? '' : cellValue.split(' ')[0]
    },

    async getDefaultMenu() {
      let selectedMenuIDs = []
      this.defaultMenus.forEach(item => {
        item.URL && selectedMenuIDs.push(item.ID)
      })
      let res = await axios.put('/ui/userpreference/shortcut', {
        shortcut: selectedMenuIDs.join()
      })
      if (res.data.status === 1) {
        this.shortcuts = _.filter(this.selectedRows, function(o) {
          return o.URL
        })
        // 更新个人设置中的快捷链接
        if (window.updateShortcutEvent) {
          document.dispatchEvent(window.updateShortcutEvent)
        }
      }
    },
    async selectMenu() {
      if (this.selectedRows.length > 8) {
        util.showErrorMessageBox('最多选择8个快捷链接！')
        return
      }
      let selectedMenuIDs = []
      this.selectedRows.forEach(item => {
        item.URL && selectedMenuIDs.push(item.ID)
      })
      let res = await axios.put('/ui/userpreference/shortcut', {
        shortcut: selectedMenuIDs.join()
      })
      if (res.data.status === 1) {
        this.shortcuts = _.filter(this.selectedRows, function(o) {
          return o.URL
        })
        // 更新个人设置中的快捷链接
        if (window.updateShortcutEvent) {
          document.dispatchEvent(window.updateShortcutEvent)
        }
      } else {
        util.showErrorMessageBox(res.data.message)
      }
      this.showMenuList = false
    },

    onSelectionChange(selection) {
      this.selectedRows = selection
    },

    async showMenuListDialog() {
      this.showMenuList = true
      this.menuDataLoading = true
      let selectedMenuIDs = []
      this.shortcuts.forEach(item => selectedMenuIDs.push(item.ID))
      let menuRes = await axios.get('/ui/menus/enabledmenulist', {
        params: {
          selectedMenuIDs: this.selectedMenuIDs
        }
      })
      this.menus = menuRes.data.data
      this.$nextTick(function() {
        this.menuDataLoading = false
      })
    },
    getSearchResult() {
      let params = {
        siteID: this.siteID,
        keyword: encodeURIComponent(this.keywords),
        contentColumn: this.contentColumn
      }
      return ['/ui/indexlist/bindsitesearchresult', { params }]
    },
    async search(val) {
      this.searchBlock = true
      this.keywords = val || this.keywords
      await this.$refs.searchResult.getData()
      document.getElementsByClassName('search-result-list')[0].scrollIntoView()

      if (this.keywords) {
        this.saveSearchHistory(this.keywords)
        this.getSearchHistory()
      }
    },
    saveSearchHistory(val) {
      if (window.localStorage) {
        const storage = window.localStorage
        var storageData = storage.getItem(localStorageSearchHistoryKey) ? storage.getItem(localStorageSearchHistoryKey).split(',') : []
        storageData.unshift(val)
        storageData = [...new Set(storageData)]
        storage.setItem(localStorageSearchHistoryKey, storageData.join(','))
      }
    },
    editRow(row) {
      let id = row.ID ? row.ID : 'new'
      let contentType = row.contentType || row.contentTypeID || 'Article'
      if (contentType === 'Special') {
        window.open(`specialDesigner.html?ID=${id}`)
      } else {
        let path = `/contentEditor/${id}?type=${contentType}&cid=${row.catalogID}`
        window.open('contentEditor.html#' + path)
      }
    },
    addContent(cmd) {
      if (cmd === 'Special'){
        this.$router.push({
          path: `/special/${this.contentParams.catalogID}/new`
        })
      } else {
        let path = `/contentEditor/new?type=${cmd}&cid=${this.contentParams.catalogID}`
        window.open('contentEditor.html#' + path)
      }
    },
    hasPrivs: function(val) {
      return !!(val && Privilege.hasPriv(val))
    },
    async showMessage(row) {
      if (row.ID > 0) {
        let rowIds = []
        rowIds.push(row.ID)
        let res = await axios.put(`/ui/message/${rowIds}/setreadflag`)
        if (res.data.status === 1) {
          this.getMessages()
        }
      }
      this.messageDetail.detail = Object.assign({}, row)
      this.messageDetail.show = true
    }
  }
}
</script>
<style>
.mainpage-wrap {
  width: 100%;
  min-height: calc(100vh - 162px);
}

.mainpage-wrap .el-aside,
.mainpage-wrap .el-main {
  overflow: hidden;
}

.mainpage-col-side {
  position: relative;
}

.mainpage-col-side:after {
  content: '';
  position: absolute;
  width: 1px;
  height: 100%;
  top: 10px;
  right: 0;
  background: #dadada;
}

.m-profile {
  position: relative;
  padding: 15px 15px 0 0;
}

.m-profile:after {
  content: ' ';
}

.u-img-avator {
  text-align: center;
  padding: 10px;
}

.u-img-avator img {
  max-width: 96px;
  border: 4px solid #fff;
  border-radius: 100%;
  box-shadow: 0 0 32px 4px rgba(40, 176, 110, 0.15);
}

.m-profile .u-user-name {
  text-align: center;
  color: #28b06e;
  font-size: 24px;
  font-weight: 100;
}

.m-profile .u-real-name {
  text-align: center;
  color: #444;
  font-size: 16px;
  font-weight: 100;
}

.m-side-links {
  margin-top: 30px;
}

.m-side-box {
  width: 90%;
  margin-bottom: 30px;
}

.m-side-box .m-side-box__header {
  border-bottom: solid 1px #dcdcdc;
}

.m-side-box .m-side-box__body {
  padding-top: 10px;
}

.m-side-box__header h3 {
  font-size: 17px;
  font-weight: 900;
  line-height: 50px;
  color: #444;
}

.m-side-box__header .u-btn-oprate {
  float: right;
  margin-top: 10px;
}

.m-side-box__body .u-btn-link-item {
  display: block;
  margin: 20px;
  font-size: 16px;
}

.m-side-box__body .u-btn-link-item a {
  color: inherit;
}
.m-side-box__body .u-btn-link-item a:hover {
  color: #28b06e;
}
.m-side-box__body .u-btn-link-item a i {
  width: 20px;
}

.m-main-blocks-wrap {
  padding-left: 40px;
  padding-top: 20px;
}

.m-main-block-item {
  margin-bottom: 80px;
}

.m-block-item-title {
  position: relative;
  line-height: 80px;
}

.m-block-item-title:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 55px;
  height: 3px;
  background: #2ab270;
}

.m-block-item-title span {
  font-weight: normal;
  display: inline-block;
}

.m-block-item-title span.u-block-item-tite-EN {
  font-weight: 100;
  margin-left: 25px;
}
.m-block-item-title span.u-block-item-tite-CN {
  color: #444;
}
.m-search-history {
  margin: 5px;
  line-height: 30px;
}
.u-history-history__list a {
  color: inherit;
  display: inline-block;
  margin-right: 20px;
}
.search-result-list {
  clear: both;
  margin-top: 10px
}

.m-quick-oprations {
  margin-top: 50px;
}

.btn-quick-oprate {
  width: 80%;
  font-size: 18px;
  color: #fff;
  background: #28b06e;
  line-height: 32px;
  border-radius: 50px;
  margin-bottom: 26px;
}

.btn-quick-oprate a {
  display: block;
  color: inherit;
  text-decoration: none;
}

.btn-quick-oprate i {
  font-size: 22px;
}

.btn-text-oprate a {
  color: inherit;
}
.m-search-input .el-input__inner {
  height: 44px;
  font-size: 16px;
}
.m-search-input .el-input__icon {
  font-size: 20px;
  line-height: 42px;
  cursor: pointer;
}
.reprint-key-wrap {
  margin: 10px 10px 0 0;
  text-align: center;
}
.reprint-key-wrap a {
  border: 1px solid #c2e7b0;
  padding: 5px 15px;
  background-color: #f0f9eb;
  border-radius: 6px;
  text-decoration: none;
}
.m-side-box__tools_extends {
  line-height: 32px;
}
</style>
