/**
 * @author chuzhixin 1204505056@qq.com
 * @description 导入所有 vuex 模块，自动加入namespaced:true，用于解决vuex命名冲突，请勿修改。
 */
import { createStore } from 'vuex'
import * as api from '@/api/publicList'
import ElMessage from 'element-plus'

const files = require.context('./modules', false, /\.js$/)
const modules = {}
files.keys().forEach((key) => {
  modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})

Object.keys(modules).forEach((key) => {
  modules[key]['namespaced'] = true
})
export default createStore({
  modules,
  state: {
    query: null,
    siteId: 1, //公共api请求参数->siteId
    siteList: [],//公共api站点下拉列表存储->siteId
    deviceList: [],//公共站点下拉列表
    monthList: [],//公共每月最后一天信息存储
    dateList: [],//公共每月当天信息存储

    timeProcessing: '',

    Time_Data: [], //公共api请求参数->Time_Data
    timearr: [], //公共处理开始时间和结束时间中的时间段天数 值存储
    Time_All: [], //公共时间 返回数组 -> 年月日时分秒 时间戳


    queryType: '', //设备监控--->数据报表api请求参数->queryType
    run_off_Status: null, //设备监控--->运行状态统计->echarts->OFF次数分布和运行状态曲线图表 api信息存储
    se_defaultTime: [], //设备监控--->历史趋势时间选择器v-model
    th_defaultTime: [], //设备监控--->数据报表时间选择器v-model
    fh_defaultTime: [], //设备监控--->运行状态统计时间选择器v-model


    // tableHeight:0,//公共table监听高度变化
    // echartHeight:0,//公共ehcarts监听高度变化
  },
  mutations: {
    /**
     * @公共站点下拉列表
     * @param {*} state 
     */
    publicSiteList(state) {
      api
        .SiteList({})
        .then((requset) => {
          if (requset.status === 'SUCCESS') {
            state.siteList = requset.data
          } else {
            ElMessage.error(requset.msg)
          }
        })
    },

    /**
     * @公共左侧树状设备
     * @param {*} state 
     */
    publicDeviceList(state) {
      if (state.siteId != "" && state.siteId != null) {
        api
          .dataManagementDeviceList({ siteId: state.siteId })
          .then((requset) => {
            if (requset.status === 'SUCCESS') {
              state.deviceList = []
              requset.data.map((val) => {
                if (val.children.length > 0) {
                  state.deviceList.push({
                    deviceCode: val.deviceCode,
                    deviceName: val.deviceName,
                    id: val.id,
                    children:
                      val.children.length > 0
                        ? val.children.map((val) => {
                          return {
                            deviceCode: val.variableCoding,
                            deviceName: val.variableName,
                            id: val.id,
                          }
                        })
                        : val.children,
                  })
                }
              })
            } else {
              ElMessage.error(requset.msg)
            }
          })
      } else {
        state.deviceList = []
      }

    },

    /**
     * @公共api请求参数siteId
     * @param {*}} state 
     * @param {*} val 
     */
    increment(state, val) {
      state.siteId = val
    },
    /**
     * @公共处理时区方法
     */
    TimeAll_function(state, time) {
      state.Time_Data = []
      for (let i in time) {
        var Y = time[i].getFullYear() < 10 ? '0' + time[i].getFullYear() : time[i].getFullYear()
        var M = (time[i].getMonth() + 1) < 10 ? '0' + (time[i].getMonth() + 1) : (time[i].getMonth() + 1)
        var D = time[i].getDate() < 10 ? '0' + time[i].getDate() : time[i].getDate()
        var HH = time[i].getHours() < 10 ? '0' + time[i].getHours() : time[i].getHours()
        var MM = time[i].getMinutes() < 10 ? '0' + time[i].getMinutes() : time[i].getMinutes()
        var SS = time[i].getSeconds() < 10 ? '0' + time[i].getSeconds() : time[i].getSeconds()
        // console.log(Y + '-' + M + '-' + D + ' ' + HH + ':' + MM + ':' + SS)
        state.Time_Data.push(Y + '-' + M + '-' + D + ' ' + HH + ':' + MM + ':' + SS)
      }
    },
    /**
     * @公共处理开始时间和结束时间中的时间段天数
     * @param {*} state 
     * @param {*} begin 开始时间和结束时间
     */
    getAll(state, begin) {
      let arr1 = begin[0].split("-");
      let arr2 = begin[1].split("-");
      let arr1_ = new Date();
      let arrTime = [];
      arr1_.setUTCFullYear(arr1[0], arr1[1] - 1, arr1[2]);
      let arr2_ = new Date();
      arr2_.setUTCFullYear(arr2[0], arr2[1] - 1, arr2[2]);
      let unixDb = arr1_.getTime();
      let unixDe = arr2_.getTime();
      for (let k = unixDb; k <= unixDe;) {
        arrTime.push(datetimeparse(k, "YY-MM-DD"));
        k = k + 24 * 60 * 60 * 1000;
      }
      state.timearr = arrTime
      // return arrTime;
      // 时间格式处理
      function datetimeparse(timestamp, format, prefix) {
        if (typeof timestamp == "string") {
          timestamp = Number(timestamp);
        }
        //转换时区
        let currentZoneTime = new Date(timestamp);
        let currentTimestamp = currentZoneTime.getTime();
        let offsetZone = currentZoneTime.getTimezoneOffset() / 60; //如果offsetZone>0是西区，西区晚
        let offset = null;
        //客户端时间与服务器时间保持一致，固定北京时间东八区。
        offset = offsetZone + 8;
        currentTimestamp = currentTimestamp + offset * 3600 * 1000;

        let newtimestamp = null;
        if (currentTimestamp) {
          if (currentTimestamp.toString().length === 13) {
            newtimestamp = currentTimestamp.toString();
          } else if (currentTimestamp.toString().length === 10) {
            newtimestamp = currentTimestamp + "000";
          } else {
            newtimestamp = null;
          }
        } else {
          newtimestamp = null;
        }
        let dateobj = newtimestamp ?
          new Date(parseInt(newtimestamp)) :
          new Date();
        let YYYY = dateobj.getFullYear();
        let MM =
          dateobj.getMonth() > 8 ?
            dateobj.getMonth() + 1 :
            "0" + (dateobj.getMonth() + 1);
        let DD =
          dateobj.getDate() > 9 ? dateobj.getDate() : "0" + dateobj.getDate();
        let HH =
          dateobj.getHours() > 9 ? dateobj.getHours() : "0" + dateobj.getHours();
        let mm =
          dateobj.getMinutes() > 9 ?
            dateobj.getMinutes() :
            "0" + dateobj.getMinutes();
        let ss =
          dateobj.getSeconds() > 9 ?
            dateobj.getSeconds() :
            "0" + dateobj.getSeconds();
        let output = "";
        let separator = "/";
        if (format) {
          separator = format.match(/-/) ? "-" : "/";
          output += format.match(/yy/i) ? YYYY : "";
          output += format.match(/MM/) ?
            (output.length ? separator : "") + MM :
            "";
          output += format.match(/dd/i) ?
            (output.length ? separator : "") + DD :
            "";
          output += format.match(/hh/i) ? (output.length ? " " : "") + HH : "";
          output += format.match(/mm/) ? (output.length ? ":" : "") + mm : "";
          output += format.match(/ss/i) ? (output.length ? ":" : "") + ss : "";
        } else {
          output += YYYY + separator + MM + separator + DD;
        }
        output = prefix ? prefix + output : output;
        return newtimestamp ? output : "";
      }
    },
    /**
     * @公共echarts图表下载
     */
    getConnectedDataURL(state, refs) {
      state || refs
      var url = refs[0].getConnectedDataURL({
        pixelRatio: 15,
        backgroundColor: "black",
        excludeComponents: ["toolbox"],
        type: "png",
      });
      var $a = document.createElement("a");
      var type = "png";
      //图片名称
      $a.download = refs[1] + "." + type;
      $a.target = "_blank";
      $a.href = url;
      if (typeof MouseEvent === "function") {
        var evt = new MouseEvent("click", {
          view: window,
          bubbles: true,
          cancelable: false,
        });
        $a.dispatchEvent(evt);
      }
    },
    /**
     * @公共时间 返回数组 -> 年月日时分秒 时间戳
     */
    getTimeAll(state) {
      const time = new Date();
      const Y = time.getFullYear(); //年
      const M = time.getMonth(); //月
      const D = time.getDate(); //日
      const HH = time.getHours(); //时，
      const MM = time.getMinutes(); //分
      const SS = time.getSeconds(); //秒
      const timestamp = new Date().getTime(); //时间戳
      state.Time_All = [Y, M, D, HH, MM, SS, timestamp]
      state.se_defaultTime = [new Date(Y, M, D, 0, 0, 0), new Date()] //设备监控--->历史趋势时间选择器v-model  //home设备总数
      state.th_defaultTime = [new Date(Y, M, D, 0, 0, 0), new Date()] //设备监控--->数据报表时间选择器v-model  //home运维管理
      state.fh_defaultTime = [new Date(Y, M, 1, 0, 0, 0), new Date()] //设备监控--->运行状态统计时间选择器v-model  //概览 -> 告警统计折线图
    },
    /**
     * @处理公共时间搓 返回数组 -> 年月日时分秒 时间戳
     */
    getTimestampAll(state, timestamp) {
      function add0(m) { return m < 10 ? '0' + m : m }
      const time = new Date(timestamp);
      const Y = time.getFullYear(); //年
      const M = time.getMonth(); //月
      const D = time.getDate(); //日
      const HH = time.getHours(); //时，
      const MM = time.getMinutes(); //分
      const SS = time.getSeconds(); //秒
      state.timeProcessing = Y + '-' + add0(M + 1) + '-' + add0(D) + ' ' + add0(HH) + ':' + add0(MM) + ':' + add0(SS);
    },
    /**
     * @公共获取某月的第一天和最后一天
     */
    getCurrentMonthLast(state, timeAll) {
      var date1 = timeAll;
      date1.setDate(1);
      var month1 = parseInt(date1.getMonth() + 1);
      var day1 = date1.getDate();
      if (month1 < 10) {
        month1 = '0' + month1
      }
      if (day1 < 10) {
        day1 = '0' + day1
      }

      var date = timeAll;
      var currentMonth = date.getMonth();
      var nextMonth = ++currentMonth;
      var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      var oneDay = 1000 * 60 * 60 * 24;
      var lastTime = new Date(nextMonthFirstDay - oneDay);
      var month = parseInt(lastTime.getMonth() + 1);
      var day = lastTime.getDate();
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      state.monthList = [date1.getFullYear() + '-' + month1 + '-' + day1, date.getFullYear() + '-' + month + '-' + day]

    },
    /**
     * @获取当天日期
     */
    getNowFormatDate(state, timeAll) {
      var date = timeAll;
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      state.dateList = currentdate
    }
  }
})
