<template>
  <div class="navbar">
    <hamburger
      :is-active="sidebar.opened"
      class="hamburger-container"
      @toggleClick="toggleSideBar"
    />

    <breadcrumb class="breadcrumb-container" v-if="showBreadcrumb" />

    <!-- <NavMenu class="navmenu" /> -->

    <div class="right-menu">
      <!-- <div class="right-menu-item hover-effect">
        <el-tooltip effect="dark" content="家用工程机登录" placement="bottom">
          <i
            class="el-icon-s-platform"
            style="font-size: 24px; line-height: 50px"
            @click="toEngine"
          ></i>
        </el-tooltip>
      </div> -->

      <div class="right-menu-item hover-effect" @click="toEngine">
        <i class="el-icon-s-platform" style="font-size: 18px;"></i>
        <span style="font-size: 16px; margin-left: 6px;">家用工程机登录</span>
      </div>

      <el-badge
        :value="noticeCount"
        :max="10"
        :hidden="!noticeVisible"
        class="right-menu-item hover-effect"
      >
        <el-tooltip effect="dark" content="系统消息" placement="bottom">
          <i
            class="el-icon-message-solid"
            @click="goNotice"
            style="font-size: 24px; line-height: 50px"
          ></i>
        </el-tooltip>
        <!-- <el-button icon="el-icon-message-solid" type="text" class="notice-icon" @click="goNotice"></el-button> -->
      </el-badge>
      <template v-if="device !== 'mobile'">
        <screenfull id="screenfull" class="right-menu-item hover-effect" />
      </template>

      <el-dropdown class="user-container" trigger="click">
        <div class="user right-menu-item hover-effect">
          <i class="el-icon-user-solid"></i>
          <span>{{ name }}</span>
        </div>
        <el-dropdown-menu slot="dropdown" class="user-dropdown">
          <router-link to="/setting/personal">
            <el-dropdown-item>个人信息</el-dropdown-item>
          </router-link>
          <el-dropdown-item divided @click.native="logout">
            <span style="display: block">退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <el-dialog
      title="绑定工程机系统"
      :visible.sync="dialogFormVisible"
      :modal="false"
      width="30%"
    >
      <el-form ref="engineForm" :model="engineForm" :rules="engineFormRules">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="account">
          <el-input
            v-model="engineForm.account"
            placeholder="请输入账号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="engineForm.password"
            placeholder="请输入密码"
            autocomplete="off"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--    工程机多帐号-->
    <!--    <el-dialog-->
    <!--      title="绑定工程机系统"-->
    <!--      :visible.sync="dialogFormVisible"-->
    <!--      :modal="false"-->
    <!--      width="60%"-->
    <!--    >-->
    <!--      <el-form ref="engineForm" :model="engineForm">-->
    <!--        <el-row v-for="(row, index) in engineForm.engineList" :key="row.id" :gutter="20">-->
    <!--          <el-col :span="8">-->
    <!--            <el-form-item-->
    <!--              :label="'账号' + (index+1)"-->
    <!--              :label-width="formLabelWidth"-->
    <!--              :prop="'engineList.' + index + '.enginUserName'"-->
    <!--              :rules="{required: true, message: '请输入工程机账号', trigger: 'blur'}"-->
    <!--            >-->
    <!--              <el-input v-model="row.enginUserName" placeholder="请输入账号" autocomplete="off"></el-input>-->
    <!--            </el-form-item>-->
    <!--          </el-col>-->
    <!--          <el-col :span="8">-->
    <!--            <el-form-item-->
    <!--              :label="'密码' + (index+1)"-->
    <!--              :label-width="formLabelWidth"-->
    <!--              :prop="'engineList.' + index + '.enginPassword'"-->
    <!--              :rules="{required: true, message: '请输入工程机密码', trigger: 'blur'}"-->
    <!--            >-->
    <!--              <el-input v-model="row.enginPassword" placeholder="请输入密码" autocomplete="off" show-password></el-input>-->
    <!--            </el-form-item>-->
    <!--          </el-col>-->
    <!--          <el-col :span="8">-->
    <!--            <template v-if="row.adminUserId">-->
    <!--              <el-button @click="submitForm(index)">重验</el-button>-->
    <!--            </template>-->
    <!--            <template v-else>-->
    <!--              <el-button @click="submitForm(index)">验证</el-button>-->
    <!--            </template>-->

    <!--            <el-button v-if="row.adminUserId" @click="toEngine(index)">打开</el-button>-->
    <!--            <el-button @click="delAccountForm(index)">删除</el-button>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--      </el-form>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="addRowEngine">新增账号</el-button>-->
    <!--        <el-button @click="dialogFormVisible = false">取 消</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import { getRebateOrderMsg } from "@/api/dashboard";
