<template>
  <el-container class="home-container">
    <el-main class="home-content" :key="gridListState">
      <el-tabs
        v-model="currentLayoutIndex"
        v-if="layoutList && layoutList.length > 0"
        @tab-click="handleClick"
      >
        <el-tab-pane
          v-for="(item, index) in layoutList"
          :key="index"
          :label="item.name"
          :style="{height: item.type == 'datav' ? '100%' : 'auto'}"
        >
          <div v-if="item.dataType == 'datav'" class="fullheight">
            <DatavDesignPreview
              v-if="currentLayoutIndex == index"
              ref="datavDesign"
              :lessWidth="5"
              :lessHeight="45"
              :layout="item.layout"
            />
          </div>
          <div
            v-if="item.dataType == 'column' && !isNewlayout && !layout.config"
            class="fullheight"
          >
            <template v-if="currentLayoutIndex == index">
              <el-row
                v-for="(grid, i) in item.layout.list"
                :key="i"
                :gutter="grid.options.gutter"
              >
                <div v-if="grid.type == 'grid'">
                  <el-col
                    v-for="(columns, j) in grid.columns"
                    :Key="j"
                    :span="columns.span"
                  >
                    <ht-column
                      v-for="(cl, k) in columns.list"
                      :key="k"
                      :column-alias="cl.alias"
                    />
                  </el-col>
                </div>
                <div v-if="grid.type == 'tab'">
                  <el-col :span="24">
                    <ht-tabs-column :grid="grid"></ht-tabs-column>
                  </el-col>
                </div>
                <div v-if="!grid.type">
                  <el-col :span="24">
                    <ht-column :column-alias="grid.alias" />
                  </el-col>
                </div>
              </el-row>
            </template>
          </div>
          <div
            class="new-layout__content"
            v-else-if="currentLayoutIndex == index"
          >
            <ht-portal
              ref="htPortal"
              @click-process="handleClickProcess"
              :isShowDelete="false"
              :isDrag="false"
              :column-layout-alias="item.alias"
            >
              <template #empty>
                <el-empty
                  :image="noDataImg"
                  :image-size="380"
                  description="暂无栏目"
                ></el-empty>
              </template>
            </ht-portal>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <leader-dialog ref="leaderDialog" />
  </el-container>
