<template>
  <div class="pageheader-box">
    <div class="pageheader-box__left" @click="goBack()" v-if="back">
      <i class="el-icon-back">&nbsp;</i>
      <span>返回</span>
    </div>
    <div class="pageheader-box__divider" v-if="back"></div>
    <div class="pageheader-box__body">
      <div class="pageheader-box__body__title" id="page-title">{{pageTitle}}</div>
      <div class="pageheader-box__body__action" id="page-action" v-if="actions && actions.length">
        <el-button
          v-for="(action, index) in actions"
          :key="index"
          :type="action.type || 'primary'"
          :size="action.size || 'small'"
          :plain="action.plain"
          :round="action.round"
          :circle="action.circle"
          @click="handleClick(index)"
        >
          <i :class="action.icon" v-if="action.icon">&nbsp;</i>
          <span>{{action.text}}</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useModel } from '@/store'

export default {

  setup(props) {
    const router = useRouter()    
    const route = useRoute()
    const goBack = () => router.back()
    
    const {
      pageTitle,
      back,
      actions,
      trigClick,
      setPageTitle,
      setBack,
      setClick,
      setActions,
     } = useModel('pageHeader')
     
    const handleClick = index => {
      if (trigClick.value) {
        trigClick.value(index)
      }
    }

    watchEffect(() => {
      setPageTitle((route.meta || {}).title)
      setClick()
      setBack(false)
      setActions()
    })

    return {
      pageTitle,
      back,
      actions,
      handleClick,
      goBack,
    }
  }
}
</script>

<style lang="less" scoped>
.pageheader-box {
  display: flex;
  line-height: 1.8em;
  padding: 1em;
  background-color: #fff;

  &__left {
    flex: none;
    cursor: pointer;
  }

  &__divider {
    flex: none;
    width: 1px;
    background-color: rgba(0,0,0, .2);
    margin: 0.4em 1em;
  }

  &__body {
    flex: auto;
    display: flex;

    &__title {
      flex: auto;
      font-size: 1.2em;
      color: rgba(0,0,0, .7);
    }

    &__action {
      flex: none;
    }
  }
}
</style>
