import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {
  api
} from "../api/all.js"
import {
  httpGet,
  httpPost,
  httpPostno,
  httpGetno
} from "../api"
import moment from "moment"
  import {
    ztreeToElementTree,
    recursion,
    uniqueArray,compare
  } from "../utils/index";
const store = new Vuex.Store({
  state: {
    treeList:[],
    tenantId: '1200',
    selectoption: [],
    tagsList: [],
    cardList: [],
    collapse: false,
    lange: false,
    token: {
      refresh_token: "",
      access_token: ""
    },
    ms_username: '',
    collectUS: {
      houseSensor400: 0,
      lock200: 0,
      lock300: 0,
      site200: 0,
      site300: 0,
      site400: 0,
      userCount: 0
    },
    seriesData: {
      abnormalTotal: 0,
      batteryLevel1: 0,
      batteryLevel2: 0,
      batteryLevel3: 0,
      batteryLevel4: 0,
      batteryLevel5: 0,
      closeTotal: 0,
      offlineTotal: 0,
      onlineTotal: 0,
      openTotal: 0,
      projects: 0,
      total: 0
    },
    cdata: [0, 0, 0, 0, 0],
    tableData: {},
    currentPage: 1,
    currentPage1: 1,
    deviceList: [],
    roomAbout: [],
    deviceAbout: [],
    customerCode: "d39eaa7fc1f34190869608259133d2fb",
		conditionRoomAndPersonnel:[],
    analysis: {
      abnormalTotal: 0,
      batteryLevel1: 0,
      batteryLevel2: 0,
      batteryLevel3: 0,
      batteryLevel4: 0,
      batteryLevel5: 0,
      offlineTotal: 0,
      onlineTotal: 0,
      operationTotal: 0,
      projects: 0,
      total: 0,
    },
    Statistics: {
      projectSum: 0,
      deviceSum: 0,
      bindingSum: 0,
      islineSum: 0,
      unlineSum: 0,
      lowElectricity: 0,
      openlook: 0,
      closelook: 0,
      openDoorlog: 0,
      closeDoorlog: 0,
      unlineList: [],
      fcDoorlog: 0,
      Processed: 0,
      allertLog: {
        openDoorlog: [0, 0, 0, 0, 0, 0, 0],
        closeDoorlog: [0, 0, 0, 0, 0, 0, 0],
        fcDoorlog: [0, 0, 0, 0, 0, 0, 0],
      },
      deviceBattery: [0, 0, 0],
      userinfo: {
        type: 1
      },
      sumTotal:0,
    },
		zNodes:[]
  },
  mutations: {
    getSumTotal(state){
      httpGet('',api.getTotalRevenue).then(res=>{
        if(res.success){
          if(res.data){
            state.sumTotal = res.data/100
          }
        }
      })
    },
		getConditionRoomAndPersonnel(state){
			var data = {};
			httpPost(data, api.onlyTenant).then((res) => {
				if(res.success){
					state.conditionRoomAndPersonnel = res.data.list
				}
			})
		},
    getTree(state) {
        var data = {};
        httpGet(data, api.getTree).then((res) => {
			if(res.success){
				var arrdata = uniqueArray(res.data, "id")
        state.treeList=arrdata
				state.zNodes = ztreeToElementTree(arrdata, {});
			}
		})
	},
    getselectoption(state, v) {
      // var userinfo = JSON.parse(localStorage.getItem("info"));
      // var tenantId = userinfo.tenantId.split(',')
      // var arr = []
      // httpGet('', api.getConfig).then(res => {
      //   if (res.success) {
      //     if(userinfo.type===0){
      //       arr=res.data.list
      //     }else{
      //       tenantId.map(lt => {
      //         var obj = res.data.list.filter(item => {return item.value==lt})[0]
      //         if(obj){
      //           arr.push(obj)
      //         }
      //       })
      //     }
      //     state.selectoption = arr
      //     localStorage.setItem('selectoption',JSON.stringify(arr))
      //   } else {
      //     this.$message.error("获取失败")
      //   }
      // })
    },
    getuserInfo(state) {
      httpGet('', api.userInfo).then(res3 => {
        if (res3.success) {
          state.userinfo = res.data
          localStorage.setItem('info',JSON.stringify(res.data))
        }
      })
    },
    settenantid(state) {
      // var tenantId = JSON.parse(localStorage.getItem("tenantId"));
      // if (tenantId) {
      //   state.tenantId = tenantId
      // } else {
      //   var userinfo = JSON.parse(localStorage.getItem("info"));
      //   tenantId = userinfo.tenantId.split(',')
      //   state.tenantId = tenantId[0]
      //   localStorage.setItem('tenantId', tenantId[0])
      // }
    },
    defaultsettenantid(state) {
      // var userinfo = JSON.parse(localStorage.getItem("info"));
      // var tenantId = userinfo.tenantId.split(',')
      // state.tenantId = tenantId[0]
      // localStorage.setItem('tenantId', tenantId[0])
    },
    updateTenantId(state, p) {
      // state.tenantId = p
      // localStorage.setItem('tenantId', p)
    },
    updatedata(state, p) {
      state.Statistics.openlook = p
    },
    getCardname(state) {
      var data = {
        pageNum: 0,
        pageSize: 0,
        orderBy: "create_at desc",
		q:JSON.stringify({})
      };
      httpPost(data, api.getlistNum).then((res) => {
        if (res.success) {
          state.cardList = res.data.list
        } else {
          state.cardList = []
        }
      })
    },
    setanalysis(state, data) {
      state.analysis = data
    },
    // 查询关于房间数据
    getAboutRoom(state, count) {
      state.roomAbout = count
    },
    // 查询关于房间数据
    getAboutDevice(state, count) {
      state.deviceAbout = count
    },
    increment(state, count) {
      state.currentPage = count
    },
    increment1(state, count) {
      state.currentPage1 = count
    },
    deviceFun(state, list) {
      state.deviceList = list
    },
    getcollectUS(state) {

    },
    setUser(state, v) {
      state.seriesData = v;
    },
   async setUser1(state) {
      var ids = JSON.parse(localStorage.getItem('info')) //require('../../static/global.json');
      let tenantIds=ids.tenantId.replace('100,','')
      var lookStatistic=0
    httpGetno("", `/v1/statistics/all/analysis/${tenantIds}/1`).then((res) => {
            for(let key in res){
              lookStatistic+=res[key].total
            }
            localStorage.setItem("lookStatistic", lookStatistic)
        })
      httpGetno("", `/v1/statistics/all/analysis/${tenantIds}/-1`).then((res) => {
        var datate = [0, 0, 0, 0, 0, 0, 0]
        var today = moment().format("YYYY-MM-DD")
        datate[6] = today
        datate[5] = moment().subtract('days', 1).format("YYYY/MM/DD")
        datate[4] = moment().subtract('days', 2).format("YYYY/MM/DD")
        datate[3] = moment().subtract('days', 3).format("YYYY/MM/DD")
        datate[2] = moment().subtract('days', 4).format("YYYY/MM/DD")
        datate[1] = moment().subtract('days', 5).format("YYYY/MM/DD")
        datate[0] = moment().subtract('days', 6).format("YYYY/MM/DD")
        var sum = [{
          order: datate[0],
          count: 0
        }, {
          order: datate[1],
          count: 0
        }, {
          order: datate[2],
          count: 0
        }, {
          order: datate[3],
          count: 0
        }, {
          order: datate[4],
          count: 0
        }, {
          order: datate[5],
          count: 0
        }, {
          order: datate[6],
          count: 0
        }]
        var array = []
        for (var i in res) {
          array.push(res[i])
        }
        var seriesData = {
          abnormalTotal: 0,
          batteryLevel1: 0,
          batteryLevel2: 0,
          batteryLevel3: 0,
          batteryLevel4: 0,
          batteryLevel5: 0,
          closeTotal: 0,
          offlineTotal: 0,
          onlineTotal: 0,
          openTotal: 0,
          projects: 0,
          total: 0,
          isAppBind:0,
        }
        array.map((li, index) => {
          if (index < array.length) {
            for (var key in seriesData) {
              seriesData[key] += li[key]
            }
          }
        })
        array.map((li, index) => {
          li.createAtS.map(lt => {
            var order = moment(lt).format("YYYY/MM/DD")
            if (order == datate[0]) {
              sum[0].count += 1
            } else if (order == datate[1]) {
              sum[1].count += 1
            } else if (order == datate[2]) {
              sum[2].count += 1
            } else if (order == datate[3]) {
              sum[3].count += 1
            } else if (order == datate[4]) {
              sum[4].count += 1
            } else if (order == datate[5]) {
              sum[5].count += 1
            } else if (order == datate[6]) {
              sum[6].count += 1
            }
          })
        })
        var cdata = state.cdata
        cdata[0] = (parseInt(seriesData.batteryLevel1) / parseInt(seriesData.total) * 100).toFixed(2);
        cdata[1] = (parseInt(seriesData.batteryLevel2) / parseInt(seriesData.total) * 100).toFixed(2);
        cdata[2] = (parseInt(seriesData.batteryLevel3) / parseInt(seriesData.total) * 100).toFixed(2);
        cdata[3] = (parseInt(seriesData.batteryLevel4) / parseInt(seriesData.total) * 100).toFixed(2);
        cdata[4] = (parseInt(seriesData.batteryLevel5) / parseInt(seriesData.total) * 100).toFixed(2);
        // seriesData['lookStatistic']=lookStatistic
        state.cdata = cdata
        state.seriesData = seriesData
        var collectUS = {
          houseSensor400: 0,
          lock200: 0,
          lock300: 0,
          site200: 0,
          site300: 0,
          site400: 0,
          userCount: 0
        }
        httpGetno("", `/v1/statistics/all/collectUSA/${tenantIds}`).then((res) => {
          state.collectUS = res
          collectUS = res
          var tenantIdsTwo=tenantIds.replace('400,','')
          httpGetno("", `/v1/statistics/collect/openLock/${tenantIdsTwo}`).then((res1) => {
            var ary = []
            for(let o in res1){
              var m=o.indexOf('week')
              if(m!=-1){
                ary = ary.concat(res1[o])
              }
            }
            var objArr = [];
            ary.forEach(function(v, i){
              const result = objArr.findIndex((ev) => {
                  return ev.order === v.order;
              })
              if(result!=-1){
                objArr[result].count+=v.count
              }else{
                objArr.push(v)
              }
            })
            var sortArry=objArr.sort(compare('order','positive'))
            setTimeout(()=>{
              var statisticsDate = {
                cdata: cdata,
                seriesData: seriesData,
                collectUS: collectUS,
                collectOpenLock: res1,
                weekopenlock: sortArry,
                addDeviceWeek: sum,
              }
              state.statisticsDate=statisticsDate
              localStorage.removeItem("statisticsDate")
              localStorage.setItem("statisticsDate", JSON.stringify(statisticsDate))
            },500)
          })
        });
      });
    },
    selectlanguage(state) {
      if (state.lange) {
        state.lange = false
        sessionStorage.setItem("lange", false)
      } else {
        state.lange = true
        sessionStorage.setItem("lange", true)

      }
    },
    delTagsItem(state, data) {
      state
        .tagsList
        .splice(data.index, 1);
    },
    setTagsItem(state, data) {
      state
        .tagsList
        .push(data)
    },
    clearTags(state) {
      state.tagsList = []
    },
    closeTagsOther(state, data) {
      state.tagsList = data;
    },
    closeCurrentTag(state, data) {
      for (let i = 0, len = state.tagsList.length; i < len; i++) {
        const item = state.tagsList[i];
        if (item.path === data.$route.fullPath) {
          if (i < len - 1) {
            data
              .$router
              .push(state.tagsList[i + 1].path);
          } else if (i > 0) {
            data
              .$router
              .push(state.tagsList[i - 1].path);
          } else {
            data
              .$router
              .push("/");
          }
          state
            .tagsList
            .splice(i, 1);
          break;
        }
      }
    },
    // 侧边栏折叠
    hadndleCollapse(state, data) {
      state.collapse = data;
    },

  },
  actions: {},
  modules: {}
})
export default store
