<template>
  <div class="header-box">
    <!--<div class="edit" @click="handleCommand">退出登录</div>-->

    <el-dropdown class="edit" trigger="click" @command="handleCommand">
       <span class="el-dropdown-link" style="display: flex">
           <span style="font-size: 15px;line-height: 25px;color: #fff;margin-right:10px;display: flex;">
               <svg-icon class="logo-tou" icon-class="logoTou"/>
               <span>{{userName}}</span>
           </span>
          <i class="el-icon-caret-bottom"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item
          v-for="(item,value) in status"
          :key="value"
          :command="item.key"
        >{{ item.lab }}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <template>
      <div class="logo-box">
        <img :src="companyLogo" />
        {{ companyName }}
      </div>
    </template>
    <el-menu
      :default-active="defaultActive"
      router
      class="el-menu-demo"
      mode="horizontal"
      background-color="#000"
      text-color="#999"
    >
      <el-menu-item index="/home">主页</el-menu-item>
      <el-menu-item index="/bayed">已购服务</el-menu-item>
      <el-menu-item index="/companyInfoIndex">公司信息</el-menu-item>
      <!-- <el-menu-item index="/travelCompanyIndex">往来公司</el-menu-item> -->
      <el-menu-item index="/organizationIndex">组织架构</el-menu-item>
      <!--<el-menu-item :index="routerLink">组织架构</el-menu-item>-->
      <el-menu-item index="/check-flow">审核流设置</el-menu-item>
      <!-- <el-menu-item v-if="serviceType == 'ship' || serviceType == 'both'" index="/shipManagement">船端管理</el-menu-item> -->
    </el-menu>

    <el-dialog
      :title="uploadTitle"
      :visible.sync="uploadUserFlag"
      width="525px"
      :close-on-click-modal="false"
      append-to-body
      @close="cancel"
      class="upload-user"
    >
      <el-form
        ref="loginMsg"
        :model="loginMsg"
        :rules="loginMsgRules"
      >
        <el-form-item label="当前管理员：" prop="userRealName" v-if="lastStepFlag">
          <span>{{ loginMsg.userRealName }}</span>
        </el-form-item>
        <el-form-item label="新的企业管理员：" prop="userRealName" v-else>
          <el-select v-model="loginMsg.userRealName" placeholder="请选择" @change="newUser" style="width: 315px;">
            <el-option
              v-for="item in userList"
              :key="item.staffMobilePhone"
              :label="item.staffName"
              :value="item.staffMobilePhone"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号：" prop="userCellPhone">
          <el-input v-model="loginMsg.userCellPhone" :disabled="true" style="width: 200px;vertical-align: top;" />
          <el-button
            :type="buttonState"
            class="send-button"
            :disabled="buttonDisable"
            :class="{stateGray:buttonDisable}"
            @click="sendNum(userCellPhone,loginMsg.userRealName)"
          >{{ buttonMsg }}</el-button>
        </el-form-item>
        <el-form-item label="验证码：" prop="veriCode">
          <el-input v-model="loginMsg.veriCode" style="width: 318px;" />
        </el-form-item>
        <div class="next-button" v-if="lastStepFlag"><el-button @click="nextStyle('loginMsg')">下一步</el-button></div>
        <div class="next-button" v-else><el-button type="primary" @click="saveStyle('loginMsg')">确定</el-button></div>
      </el-form>
    </el-dialog>

    <!--修改密码-->
    <el-dialog
      title="修改密码"
      :visible.sync="passwordFlag"
      width="525px"
      :close-on-click-modal="false"
      append-to-body
      @close="cancelPaw"
      class="upload-user password"
    >
      <el-form
        ref="passwordMsg"
        :model="passwordMsg"
        :rules="passwordMsgRules"
      >
        <el-form-item label="当前密码：" prop="originalPassword">
          <el-input type="password" placeholder="请输入当前密码" v-model="passwordMsg.originalPassword"  style="width: 318px;" />
        </el-form-item>
        <el-form-item label="新密码：" prop="newPassword">
          <el-input type="password" v-model="passwordMsg.newPassword" placeholder="密码为6-20位字母及数字组合" style="width: 318px;" />
        </el-form-item>
        <el-form-item label="确认密码：" prop="password">
          <el-input type="password" v-model="passwordMsg.password" placeholder="密码为6-20位字母及数字组合" style="width: 318px;" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordFlag = false">取 消</el-button>
        <el-button type="primary" @click="savePassword('passwordMsg')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

import {
  validPassword
} from "../../utils/validate";

