<script type="text/javascript">
import Vue from "vue";
import axios from "axios";
import app from "@/main";
import ajaxAuth from "@/script/api/auth";
import Service from "@/script/api/service";


const userInfo = JSON.parse(window.localStorage.getItem("userInfo"));
const token = window.localStorage.getItem("token");

/**权限指令 v-per="'资源公海-邀约电话'" **/
Vue.directive('per', {
  bind: function (el, binding,vnode) {
    if (!Vue.prototype.$_has(binding.value)) {
      el.style.display = 'none';
    }
  }
});

//校验button权限 {{$_has('资源公海-邀约电话')}}
Vue.prototype.$_has = function (value) {
  let isExist = false;
  let buttonperm =JSON.parse(window.localStorage.getItem("buttonperm"));//['资源公海-电话邀约','资源公海-信息完善-保存']

  for (let i = 0; i < buttonperm.length; i++) {
    // if (buttonperm[i].indexOf(value) > -1) {
      if (buttonperm[i]==value) {
      isExist = true;
      break;
    }
  }
  return isExist;
};

const initUserAuth = function() {
  ajaxAuth
    .$ajaxFindoneuser({
      userId:  JSON.parse(window.localStorage.getItem("userInfo")).id
    })
    .then(res => {
      // console.log("System oauth loading..."+res);
      if (
        res.data.errno == 402 ||
        res.data.errno == "402" ||
        res.data.errno != 0
      ) {
        this.$message.warning("身份认证失败，请登陆！");
        this.$router.push("/login");
      } else {
        let userPerm = res.data.data.userPerm;

        let allProvince=res.data.data.allProvince;
        let allCity = res.data.data.allCity;
        let allStation = res.data.data.allStation;
        let userCity = [];
        let userStation = [];


        let perm_class_city_model_code = userPerm.perm_class_city_model_code; //城市只有一个对象组
        if (undefined != perm_class_city_model_code) {
          perm_class_city_model_code =
            perm_class_city_model_code.perm_class_city_model_code;
        }

        let perm_class_station_model_code =
          userPerm.perm_class_station_model_code; //服务站，是个map


        if (undefined != perm_class_city_model_code) {
          perm_class_city_model_code.forEach(e => {
            userCity.push({ id: e.refId, cityName: e.refName });
          });
        }

        if (undefined != perm_class_station_model_code) {
          for (let e in perm_class_station_model_code) {
            //便利map
            let arr = perm_class_station_model_code[e];
            arr.forEach(f => {
              userStation.push({
                id: f.refId,
                stationName: f.refName,
                cityId: e
              });
            });
          }
        }

        window.localStorage.setItem("allProvince", JSON.stringify(allProvince));
        window.localStorage.setItem("allCity", JSON.stringify(allCity));
        window.localStorage.setItem("allStation", JSON.stringify(allStation));
        window.localStorage.setItem("userCity", JSON.stringify(userCity));
        window.localStorage.setItem("userStation", JSON.stringify(userStation));

         window.localStorage.setItem("userInfo",JSON.stringify(res.data.data.user));
      }
    })
    .catch(err => {
      console.log(err);
    });
};

const initSelfCityStation = function() {
  Service
    .$axiosGetSelfCityStation({
      userId:  JSON.parse(window.localStorage.getItem("userInfo")).id
    })
    .then(res => {
    if (res.data.errno == "0") {
        window.localStorage.setItem("allSelfCity", JSON.stringify(res.data.data.city));
        window.localStorage.setItem("allSelfStation", JSON.stringify(res.data.data.station));
        } else {
          this.$message.warning(res.data.errmsg);
        }

    })
    .catch(err => {
      console.log(err);
    });
};
const initHmCityStation = function() {
  Service
    .$axiosGetHmCityStation({
      userId:  JSON.parse(window.localStorage.getItem("userInfo")).id
    })
    .then(res => {
    if (res.data.errno == "0") {
        window.localStorage.setItem("allHmCity", JSON.stringify(res.data.data.city));
        window.localStorage.setItem("allHmStation", JSON.stringify(res.data.data['station&Shop']));
        } else {
          this.$message.warning(res.data.errmsg);
        }

    })
    .catch(err => {
      console.log(err);
    });
};

const getLocationAllInOne =function (){
  Service.$axiosGetCityStationAllInOne().then(res=>{if (res.data.errno === 0) {
    window.localStorage.setItem("city",JSON.stringify(res.data.data.city));
    window.localStorage.setItem("postStation",JSON.stringify(res.data.data.postStation));
    window.localStorage.setItem("station",JSON.stringify(res.data.data.station));
    window.localStorage.setItem("hmShop",JSON.stringify(res.data.data.hmShop));
    window.localStorage.setItem("hmStation",JSON.stringify(res.data.data.hmStation));
  }else{
    this.$message.warning(res.data.errmsg);
  }}).catch(e=>console.log(e));

};