</template>
<script>
import req from '@/request.js'
import portal from '@/api/portal.js'
let Base64 = require('js-base64').Base64
import HtColumn from '@/components/common/HtColumn.vue'
import HtTabsColumn from '@/components/common/HtTabsColumn.vue'
import DatavDesignPreview from '@/components/portal/DatavDesignPreview.vue'
import WidgetFormBus from '@/components/form/bus/WidgetFormBus.js'
import TemplateEdit from '../../components/form/customView/TemplateEdit.vue'
import LeaderDialog from '@/views/portal/components/LeaderDialog.vue'
import {mapState} from 'vuex'
import flow from '@/api/flow.js'
export default {
  components: {HtColumn, HtTabsColumn, DatavDesignPreview, LeaderDialog},
  data() {
    return {
      layout: {},
      dataType: 'column',
      gridList: [],
      gridListState: 'init',
      layoutList: [],
      currentLayoutIndex: 0,
      newLayout: {
        header: [],
        main: {
          left: [],
          center: [],
          right: []
        },
        bottom: []
      },
      mainLayout: {
        left: [],
        center: [],
        right: []
      },
      spanMap: {
        two: {
          left: 16,
          right: 8
        },
        three: {
          left: 8,
          center: 8,
          right: 8
        },
        'equal-two': {
          left: 12,
          right: 12
        }
      },
      isNewlayout: false,
      noDataImg: require('@/assets/nodata_images/no-data.png')
    }
  },
  computed: {
    ...mapState('login', ['currentUser']),
    colSpan() {
      const layoutCol = this.newLayout.main.layoutCol || 'two'
      return key => {
        return this.spanMap[layoutCol][key]
      }
    },
    token() {
      return this.currentUser && this.currentUser.token
    }
  },
  created() {
    //获取用户可切换布局资源
    WidgetFormBus.$emit('initLayoutList')
    this.initLayoutList()
    //获取用户优先级最高的布局
    // portal.getHomeLayout().then(data => {
    //   let designHtml = data.value.designHtml;
    //   this.dataType = data.value.dataType;
    //   WidgetFormBus.$emit('changeLayout',data.value.id);
    //   this.layout = JSON.parse(Base64.decode(designHtml) || "{}");
    //   if (this.layout && this.layout.list && this.layout.list.length > 0) {
    //     this.gridList = this.layout.list;
    //   }
    //   this.gridListState = 'load';
    // });

    //监听切换布局
    WidgetFormBus.$on('switchLayout', obj => {
      WidgetFormBus.$emit('changeLayout', obj.id)
      this.dataType = obj.dataType
      this.layout = JSON.parse(Base64.decode(obj.designHtml) || '{}')
      if (
        this.layout &&
        this.layout.list &&
        this.layout.list.length > 0 &&
        !this.layout.config
      ) {
        this.gridList = this.layout.list
      }
      this.gridListState = 'switch'
      this.cacheUserLayout(obj.type, obj.id)
    })
  },
  methods: {
    cacheUserLayout(type, layoutId) {
      req
        .post('${portal}/portal/main/v1/cacheUserLayout', {
          type: type,
          layoutId: layoutId,
          layoutType: 0
        })
        .then(response => {})
    },
    initLayoutList() {
      let _this = this
      req
        .get(
          '${portal}/portal/sysIndexLayoutManage/sysIndexLayoutManage/v1/getCurrentAuthLayout?from=manage'
        )
        .then(response => {
          if (response.data && response.data.length > 0) {
            response.data.forEach(item => {
              item.layout = JSON.parse(Base64.decode(item.designHtml) || '{}')
            })
            _this.layoutList = response.data
            _this.layout = response.data[_this.currentLayoutIndex].layout
            _this.setNewLayoutConfig()
          }
        })
    },
    handleClick() {
      this.layout = this.layoutList[this.currentLayoutIndex].layout
      this.setNewLayoutConfig()
    },
    setNewLayoutConfig() {
      if (this.layout.main && Object.keys(this.layout.main).length > 0) {
        this.isNewlayout = true
        const {left, center, right} = this.layout.main || {}
        this.newLayout = this.layout
        this.mainLayout = {
          left: left,
          center: center,
          right: right
        }
        this.layout.main.layoutCol !== 'three' && delete this.mainLayout.center
      } else {
        this.gridList = this.layout.config ? [] : this.layout.list
        this.isNewlayout = false
      }
    },
    handleClickProcess(row, type, tableData) {
      if (['commonProcess', 'processOverview', 'collection'].includes(type)) {
        this.$refs.leaderDialog.handleNewProcessJumps(row)
      } else if (type === 'request') {
        this.handleRequestJump(row)
      } else if (type == 'done') {
        this.setReaded(row.id)
        const path = '/matter/approvalForm'
        this.$router.push({
          path,
          query: this.getCurrentQuery(row, type)
        })
      } else {
        const url = `${
          window.context.front
        }/matter/approvalForm?${this.getCurrentQuery(row, type)}&token=${
          this.token
        }`
        window.open(url, '_blank')
      }
    },
    getCurrentQuery(row, type) {
      const {
        id,
        procInstId,
        nodeId,
        status,
        taskId,
        subject,
        procDefId,
        isRead
      } = row
      const queryMap = {
        done: `type=done&doneTaskId=${taskId}`,
        draft: `defId=${procDefId}&name=${subject}&instStatus=${status}`,
        received: `readId=${id}&receivedStatus=${status}&isRead=${isRead}`,
        circulated: `readId=${id}`
      }
      const instId = ['done', 'request', 'draft'].includes(type)
        ? id
        : procInstId
      let query = `instId=${instId}&nodeId=${nodeId}&from=${type}`
      if (['done', 'draft', 'received', 'circulated'].includes(type)) {
        query = `${query}&${queryMap[type]}`
      }
      return query
    },
    handleRequestJump(row) {
      flow.getMyRequestTask(row.id).then(res => {
        let task = res.value
        const path = `${window.context.front}/matter/approvalForm`
        let query = `instId=${row.id}&type=request&myApplication=true`
        if (task && task.id) {
          query = `${query}&task=${task.id}&isGetApprovalBtn=true`
        }
        window.open(`${path}?${query}&token=${this.token}`, '_blank')
      })
    },
    setReaded(id) {
      this.$requestConfig.setReaded({procInstId: id}).then(resp => {
        console.log(resp)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.home-container {
  height: 100%;
  width: 100%;
  background: #f5f5f5;
}
.home-content {
  padding: 5px;
  // height: auto;
  /deep/ .el-card {
    margin-bottom: 5px;
  }
  /*   /deep/ .el-tabs {
    height: 100%;
  } */
  /deep/ .el-tabs__content,
  .el-tabs__content {
    height: auto;
    width: 100%;
    padding-top: 24px;
  }
  /deep/ .el-tabs--border-card > .el-tabs__content {
    padding: 0px;
  }
  /deep/ .el-main {
    padding: 0px;
  }
  /deep/ .el-tabs__header {
    margin: 0 0 5px;
  }
}
/deep/.el-main,
/deep/.column-body {
  // 隐藏滚动条
  &::-webkit-scrollbar {
    width: 0;
    background-color: transparent;
  }
}
@media (max-width: 1152px) {
  /deep/.flow_item {
    padding: 0 10px !important;
    .flow_item__bg {
      width: 32px !important;
      height: 32px !important;
      margin-top: 4px;
      span {
        font-size: 22px !important;
        padding: 6px !important;
      }
    }
    .flow_item__count {
      font-size: 14px !important;
      line-height: 26px !important;
    }
    .flow_item__text {
      zoom: 0.9;
      line-height: 26px !important;
    }
  }
}
</style>