const validPasswordRule = function(rule, value, callback) {
  if (!validPassword(value)) {
    callback(new Error('密码为6到20位数字密码任意组合'));
  } else {
    callback();
  }
};
const validPasswordRule2 = function(rule, value, callback) {
  if (!value) {
    callback(new Error('请再次输入密码'));
  } else if (value !== this.passwordMsg.newPassword) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

import {
  getLoginInfo,
  changePasswordByPwd,
  sendMsg,
  checkMsg,
  changeManager,
} from '../../api/loginOut';
import { getstaffsHasTelByDept } from '../../api/basicData';
export default {
  name: 'Navigation',
  data() {
    return {
      userName: localStorage.getItem('enterprise-front-userRealName'),
      companyName: localStorage.getItem('enterprise-front-companyName'),
      uploadUserFlag: false,
      uploadTitle:'',
      loginMsgRules:{
        userCellPhone: [{required: true, trigger: 'blur'}],
        userRealName: [{required: true,trigger: 'blur'}],
        veriCode: [{required: true,trigger: 'blur'}],
      },
      loginMsg:{
        userCellPhone: '',
        userRealName: '',
        veriCode: ''
      },
      passwordMsgRules:{
        originalPassword: [{ required: true, message: ' ', trigger: 'blur' }],
        newPassword: [{ required: true, trigger: 'blur', validator: validPasswordRule.bind(this) }],
        password: [{ required: true, trigger: 'blur', validator: validPasswordRule2.bind(this) }],
      },
      passwordMsg:{
        originalPassword: '', // 原始密码
        newPassword: '', // 新密码
        password: '' // 二次输入密码
      },
      userCellPhone: '',
      oldVeriCode: '',
      buttonState: 'primary',
      buttonDisable: false,
      passwordFlag: false,
      lastStepFlag: true,
      buttonMsg: '发送验证码',
      timer: null,
      userList:[],
    };
  },
  computed: {
    userName(){

    },
    companyLogo(){
      return !this.$store.getters.companyLogo? require('../../static/images/page/login/login.png'): this.$store.getters.companyLogo
    },
    status() {
      return [
        {
          lab: '修改密码',
          key: '0',
        },
        {
          lab: '更换企业管理员',
          key: '1',
        },
        {
          lab: '退出',
          key: '2',
        }
      ]
    },
    defaultActive() {
      return this.$route.matched[this.$route.matched.length - 1].path;
    },
    // routerLink() {
    //   let type = ''
    //   if (this.serviceType === 'ship') {
    //     type = '/organizationShip'
    //   } else {
    //     type = '/organization'
    //   }
    //   return type
    // },
    ...mapGetters({
      serviceType: 'serviceType'
    })
  },
  methods: {
    cancelPaw(){
      this.$refs.passwordMsg.resetFields();
    },
    cancel(){
      this.$refs.loginMsg.resetFields();
    },
    // 下拉选择
    handleCommand(command) {
      // 退出
      if(command === '2') {
        this.$store.dispatch('user/logout');
        this.$router.push(`/login?redirect=${this.$route.fullPath}`);
        // 更换企业管理员
      } else if(command === '1') {
        this.uploadTitle = '换绑企业管理员账号，需要验证当前企业管理员账号的身份';
        this.uploadUserFlag = true;
        this.getloading();
        // 修改密码
      } else {
        this.passwordFlag = true;
      }
    },
    // 修改管理员密码
    savePassword(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = {
            originalPassword: this.passwordMsg.originalPassword,
            password: this.passwordMsg.password
          };
          changePasswordByPwd(data).then(() => {
            this.$message({
              message: '修改成功',
              type: 'success',
              showClose: true,
            });
            this.passwordFlag = false;
          }).catch((code) => {
            if (code === 'AUTH_005') {
              this.$message({
                message: '原始密码不正确!',
                type: 'error',
                showClose: true,
              });
              return false;
            } if (code === 'AUTH_006') {
              this.$message({
                message: '新密码与原始密码相同!',
                type: 'error',
                showClose: true,
              });
            }
          });
        } else {
          this.$message({
            message: '带*号为必填项!',
            type: 'error',
            showClose: true,
          });
          return false;
        }
      });
    },
    // 确认修改管理员
    saveStyle(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let index = this.userList.findIndex(itm => itm.staffMobilePhone === this.loginMsg.userRealName)
          let newManagerId = this.userList.find(
            item => item.staffMobilePhone === this.loginMsg.userRealName
          ).staffId
          const data = {
            newManagerId: newManagerId,
            originalManagerVeriCode: this.oldVeriCode,
            newManagerVeriCode: this.loginMsg.veriCode
          };
          changeManager(data).then(() => {
            this.$message({
              message: '修改成功',
              type: 'success',
              showClose: true,
            });
            localStorage.setItem('enterprise-front-userRealName', this.userList[index].staffName)
            let dom = document.getElementsByClassName("hello-title")[0]
            dom.textContent = dom.textContent.split('，')[0] + '，' + this.userList[index].staffName
            this.userName = this.userList[index].staffName
            clearInterval(this.timer);
            this.buttonMsg = '发送验证码';
            this.buttonState = 'primary';
            this.buttonDisable = false;
            this.uploadUserFlag = false;
            this.cancel();
          }).catch(() => {
            this.$message({
              message: '修改失败',
              type: 'error',
              showClose: true,
            });
          });
        } else {
          this.$message({
            message: '带*号为必填项',
            type: 'error',
            showClose: true,
          });
          return false;
        }
      });
    },
    // 获取部门下成员岸端
    getUserList() {
      getstaffsHasTelByDept({
        enabled: '1',
        vesselBankFlag: 'B'
      }).then(response => {
        this.userList = response.records;
      }).catch(err=>{
        if(err){
          this.$message({
            message: '公司岸端成员加载失败，请重新获取！',
            type: 'error',
            showClose: true,
          });
        }
      })
    },
    // 当前登录人基本信息
    getloading() {
      getLoginInfo().then((response) => {
        let phonenum = response.managerMobilePhone;
        this.userCellPhone = phonenum;
        phonenum = phonenum.split('');
        phonenum.splice(3, 4, '****');
        phonenum = phonenum.join('');
        this.loginMsg.userCellPhone = phonenum;
        this.loginMsg.userRealName = response.managerName;
      });
    },
    // 下一步
    nextStyle(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = {
            mobilePhone: this.userCellPhone,
            veriCode: this.loginMsg.veriCode
          };
          this.oldVeriCode = JSON.parse(JSON.stringify(this.loginMsg.veriCode));
          checkMsg(data).then((response) => {
            if (response) {
              this.$message({
                message: '验证成功',
                type: 'success',
                showClose: true,
              });
              this.uploadTitle = '修改完成后，绑定的安全手机号也会修改';

              clearInterval(this.timer);

               this.buttonMsg = '发送验证码';
               this.buttonState = 'primary';
               this.buttonDisable = false;
               this.cancel();
               this.lastStepFlag = false;
               this.getUserList();

            } else {
              this.$message({
                message: '验证码填写错误，请检查后重试',
                type: 'error',
                showClose: true,
              });
            }
          }).catch(() => {
            this.$message({
              message: '验证失败',
              type: 'error',
              showClose: true,
            });
          });
        } else {
          this.$message({
            message: '验证码不能为空',
            type: 'error',
            showClose: true,
          });
          return false;
        }
      });
    },
    // 第二次发送验证
    newUser(phone){
      this.userCellPhone = phone;
      phone = phone.split('');
      phone.splice(3, 4, '****');
      phone = phone.join('');
      this.loginMsg.userCellPhone = phone;
    },
    // 发送验证码
    sendNum(mobilePhone, userKind) {
      if (mobilePhone === '' && userKind === '') {
        this.$message({
          message: '企业管理员及电话号不能为空',
          type: 'error',
          showClose: true,
        });
      } else {
        let data = {};
        if(this.lastStepFlag){
          data = {
            mobilePhone,
            domainName: localStorage.getItem('enterprise-front-domainName'),
            companyId: localStorage.getItem('enterprise-front-companyId')
          };
        }else{
          data = {
            mobilePhone,
            domainName: localStorage.getItem('enterprise-front-domainName'),
            userKind : "STAFF",
            companyId: localStorage.getItem('enterprise-front-companyId')
          };
        }
        sendMsg(data).then(() => {
          this.$message({
            message: '验证码已发出，请注意查收',
            type: 'success',
            showClose: true,
          });
          this.buttonMsg = '重试(  60  ) ';
          this.buttonState = 'info';
          this.buttonDisable = true;
          this.setS();
        }).catch(() => {
          this.$message({
            message: '验证码发送失败，请重试',
            type: 'error',
            showClose: true,
          });
        });
      }
    },
    // 计时器
    setS() {
      let s = 60;
      this.timer = setInterval(() => {
        if (s > 0) {
          s -= 1;
          this.buttonMsg = '重新(  ' + s + '  ) ';
        } else {
          this.buttonMsg = '重试';
          this.buttonState = 'primary';
          this.buttonDisable = false;
          clearInterval(this.timer);
        }
      }, 1000);
    },
  }
};
</script>