import { mapGetters } from "vuex";
import Breadcrumb from "@/components/Breadcrumb";
import Hamburger from "@/components/Hamburger";
import Screenfull from "@/components/Screenfull";
import NavMenu from "@/components/NavMenu";
import { getNoticeListCount } from "@/api/notice";
import {
  checkEngineAccount,
  bindEngineAccount,
  delEngineAccount,
} from "@/api/setting";
import request from "@/utils/request";

export default {
  data() {
    return {
      intivalId: "",
      timer: "",
      noticeCount: 0,
      userInfo: "",
      engineForm: {
        account: "",
        password: "",
        // engineList: []
      },
      engineFormRules: {
        account: [
          { required: true, message: "请输入工程机账号", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入工程机密码", trigger: "blur" },
        ],
      },
      formLabelWidth: "100px",
      dialogFormVisible: false,
    };
  },
  mounted() {
    const that = this;
    // 开定时器轮询未读消息接口(写在全局vuex里比较好)
    // that.initNotice();
    that.tcMessage();
    this.intivalId = setInterval(function () {
      that.tcMessage();
    }, 5000);
    // this.timer = setInterval(function () {
    //   that.initNotice();
    // }, 3000);
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem("supply_user"));
  },
  beforeDestroy() {
    window.clearInterval(this.intivalId);
    window.clearInterval(this.timer);

    console.log("退出清理定时器" + this.timer);
  },
  components: {
    Breadcrumb,
    Hamburger,
    Screenfull,
    NavMenu,
  },
  computed: {
    showBreadcrumb() {
      return this.$store.state.settings.breadcrumb;
    },
    noticeVisible() {
      return this.noticeCount > 0;
    },
    ...mapGetters(["sidebar", "avatar", "device", "name"]),
  },
  methods: {
    toggleSideBar() {
      this.$store.dispatch("app/toggleSideBar");
    },
    async logout() {
      await this.$store.dispatch("user/logout");
      // this.$router.push(`/login?redirect=${this.$route.fullPath}`)

      this.$router.push(`/login`);
    },
    initNotice() {
      getNoticeListCount().then((res) => {
        if (res.data > 0 && this.noticeCount !== res.data) {
          this.noticeCount = res.data;
        } else if (res.data === 0 && this.noticeCount !== res.data) {
          this.noticeCount = 0;
        }
      });
    },
    async tcMessage() {
      let res = await getRebateOrderMsg();
      if (res.data.hasMessage) {
        this.$notify.info({
          title: "消息",
          message: res.data.messages,
          position: "bottom-right",
          duration: 4000,
          showClose: false,
        });
      }
    },
    goNotice() {
      this.$router.push("/notice/index");
    },
    openEngineAccount() {
      this.engineForm.engineList = this.userInfo.bindEnginList;
      this.dialogFormVisible = true;
    },
    toEngine() {
      const userInfoCopy = this.userInfo;
      if (userInfoCopy && userInfoCopy.bindEngin) {
        checkEngineAccount().then((res) => {
          if (res.code === 200) {
            // this.$refs.engineSubmit.click()
            const { href } = this.$router.resolve({
              name: "open_engin",
            });
            window.open(href, "_blank");
          } else {
            this.$errorMsg("账号密码错误，请重新绑定");
            this.dialogFormVisible = true;
          }
        });
      } else {
        this.dialogFormVisible = true;
      }
    },
    // toEngine(index) {
    //   工程机多帐号
    //   const { href } = this.$router.resolve({
    //     name: "open_engin",
    //     query: {
    //       index: index
    //     }
    //   });
    //   window.open(href, "_blank");
    // },
    // addRowEngine() {
    //   this.engineForm.engineList.push({
    //     adminUserId: '',
    //     enginPassword: '',
    //     enginUserName: '',
    //     status: '',
    //   })
    // },
    submitForm() {
      this.$refs.engineForm.validate((valid) => {
        if (valid) {
          const params = {
            enginUserName: this.engineForm.account,
            enginPassword: this.engineForm.password,
          };
          bindEngineAccount(params).then((res) => {
            if (res.code === 200) {
              this.$successMsg("绑定成功，正在打开工程机系统");
              this.dialogFormVisible = false;
              this.$store.dispatch("user/getInfo").then(() => {
                this.userInfo = JSON.parse(localStorage.getItem("supply_user"));
                const { href } = this.$router.resolve({
                  name: "open_engin",
                });
                window.open(href, "_blank");
              });
            } else {
              this.$errorMsg(res.message);
            }
          });
        }
      });
    },
    // submitForm(index) {
    //   工程机多帐号
    //   this.$refs.engineForm.validate((valid) => {
    //     if (valid) {
    //       const params = {
    //         enginUserName: this.engineForm.engineList[index].enginUserName,
    //         enginPassword: this.engineForm.engineList[index].enginPassword,
    //         isReset: this.engineForm.engineList[index].adminUserId !== ''
    //       };
    //       bindEngineAccount(params).then((res) => {
    //         if (res.code === 200) {
    //           this.$successMsg("绑定成功，工程机系统");
    //           this.$store.dispatch("user/getInfo").then(() => {
    //             this.userInfo = JSON.parse(localStorage.getItem("supply_user"));
    //             this.engineForm.engineList = this.userInfo.bindEnginList
    //           });
    //         } else {
    //           this.$errorMsg(res.message);
    //         }
    //       });
    //     }
    //   });
    // },
    // delAccountForm(index) {
    //   if (this.engineForm.engineList[index].id) {
    //     this.$confirm('此操作将删除账号, 是否继续?', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning',
    //       center: true
    //     }).then(() => {
    //       delEngineAccount({id: this.engineForm.engineList[index].id}).then(() => {
    //         this.$store.dispatch("user/getInfo").then(() => {
    //           this.userInfo = JSON.parse(localStorage.getItem("supply_user"));
    //           this.engineForm.engineList = this.userInfo.bindEnginList
    //         });
    //         this.$successMsg("删除成功");
    //       })
    //     }).catch(() => {
    //     });
    //   } else {
    //     this.engineForm.engineList.splice(index, 1)
    //   }
    // }
  },
};
</script>

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

