<template>
  <div class="headers" :style="{backgroundColor: color}">
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="1" style="height: 100%">
        <div class="logo"></div>
      </el-col>
      <el-col :span="4" style="height: 100%">
        <span class="title">数智牧场管理系统</span>
      </el-col>
      <el-col :span="10" :offset="9" style="height: 100%">
        <div class="flex">
          <div class="user" style="width: 180px;">
            <div>
              <el-select @change="onChange" size="mini" v-model="farmId">
                <el-option v-for="item in getFarmList" :key="item.id" :label="item.farmName" :value="item.id"></el-option>
              </el-select>
            </div>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="user" style="width: 250px;">
            <div>
              <el-switch
                  style="display: block"
                  v-model="$store.state.mode"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="多级导航"
                  inactive-text="折叠导航"
                  @change="changeMode">
              </el-switch>
            </div>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="user" style="width: 100px;">
            <div>
              <i class="el-icon-user-solid" style="font-size: 28px"></i>
            </div>
            <div>
              <el-popover
                  placement="bottom"
                  width="400"
                  trigger="hover">
                  <div style="padding: 10px">
                    <div style="width: 100%;">
                      <span style="color: #BBBBBB;">账户信息</span>
                      <span class="user-right">账户设置</span>
                    </div>
                    <el-divider></el-divider>
                    <el-button type="text" @click="dialogVisible = true">修改密码</el-button>
<!--                    <ul>-->
<!--                      <li>职位： <span class="user-color">厂长</span></li>-->
<!--                      <li>本次登录： <span class="user-color">厂长</span></li>-->
<!--                      <li>本次登录： <span class="user-color">厂长</span></li>-->
<!--                      <li>上次登录： <span class="user-color">厂长</span></li>-->
<!--                    </ul>-->
                  </div>
                <span slot="reference">{{userName}}</span>
              </el-popover>
            </div>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="user">
            <div style="width: 100%; text-align: center">
              <router-link to="/">
                <i class="home" title="首页"></i>
              </router-link>
            </div>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="user">
            <div style="width: 100%; text-align: center">
              <el-popover
                  placement="bottom"
                  width="270"
                  trigger="hover">
                <div class="color_flex">
                  <chrome-picker :value="color" @input="cut"></chrome-picker>
<!--                  <div v-for="item in colorList" :style="{backgroundColor: item.color}" :key="item.id" class="box" @click="cut(item.color)">-->
<!--                    <span>点击换肤</span>-->
<!--                  </div>-->
                </div>
                <i slot="reference" class="colour"></i>
              </el-popover>
            </div>
          </div>
          <el-divider direction="vertical"></el-divider>
          <div class="user">
            <div style="width: 100%; text-align: center">
              <i class="guanbi" @click="logout" title="退出登录"></i>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog
      title="修改密码"
      ref="passForms"
      width="30%"
      :visible.sync="dialogVisible"
      @close="passReset"
    >
      <div>
        <el-form :model="passWordForm" :rules="passWordRules" label-width="80px" ref="passForms">
          <el-form-item label="原密码" prop="password">
            <el-input type="password" v-model="passWordForm.password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="onePassWord">
            <el-input type="password" v-model="passWordForm.onePassWord"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="passWordForm.checkPass" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
                <el-button @click="passReset">取 消</el-button>
                <el-button type="primary" @click="onPassSubmit('passForms')">保 存</el-button>
              </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import {findUpdate, getFarmId, findOne, editPassWord} from '../utils/api';
import { Chrome } from 'vue-color';
import { Debounce } from "../utils";