const getallProvince = function() {
  let allProvince = JSON.parse(window.localStorage.getItem("allProvince"));
  return allProvince;
};

const getallProvinceById=function(provinceId){
  let prv=getallProvince();
  let proviceName="";
  prv.forEach(function(e){
    if(e.id==provinceId){
      proviceName=e.provinceName;
    }
  })
  return proviceName;
}

const getallCity = function() {
  let allCity = JSON.parse(window.localStorage.getItem("allCity"));
  return allCity;
};

const getallCityName=function(cityId){
  let ct=getallCity();
  let cityName="";
  ct.forEach(function(e){
    if(e.id==cityId){
      cityName=e.cityName;
    }
  })
  return cityName;
}

const getallStation = function() {
  let allStation = JSON.parse(window.localStorage.getItem("allStation"));
  return allStation;
};

const getuserCity = function() {
  let userCity = JSON.parse(window.localStorage.getItem("userCity"));

  if (userCity.length == 0) {
    let tempCityId = []; //拿到服务站对应的cityId
    let tempCityIdstr = "";
    let userStation = getuserStation();
    userStation.forEach(e => {
      if (tempCityIdstr.indexOf(e.cityId + ",") == "-1") {
        tempCityId.push(e.cityId);
        tempCityIdstr = e.cityId + ",";
      }
    });

    let allCity = getallCity();
    for (let i = 0; i < tempCityId.length; i++) {
      allCity.forEach(function(c) {
        if (tempCityId[i] == c.id) {
          userCity.push(c);
        }
      });
    }
  }
  // console.log("globaldata中的getuserCity：" + userCity);
  return userCity;
};

const getuserStation = function() {
  let userStation = JSON.parse(window.localStorage.getItem("userStation"));
  return userStation;
};


const getuserStationByCity = function(cityId) {
  //根据城市找服务站,个人拥有的权限
  // console.log(cityId);
  let userStation = getuserStation();
  let station = [];
  userStation.forEach(e => {
    if (e.cityId * 1 == cityId) {
      station.push(e);
    }
  });
  return station;
};

const getuserStationListByCity = function(cityId) {
  //根据城市Id批量获取服务站
  let tempStationList = [];
  for (let i = 0; i < cityId.length; i++) {
    let station = getuserStationByCity(cityId[i]);
    tempStationList = tempStationList.concat(station);
  }
  return tempStationList;
};

const getallStationByCity = function(cityId) {
  //根据城市找服务站,系统所有的服务站
  // console.log(cityId);
  let uallStation = getallStation();
  let station = [];
  uallStation.forEach(e => {
    if (e.cityId * 1 == cityId) {
      station.push(e);
    }
  });
  return station;
};

const getCityByCityId = function(cityId) {
  //根据城市id获取城市对象
  // console.log(stationId);
  let allCity = getallCity();
  let city = {};
  allCity.forEach(e => {
    if (e.id * 1 == cityId) {
      city = e;
    }
  });
  return city;
};

const formatDate = function(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
};
let padLeftZero = function(str) {
  return ("00" + str).substr(str.length);
};

let getDay = function(day) {
  //几天后的日期
  var today = new Date();
  var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  today.setTime(targetday_milliseconds); //注意，这行是关键代码
  var tYear = today.getFullYear();
  var tMonth = today.getMonth();
  var tDate = today.getDate();
  tMonth = doHandleMonth(tMonth + 1);
  tDate = doHandleMonth(tDate);
  return tYear + "-" + tMonth + "-" + tDate;
};

let doHandleMonth = function(month) {
  var m = month;
  if (month.toString().length == 1) {
    m = "0" + month;
  }
  return m;
};


export default {
  userInfo,
  token,

  getallProvince,//所有省份
  getallProvinceById,//根据省份id获取名称
  getallCity, //所有城市
  getallCityName,//根据城市获取城市名称
  getallStation, //所有服务站
  getuserCity, //用户拥有城市
  getuserStation, //用户拥有服务站
  getuserStationByCity, //根据 用户 的城市id找下面的服务站
  getallStationByCity, //根据 系统 所有的城市id找下面的服务站
  getuserStationListByCity, //根据城市Id批量获取服务站
  initUserAuth, //刷新用户权限
  getCityByCityId, //根据城市id获取城市对象

  formatDate,
  getDay,
  initSelfCityStation,
  initHmCityStation,
  getLocationAllInOne

};
</script>
