<template>
  <div>
    <div class="title-container">
      <div class="function-container">
        <el-dropdown class="mr10" @command="onAppChange" v-if="allowChange && appName">
          <span class="user-info-container el-dropdown-link">{{ appList.find(item => item.name === appName).name }}<i class="el-icon-arrow-down el-icon--right"></i></span>
          <el-dropdown-menu slot="dropdown" placement="top-start">
            <el-dropdown-item style="line-height: 24px;" :command="item.name" v-for="(item, index) in appList" :key="item.name" :divided="index>0">{{ item.name }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-divider direction="vertical" v-if="allowChange && appName"></el-divider>

        <el-dropdown @command="onCommand">
          <div class="user-info-container el-dropdown-link">
            <el-image class="avatar" :src="userInfo.avatar || require('../../assets/default-avatar.png')" cover>
              <div slot="placeholder">
                <el-image class="avatar" :src="require('../../assets/default-avatar.png')" cover/>
              </div>
              <div slot="error">
                <el-image class="avatar" :src="require('../../assets/default-avatar.png')" cover/>
              </div>
            </el-image>
            <span>{{ userInfo.nickname }}</span>
          </div>
          <el-dropdown-menu slot="dropdown" placement="top-start">
<!--            <el-dropdown-item style="line-height: 24px;" command="center">个人中心</el-dropdown-item>-->
            <el-dropdown-item style="line-height: 24px;" command="password">修改密码</el-dropdown-item>
            <el-dropdown-item style="line-height: 24px;" divided command="logout">退出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-tooltip content="主题色" placement="top center">
          <theme-picker class="flex ml10" v-model:defaultThemeColor="themeColor" @change="onThemeColorChange"></theme-picker>
        </el-tooltip>

        <el-tooltip effect="dark" :content="active ? '退出全屏' : '全屏'" placement="bottom">
          <el-button class="full-screen-btn ml10" icon="el-icon-full-screen" @click="toggle"></el-button>
        </el-tooltip>
      </div>
    </div>

    <el-dialog title="修改密码"
               :visible.sync="dialogVisible"
               :modal-append-to-body="false"
               :before-close="beforeDialogClose"
               width="500px">
      <el-form :model="passwordForm"
               :rules="passwordRules"
               ref="passwordForm"
               :inline="false"
               label-position="left">
        <el-form-item label="新密码"
                      label-width="90px"
                      prop="password">
          <el-input v-model="passwordForm.password"
                    placeholder="请输入新密码"
                    type="password"
                    auto-complete="off"/>
        </el-form-item>
        <el-form-item label="确认密码"
                      label-width="90px"
                      prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword"
                    placeholder="请再次输入新密码"
                    type="password"
                    auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmButton">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import md5 from "js-md5";
import config, {allowChange, appList, defaultAppName} from "@/config";
import ThemePicker from '@/components/ThemePicker'
import screenFull from 'screenfull/dist/screenfull'

export default {
  name: "TitleBar",
  components: {ThemePicker},
  data() {
    let validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (value.length < 6) {
        // callback(new Error('密码长度不小于6位，至少包含大写字母、小写字母、数字、符号中的3种'));
        callback(new Error('密码长度不小于6位'));
      } else {
        if (this.passwordForm.confirmPassword) {
          this.$refs.passwordForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      keyword: '',
      dialogVisible: false,
      passwordForm: {
        password: undefined,
        confirmPassword: undefined,
      },
      passwordRules: {
        password: [{validator: validatePass, trigger: 'blur'}],
        confirmPassword: [{validator: validatePass2, trigger: 'blur'}],
      },
      appName: undefined,
      appList: appList,
      allowChange: allowChange,

      themeColor: undefined,

      active: false, // 是否激活全屏
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    }
  },
  mounted() {
    this.appName = this.$storage.getString("appName", defaultAppName);
    this.themeColor = this.$storage.getString("themeColor", config.defaultThemeColor);
  },
  methods: {
    // 下拉菜单点击事件
    onCommand(command) {
      if (command === "center") {
        this.$router.push({name: "personalIndex"});
      } else if (command === "logout") {
        this.logout();
      } else if (command === "password") {
        this.showChangePasswordDialog();
      }
    },

    // 应用切换
    onAppChange(appName) {
      this.$storage.setString("appName", appName);
      location.reload();
    },

    // 主题色改变
    onThemeColorChange(color) {
      this.$storage.setString("themeColor", color);
    },

    // 退出登录
    logout() {
      this.$confirm('确认要退出系统吗?', '确认', {
        confirmButtonText: '退出',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // this.$axios.delete('/admin/u/admin/login').then(() => {
        this.$storage.removeUserInfo();
        this.$message.success("已退出登录");
        await this.$router.push({
          path: '/login',
          query: {redirect: this.$router.currentRoute.path, ...this.$router.currentRoute.query}
        });
        // })
      }).catch(() => {
        this.$message.info("取消操作")
      });
    },

    // 显示修改密码对话框
    showChangePasswordDialog() {
      this.dialogVisible = true;
    },

    // 修改密码对话框关闭前清空密码
    beforeDialogClose(done) {
      this.$refs.passwordForm.resetFields();
      done();
    },

    // 确认修改密码
    confirmButton() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.$axios.put('/v1/home/update/password', {password: md5(this.passwordForm.password)}).then(() => {
            this.$message.success('密码修改成功');
            this.$refs.passwordForm.resetFields();
            this.dialogVisible = false;
          });
        }
      })
    },

    // 切换全屏
    toggle() {
      if (screenFull.isFullscreen) {
        screenFull.exit();
      } else {
        screenFull.request();
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

.title-container {
  height: $titleBarHeight;
  flex: 1;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;

  .function-container {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;

    .user-info-container {
      display: flex;
      align-items: center;

      &:hover {
        cursor: pointer;
      }
    }

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      margin-right: 10px;
    }

    .full-screen-btn {
      width: 26px;
      height: 26px;
      padding: 0;
    }
  }
}
</style>
