import { interfaceRequest } from '@/components/Configure/networkRequest/requestSend';
import { getHistoryData } from '@/api/configure/configuration/equipment';

const mappingFunction = async (data, method) => {
  let res2;
  if (data.type === 1) {
    res2 = await interfaceRequest(data);
  }
  if (data.type === 2) {
    res2 = await getHistoryData({
      deviceModeId: data.deviceModeId,
      functionIdentifier: data.functionIdentifier + '1',
      interval: data.interval,
      'sceneId': 144,
      'deviceId': data.deviceId,
      startTime: data.startTime,
      endTime: data.endTime,
      intervalType: 1 || data.intervalType
    });
  }
  let returnRes = {};
  method?.mappingArr?.forEach(v => {
    let res = res2.data;
    for (let i of (v?.region || [])) {
      if (res[i]) {
        res = res[i];
      } else {
        res = null;
        return;
      }
    }
    if (v?.isArray && v?.mapData && Array.isArray(res)) {
      res = res.map(e => e[v.mapData]);
    }
    returnRes = {
      ...returnRes, [v?.name]: res
    };
  });
  return returnRes;
};


const detectingNullValues = (obj, keys) => {
  let data = obj;
  if (keys.length > 1) {
    if (!data[keys[0]]) {
      if (typeof keys[1] === 'string') {
        data[keys[0]] = {};
        detectingNullValues(data[keys[0]], keys.slice(1));
      }
      if (typeof keys[1] === 'number') {
        data[keys[0]] = [];
        detectingNullValues(data[keys[0]], keys.slice(1));
      }
    } else {
      detectingNullValues(data[keys[0]], keys.slice(1));
    }
  }
  return data;
};

const GetFinalData = async (requests) => {
  let requestArr = [];
  requests.forEach(e => {
    if (e.type === 'network') {
      requestArr.push(mappingFunction(e, e.mappingForm));
    }
  });
  return Promise.all(requestArr).then(e => {
    let data = {};
    e.forEach(v => {
      data = {
        ...data, ...v
      };
    });
    return data;
  });
};

const limitSolve = (type, e) => {
  switch (type) {
    case 0:
      if (e.data2) {
        return e.data3;
      } else if (e.data1 >= 100) {
        return 100;
      } else if (e.data1 <= 0) {
        return 0;
      } else {
        return e.data1;
      }
    case 1:
      if (e.data1 >= 100) {
        return 100;
      } else if (e.data1 <= 0) {
        return 0;
      } else {
        return e.data1;
      }
  }
};
const parseData = (str, data) => {
  let data1 = str.substring(2, str.length - 2);
  let keys = data1.split('.');
  let dataRow = data;
  keys.forEach(e => {
    if (dataRow && dataRow !== void 0) {
      dataRow = dataRow[e];
    }
  });
  return dataRow;
};
const clearObjNull = (e, data1) => {
  let obj = {};
  for (const key in e) {
    if (e.hasOwnProperty(key)) {
      if (e[key] === null || (e[key] === void 0) || e[key] === '') {
      } else if (e[key]?.constructor === Object) {
        let data = clearObjNull(e[key], data1);
        if (data) {
          obj[key] = data;
        }
      } else if (Array.isArray(e[key])) {
        let data = clearArrNull(e[key], data1);
        if (data) {
          obj[key] = data;
        }
      } else {
        let v = e[key];
        if (typeof v === 'string' && v.startsWith('{{') && v.endsWith('}}')) {
          obj[key] = parseData(v, data1);
        } else {
          obj[key] = v;
        }
      }
    }
  }
  return Object.keys(obj).length === 0 ? null : obj;
};
const clearArrNull = (e, data1) => {
  if (!Array.isArray(e)) {
    return null;
  }
  let arr = [];
  e.forEach(v => {
    if (v === null || (v === void 0) || v === '') {
    } else if (v?.constructor === Object) {
      let data = clearObjNull(v, data1);
      if (data) {
        arr.push(data);
      }
    } else if (Array.isArray(v)) {
      let data = clearArrNull(v, data1);
      if (data) {
        arr.push(data);
      }
    } else {
      if (typeof v === 'string' && v.startsWith('{{') && v.endsWith('}}')) {
        arr.push(parseData(v, data1));
      } else {
        arr.push(v);
      }
    }
  });
  return arr.length === 0 ? null : arr;
};
const clearNull = (e, data) => {
  if (typeof e === 'string' && e.startsWith('{{') && e.endsWith('}}')) {
    return parseData(e, data);
  }
  if (e?.constructor === Object) {
    return clearObjNull(e, data);
  } else if (Array.isArray(e)) {
    return clearArrNull(e, data);
  } else {
    return e;
  }
};

const parseTime = (time, pattern) => {
  if (!time) {
    return null;
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time);
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
};

const getFinalData = async (e) => {
  let requestArr = [];
  e.forEach((i, k) => {
    requestArr.push(mappingFunction(i, i.mappingForm));
  });
  return Promise.all(requestArr).then(i => {
    let data = {};
    i.forEach(v => {
      data = {
        ...data, ...v
      };
    });
    return data;
  });
};
const testColor = (color) => {
  const regexHex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
  const regexRgb = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/;
  const regexRgba = /^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*([0-9]*\.?[0-9]+)\)$/;

  return regexHex.test(color) || regexRgb.test(color) || regexRgba.test(color);
};

// 判断是否是json
const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  }
  return false;
};
export {
  limitSolve, parseData, clearObjNull, clearArrNull, clearNull, detectingNullValues, getFinalData, parseTime, testColor,isJSON
};