.navbar {
  width: 100%;
  height: 50px;
  overflow: hidden;
  background: #{$navbarBg};
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  .hamburger-container {
    line-height: 46px;
    height: 100%;
    color: #{$navbarText};
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;
    border-right: 1px solid #eaeaea;
    &:hover {
      background: rgba(0, 0, 0, 0.025);
    }
  }

  .navmenu {
    float: left;
  }

  .breadcrumb-container {
    float: left;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;
    & > div {
      float: left;
    }
    &:focus {
      outline: none;
    }
    .user-container {
      height: 50px;
      .user {
        i {
          font-size: 18px;
          margin-right: 5px;
        }
        span {
          font-size: 16px;
        }
      }
    }
    .right-menu-item {
      display: inline-block;
      padding: 0 15px;
      height: 100%;
      font-size: 18px;
      color: #{$navbarText};
      vertical-align: text-bottom;
      border-left: 1px solid #eaeaea;
      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
      .notice-icon {
        padding-top: 0;
        padding-bottom: 0;
      }
    }
  }
}
</style>

<style lang="scss">
.navbar {
  .right-menu {
    .right-menu-item {
      .notice-icon > i {
        font-size: 18px;
      }
      sup {
        top: 12px;
        right: 25px;
      }
    }
  }
}
</style>