<style scoped lang="scss">
  .send-button {
    height: 32px;
    line-height: 16px;
    vertical-align: top;
    width: 112px;
  }
  .stateGray {
    color: #333333;
  }
.header-box {
  display: flex;
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  background-color: black;
  .logo-box {
    position: absolute;
    left: 80px;
    display: flex;
    align-items: center;
    height: 60px;
    line-height: 60px;
    color: #999;
    font-size: 15px;
    img {
      padding-bottom: 2px;
      height: 19px;
      width: 19px;
      margin-right: 8px;
    }
  }
}
.edit {
  top: 20px;
  position: absolute;
  right: 23px;
  color: rgb(153, 153, 153);
  font-size: 18px;
  padding-bottom: 20px;
  cursor: pointer;
}
.edit-title {
  top: 20px;
  position: absolute;
  right: 48px;
  font-size: 15px;
  line-height: 25px;
  color: #fff;
  cursor: pointer;
  span{
    vertical-align: top;
  }
}
  .logo-tou {
    width: 38px !important;
    height: 25px !important;
    margin-right: 5px;
  }
  .next-button {
    text-align: left;
    width: 208px;
    margin: 0 auto;
  }
  .upload-user {
    /deep/ .el-form-item__label {
      flex: 0 0 140px;
    }
  }
  .password {
    /deep/ .el-form-item__error {
      display: block;
    }
  }

</style>
