<template>
  <div class="main">
    <v-head></v-head>
    <Navbar />
    <div class="layout">
      <Sidebar :class="{ show: showSidebar }" :path.sync="path" />
      <div class="content">
        <transition name="move" mode="out-in">
          <router-view class="view"></router-view>
        </transition>
        <el-backtop target=".content"></el-backtop>
      </div>
    </div>
    <v-footer ref="footer"></v-footer>

    <div class="log-mask" v-if="logVisible"></div>
    <div class="log-dia" v-if="logVisible">
      <img class="bg1" src="@/assets/img/log-bg.png" alt="">
      <img class="bg2" src="@/assets/img/log-bg1.png" alt="">
      <p class="log-title">更新日志</p>
      <div class="log-wrap">
        <div class="logs">
          <div class="item" v-for="(item, i) in list" :key="i" v-show="!i || (i && logAll)">
            <h6>{{ item.versionName }}</h6>
            <img v-if="item.coverUrl" :src="item.coverUrl" alt="" class="cover">
            <ul class="detail">
              <li v-for="(item, i) in item.logContents" :key="i">
                <p class="name"><img
                    :src="require('@/assets/img/' + funcList.find(e => e.id === item.type).icon + '.png')" alt=""> {{
                      funcList.find(e => e.id === item.type).name }}</p>
                <div class="val">
                  <p v-for="(item, i) in item.content" :key="i">{{ i + 1 }}、{{ item }}</p>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="more-wrap">
          <el-button class="know" type="primary" size="small" @click="logVisible = false">知道了</el-button>
        </div>
      </div>
    </div>

    <el-dialog title="" :visible.sync="realNameVisible" :close-on-click-modal="false" :close-on-press-escape="false"
      :show-close="false" width="300px" custom-class="name-dia">
      <el-form ref="realNameForm" :model="realNameForm" :rules="realNameRules" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model.trim="realNameForm.userName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model.trim="realNameForm.workNumber" placeholder="请输入工号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="realNameSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import vHead from "../header";
import Navbar from "../navbar";
import vFooter from "../footer";
import Sidebar from '../sidebar'
import { mapState, mapMutations, mapActions } from "vuex";
import util from "@/libs/util";
import Setting from "@/setting";

export default {
  components: {
    vHead,
    Navbar,
    Sidebar,
    vFooter
  },
  data () {
    return {
      showSidebar: false,
      path: '',
      logVisible: false,
      list: [],
      logAll: false,
      funcList: [
        {
          id: 0,
          name: '新功能',
          icon: 'func'
        },
        {
          id: 1,
          name: '修复',
          icon: 'bug'
        },
        {
          id: 2,
          name: '优化',
          icon: 'optimize'
        }
      ],

      realNameVisible: false,
      realNameForm: {
        userName: '',
        workNumber: '',
      },
      realNameRules: {
        userName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
      },
    };
  },
  computed: {
    ...mapState("user", [
      'logView'
    ])
  },
  watch: {
    '$route.path': {
      handler (val) {
        this.path = val
        // 是否显示左侧导航
        this.showSidebar = ['/assessment/list', '/achievement/list', '/evaluation/list', '/course/list', '/review/list', '/information/list', '/project/list', '/resourse/list', '/exam/list', '/review', '/theoreticalCourse', '/resourse'].includes(val)
      },
      immediate: true
    }
  },
  mounted () {
    this.autoLogout()
    this.logView || this.getLogStatus() // logView为false才需要查询接口
    this.handleRealName()
  },
  methods: {
    ...mapMutations("user", [
      'SET_LOG'
    ]),
    ...mapActions("user", [
      "logout"
    ]),
    // 提示填写姓名（登录后调用一次）
    async handleRealName () {
      const res = await this.$post(this.api.checkUserNameOrWorkNumber)
      // 如果没有真实姓名，则弹框提示填写
      if (!res.hasName) {
        this.realNameForm.workNumber = res.workNumber || ''
        this.realNameVisible = true
      }
    },
    // 获取日志列表
    getLog () {
      this.$get(`${this.api.platformLogList}?platformId=${Setting.platformId}&port=1&versionName=`).then(({ logList }) => {
        logList.map((e, i) => {
          e.logContents.map(n => {
            n.content = n.content.split('\n')
          })
        })
        this.list = logList
      }).catch(res => { })
    },
    // 获取日志状态
    getLogStatus () {
      util.local.get(Setting.tokenKey) && this.$get(this.api.logNotification, {
        platformId: Setting.platformId
      }).then(({ notification }) => {
        this.SET_LOG() // 把查看日志状态设置为true
        if (notification) {
          this.logVisible = true // 返回true，则显示日志弹框
          this.getLog()
        }
      }).catch(res => { })
    },
    // 真实姓名提交
    realNameSubmit () {
      this.$refs.realNameForm.validate(async (valid) => {
        if (valid) {
          const form = this.realNameForm
          await this.$post(`${this.api.updateUserNameOrWorkNumber}?userName=${form.userName}&workNumber=${form.workNumber}`)
          this.realNameVisible = false
        } else {
          return false
        }
      })
    },
    // 长时间未操作,自动退出登录
    autoLogout () {
      let lastTime = new Date().getTime();
      document.onmousedown = () => {
        lastTime = new Date().getTime();
      };

      setInterval(() => {
        if (util.local.get(Setting.tokenKey) && (new Date().getTime() - lastTime) > Setting.autoLogoutTime) {
          util.errorMsg("由于您已经有三个小时没有操作，系统自动登出，请重新登录。页面刷新到登录页。");
          setTimeout(this.logout, 1500);
        }
      }, 1000);
    }
  }
};
</script>
<style lang="scss" scoped>
.main {
  .layout {
    display: flex;
  }

  .sidebar:not(.show) {
    margin-left: -160px;
  }

  .content {
    // width: calc(100vw - 160px);
    flex: 1;
    height: calc(100vh - 213px);
    padding: 24px;
    margin-bottom: 20px;
    transition: all 0.3s ease-in-out;
    overflow: auto;
  }
}

.log-mask {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.4);
}

/deep/.log-dia {
  z-index: 11;
  position: absolute;
  top: 250px;
  left: 50%;
  width: 550px;
  transform: translateX(-50%);
  background-color: #fff;
  border-radius: 6px;

  .bg1 {
    width: 100%;
    height: 140px;
  }

  .bg2 {
    position: absolute;
    top: -130px;
    left: 48px;
    max-width: 100%;
    height: 250px;
  }

  .log-title {
    position: absolute;
    top: 65px;
    left: 0;
    width: 100%;
    text-align: center;
    font-size: 22px;
    color: #fff;
    font-weight: 600;
  }

  .log-wrap {
    padding-bottom: 30px;
  }

  .logs {
    max-height: 250px;
    padding: 0 100px;
    margin: 30px 0;
    overflow: auto;
  }

  h6 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #333;
    line-height: 1;
  }

  .more-wrap {
    padding: 0 60px;
    font-size: 14px;
    color: #333;
    text-align: center;
  }

  .know {
    margin-top: 15px;
  }

  .cover {
    max-width: 250px;
    max-height: 160px;
    margin: 10px 0 20px;
  }

  .detail {
    li {
      margin-bottom: 20px;
    }

    .name {
      display: flex;
      align-items: center;
      margin-bottom: 5px;
      font-size: 14px;

      img {
        width: 20px;
        margin-right: 8px;
      }
    }

    .val {
      font-size: 15px;
      line-height: 1.8;
      white-space: pre-wrap;

      p {
        position: relative;
        font-size: 13px;
        color: #727272;
      }
    }
  }
}
</style>