<template>
  <div>

    <el-select id="deptSelector" v-model="selectValue" placeholder="请选择" @change="mychange">
      <el-option  :key="index" :value="dept.deptId" :label="dept.deptName" v-for="(dept,index) in selectList">
      </el-option>
    </el-select>
  </div>
</template>

<script>
  import {getDepts} from '@/api/sysutils/deptselector'
  import {setToken} from '@/utils/auth'
  import Cookies from 'js-cookie'

  export default {
    name: "deptSelector",
    props:{
      setValue : Function
    },
    created() {
      this.showDepts();
    },
    data(){
      return {
        selectDeptCookieKey: "Global-Dept",
        selectValue: '',
        selectList: [],
      }
    },
    methods :{

      mychange : function(){
        this.setValue(this.selectValue);
        Cookies.set(this.selectDeptCookieKey, this.selectValue)
      },

      showDepts(){
        let _this = this;
        let username = Cookies.get("username")
        console.log("$$$$",username)
        getDepts({userName:username}).then(resp =>{
          let deptList = new Array();
          console.log("!!!!!!",resp);
          let depts = resp.data.depts;
          let deptParties = resp.data.deptParties;
          for (let i = 0; i < depts.length; i++) {
            let dept = new Object();
            dept.deptId = depts[i].deptId;
            dept.deptName = depts[i].deptName;
            deptList.push(dept);
          }
          for (let i = 0; i < deptParties.length; i++) {
            let dept = new Object();
            dept.deptId = deptParties[i].deptId;
            dept.deptName = deptParties[i].deptName;
            deptList.push(dept);
          }
          _this.selectList = deptList;
          if(deptList.length == 0){//当前用户没有部门
            //alert("当前用户没有部门")
            return;
          }
          let cookie = Cookies.get(this.selectDeptCookieKey);
          if(cookie != null){//cookie 获取到了 证明曾经触发过 onchange
            console.log(cookie+'=cookie 获取到了 证明曾经触发过 onchange');
            let isCookieExists = false;
            deptList.forEach((dept) => {
              if(cookie == dept.deptId){
                isCookieExists = true;
                _this.selectValue = dept.deptId;
                _this.setValue(_this.selectValue);
                //break;
              }
            });
            if(isCookieExists == false) {//cookie存在但当前不在那个部门了
              console.log("cookie存在但当前不在那个部门了");
              _this.selectValue = deptList[0].deptId;
              _this.setValue(_this.selectValue);
            }
          }else {
            _this.selectValue = deptList[0].deptId;
            _this.setValue(_this.selectValue);
            console.log(cookie+'=cookie false');
          }
          // this.$emit("wangzhe",xxxxx)
        })
      }
    }
  }
</script>

<style scoped>

</style>
