<template>
  <nav class="site-navbar" :class="'site-navbar--' + navbarLayoutType">
    <div class="site-navbar__header">
      <h1 class="site-navbar__brand" @click="$router.push({ name: 'home' })">
        <a class="site-navbar__brand-lg" href="javascript:;">智慧养殖云平台</a>
        <a class="site-navbar__brand-mini" href="javascript:;">养殖</a>
      </h1>
    </div>
    <div class="site-navbar__body clearfix">
      <el-menu
        class="site-navbar__menu"
        mode="horizontal">
        <el-menu-item class="site-navbar__switch" index="0" @click="sidebarFold = !sidebarFold">
          <icon-svg name="zhedie"></icon-svg>
        </el-menu-item>
      </el-menu>
      <el-menu
        class="site-navbar__menu site-navbar__menu--right"
        mode="horizontal">
        <el-menu-item>
          <!-- 拥有牧场 id 的不允许选择牧场，没有的则允许 -->
          <template slot="title" v-if="farmId > 0">
            <span>{{farmName}}</span>
          </template>
          <template slot="title" v-else>
            <el-select
              placeholder="牧场"
              v-model="formFarmId"
              @change="farmChange"
              size="mini"
              style="width: 120px">
              <el-option
                v-for="item in farmList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-menu-item>
        <el-menu-item index="1" @click="$router.push({ name: 'theme' })">
          <template slot="title">
            <!-- <el-badge value="new"> -->
              <icon-svg name="shezhi" class="el-icon-setting"></icon-svg>
            <!-- </el-badge> -->
          </template>
        </el-menu-item>
        <!-- <el-menu-item index="2">
          <el-badge value="hot">
            <a href="https://www.renren.io/" target="_blank">官方社区</a>
          </el-badge>
        </el-menu-item>
        <el-submenu index="3">
          <template slot="title">Git源码</template>
          <el-menu-item index="2-1"><a href="https://github.com/renrenio/renren-fast-vue" target="_blank">前端</a></el-menu-item>
          <el-menu-item index="2-2"><a href="https://gitee.com/renrenio/renren-fast" target="_blank">后台</a></el-menu-item>
          <el-menu-item index="2-3"><a href="https://gitee.com/renrenio/renren-generator" target="_blank">代码生成器</a></el-menu-item>
        </el-submenu> -->
        <el-menu-item class="site-navbar__avatar" index="3">
          <el-dropdown :show-timeout="0" placement="bottom">
            <span class="el-dropdown-link">
              <!-- <img src="~@/assets/img/avatar.png" :alt="userName">{{ userName }} -->
              <img src="~@/assets/img/pig.png" :alt="userName" style="height: 40px">
              {{ userName }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="updatePasswordHandle()">修改密码</el-dropdown-item>
              <el-dropdown-item @click.native="logoutHandle()">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </div>
    <el-dialog
      title="请选择牧场"
      :visible="dialogVisible"
      width="30%"
      :modal-append-to-body="false">
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="80px"
        size="mini"
        style="margin-left: 20px;width: 500px">
        <el-form-item label="牧场名称" prop="farmId">
          <el-select
            placeholder="牧场"
            v-model="dataForm.farmId"
            :disabled="farmId > 0">
            <el-option
              v-for="item in farmList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗, 修改密码 -->
    <update-password v-if="updatePassowrdVisible" ref="updatePassowrd"></update-password>

  </nav>
</template>

<script>
  import UpdatePassword from './main-navbar-update-password'
  import { clearLoginInfo } from '@/utils'
  export default {
    data () {
      return {
        updatePassowrdVisible: false,
        farmId: 0,
        farmName: '',
        farmList: [], // 牧场List
        formFarmId: Number(localStorage.getItem('farmId')),
        dialogVisible: false,
        dataForm: {
          farmId: ''
        },
        dataRule: {
          farmId: [
            { required: true, message: '牧场名称不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    mounted () {
      this.getDataList()
      // this.initFind()
    },
    components: {
      UpdatePassword
    },
    computed: {
      navbarLayoutType: {
        get () { return this.$store.state.common.navbarLayoutType }
      },
      sidebarFold: {
        get () { return this.$store.state.common.sidebarFold },
        set (val) { this.$store.commit('common/updateSidebarFold', val) }
      },
      mainTabs: {
        get () { return this.$store.state.common.mainTabs },
        set (val) { this.$store.commit('common/updateMainTabs', val) }
      },
      userName: {
        get () { return this.$store.state.user.name }
      }
    },
    methods: {
      // 判断是否是第一次进入
      initFind () {
        this.$http({
          url: this.$http.adornUrl('/sys/user/findLatestChooseFarm'),
          methods: 'get'
        }).then(res => {
          if (res.data === '') {
            this.dialogVisible = true
          } else {
            this.formFarmId = res.data
            this.$cookie.set('farmId', this.formFarmId)
            localStorage.setItem('farmId', this.formFarmId)
            this.$cookie.set('formFarmId', this.formFarmId)
          }
        })
      },
      // 获取牧场List
      getDataList () {
        // this.dialogVisible = true
        this.farmId = this.$cookie.get('farmId') === 'null' ? undefined : parseInt(this.$cookie.get('farmId'))
        // if (this.farmId || this.$cookie.get('formFarmId')) {
        //   this.dialogVisible = false
        //   this.formFarmId = this.farmId || (parseInt(this.$cookie.get('formFarmId')) || '')
        // }
        this.$http({
          url: this.$http.adornUrl('/management/farm/findAll'),
          method: 'post'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.farmList = data.all
          } else {
            this.farmList = []
            this.$message.error(data.msg)
          }
        })
        // 判断cookie里的 farmId 是否为 null
        if (this.$cookie.get('farmId') === 'null') {
          this.initFind()
        }
        this.getFarmName()

        // this.farmId = this.$cookie.get('farmId') === 'null'? undefined: parseInt(this.$cookie.get('farmId'))
        // if (this.formFarmId) {

        //   return
        // }
      },
      submit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.formFarmId = this.dataForm.farmId
            this.$cookie.set('formFarmId', this.formFarmId)
            localStorage.setItem('farmId', this.formFarmId)
            this.dialogVisible = false
            this.$http({
              url: this.$http.adornUrl('/sys/user/saveChooseFarm'),
              methods: 'get',
              params: this.$http.adornParams({farmId: this.dataForm.farmId}, false)
            })
                .then(res => {
                  console.log(res)
                })
          }
        })
      },
      // 选择牧场
      farmChange (val) {
        // 管理员选择牧场
        this.$cookie.set('formFarmId', val)
        localStorage.setItem('farmId', val)
        this.$http({
          url: this.$http.adornUrl('/sys/user/saveChooseFarm'),
          methods: 'get',
          params: this.$http.adornParams({farmId: val})
        })
        .then(res => {
          if (res.data.code === 0) {
            location.reload()
          }
        })
      },
      // 弹框framid确认
      dataFormSubmit () {
        this.$http({
          url: this.$http.adornUrl('/sys/user/saveChooseFarm'),
          methods: 'get',
          params: this.$http.adornParams({farmId: this.dataForm.farmId})
        })
        .then(res => {
          console.log(res)
        })
      },
      // 获取牧场名称
      getFarmName() {
        // this.farmName = this.farmId? this.farmList.filter(item => item.id === this.farmId)[0].name: 0
        this.$http({
          url: this.$http.adornUrl('/sys/user/info'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            // this.loading = false
            // this.userId = data.user.userId
            // this.userName = data.user.username
            this.farmId = data.user.farmId || 0
            this.farmName = this.farmId? this.farmList.filter(item => item.id === this.farmId)[0].name: 0
            // this.token = data.user.token
          }
        })
      },
      // 修改密码
      updatePasswordHandle () {
        this.updatePassowrdVisible = true
        this.$nextTick(() => {
          this.$refs.updatePassowrd.init()
        })
      },
      // 退出
      logoutHandle () {
        this.$confirm(`确定进行[退出]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/logout'),
            method: 'post',
            data: this.$http.adornData()
          }).then(({data}) => {
            if (data && data.code === 0) {
              clearLoginInfo()
              this.$router.push({ name: 'login' })
            }
          })
        }).catch(() => {})
      }
    }
  }
</script>