export default {
  name: "HeaderElement",
  computed: {
    ...mapState(['color', 'farmList', 'farmId', 'userName'])
  },
  components: {
    // 'slider-picker': Slider,
    'chrome-picker': Chrome
  },
  watch: {
    farmList: {
      handler(newVal) {
        if(newVal.length > 0) {
          this.getFarmList = []
          newVal.forEach(item => {
            if(item.rowStatus) {
              this.getFarmList.push(item)
            }
          })
        }
      },
      deep: true
    }
  },
  data() {
    let validPassword=(rule,value,callback)=>{
      let reg= /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/
      if(!reg.test(value)){callback(new Error('密码必须是字母+数字组合6-16位密码'))
      }else{
        callback()
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passWordForm.onePassWord) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    let validatePass3 = (rule, value, callback) => {
      let password = localStorage.getItem('password')
      if(value === '') {
        callback(new Error('请输入原密码'));
      } else if (value !== password) {
        callback(new Error('原密码错误!'));
      } else {
        callback();
      }
    }
    return {
      getFarmList: [],
      dialogVisible: false,
      passWordForm: {
        account: '',
        password: '',
        onePassWord: '',
        checkPass: ''
      },
      passWordRules: {
        password: [
          { validator: validatePass3, trigger: 'blur' }
        ],
        onePassWord: [
          { validator: validPassword, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      },
      account: '',
      password: '',
    }
  },
  methods: {
    ...mapActions(['setModeAsync', 'setColorAsync', 'GetFarm', 'setFarmIdAsync']),
    cut: Debounce(function(data) {
      this.setColorAsync(data.hex)
      let params = {
        id: localStorage.getItem('UserId'),
        color: data.hex
      }
      findUpdate(params).then(res => {
        if(res.code === 10000) {
          console.log(res)
        }
      })
    }),
    changeMode(val) {
      let params = {
        id: localStorage.getItem('UserId'),
        mode: val
      }
      findUpdate(params).then(res => {
        console.log(res)
      })
      this.setModeAsync(val)
    },
    logout() {
      localStorage.removeItem('UserName');
      localStorage.removeItem('accessToken');
      localStorage.removeItem('UserId');
      localStorage.removeItem('lastFarmId')
      localStorage.removeItem('password')
      this.$router.replace('/login');
    },
    // 拿到farmid
    init() {
      getFarmId({}).then(res => {
        console.log(res)
        if(res.code == 10000) {
          this.setFarmIdAsync(res.data);
          localStorage.setItem('lastFarmId', res.data);
        }
      })
      let params = {
        id: localStorage.getItem('UserId'),
      }
      findOne(params).then(res => {
          if(res.code == 10000) {
            localStorage.setItem('password', res.data.password);
          }
      })
    },
    // 选择牧场
    onChange(val) {
      let params = {
        id: localStorage.getItem('UserId'),
        lastFarmId: val
      }
      localStorage.setItem('lastFarmId', val)
      findUpdate(params).then(res => {
        console.log(res.data)
        setTimeout(() => {
          location.reload();
        }, 1000)
      })
      this.setFarmIdAsync(val);
    },
    passReset() {
      this.dialogVisible = false;
      this.passWordForm = {
        account: '',
        password: '',
        onePassWord: '',
        checkPass: '',
      }
    },
    onPassSubmit(ElForm) {
      this.$refs[ElForm].validate((valid) => {
        if(valid) {
          let params = {
            account: localStorage.getItem('UserName'),
            password: this.passWordForm.password,
            newPassword: this.passWordForm.onePassWord
          }
          editPassWord(params).then(res => {
            if(res.code === 10000) {
              this.$message.success('修改密码成功!将重新登录')
              setTimeout(() => {
                this.logout()
              }, 1000);
            } else {
              this.$message.error('修改密码失败!')
            }
          }).finally(() => {
            this.passReset()
          })
        }
      })
    }
  },
  created() {
    this.GetFarm()
  },
  mounted() {
    this.init();
  }
}
</script>

<style scoped>
p {
  margin: 0;
  display: inline-block;
  position: relative;
}
/deep/.el-row {
  margin: 0 !important;
}
/deep/.el-divider--vertical {
  margin: 0 15px;
}
/deep/.el-switch__label {
  color: white;
}
.headers {
  width: 100%;
  height: 50px;
}
.logo {
  width: 50px;
  height: 50px;
  margin: 0 auto;
  background-image: url("../assets/logo.png");
  background-size: 100% 100%;
}
.title {
  font-size: 18px;
  font-weight: 700;
  line-height: 50px;
  color: #fff;
}
.flex {
  width: 100%;
  height: 50px;
  color: #fff;
  display: flex;
  align-items: center;
}
.user {
  width: 80px;
  height: 50px;
  display: flex;
  align-items: center;
  cursor: pointer;
}
.user-right {
  float: right;
  margin-right: 10px;
  cursor: pointer;
  color: #31C3A6;
}
li {
  margin-bottom: 10px;
  color: #BBBBBB;
}
.user-color {
  color: #000
}
.colour {
  display: inline-block;
  width: 32px;
  height: 32px;
  background-image: url("../assets/images/colour.png");
  background-size: 100% 100%;
}
.color_flex {
  width: 100%;
  height: 260px;
  padding: 10px;
}
.box {
  cursor: pointer;
  text-align: center;
  color: #fff;
  line-height: 80px;
}
.box:hover {
  content: '点击换肤';
}
.guanbi {
  display: inline-block;
  width: 32px;
  height: 32px;
  background-image: url("../assets/images/guanbi.png");
  background-size: 100% 100%;
}
.home {
  display: inline-block;
  width: 28px;
  height: 28px;
  background-image: url("../assets/images/home.png");
  background-size: 100% 100%;
}
</style>
