
import store from '@/store'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal (path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUsername (str) {
  const valid_map = ['admin', 'editor']
  return valid_map.indexOf(str.trim()) >= 0
}
// 账号组树构造
// export function translateDataToTreeAllTree (data, parentKey, parentIDKey) {
//   const parent = data.filter(value => Number(value[parentKey]) <= 0) // 父数据
//   const children = data.filter(value => Number(value[parentKey]) > 0) // 子数据
//   // 
//   // 
//   const translator = (parent, children) => {
//     parent.forEach(parent => {
//       parent.children = []
//       children.forEach((current, index) => {
//         if (current[parentKey] === parent[parentIDKey]) {
//           const temp = JSON.parse(JSON.stringify(children))
//           temp.splice(index, 1)
//           translator([current], temp)
//           typeof parent.children !== 'undefined' ? parent.children.push(current) : (parent.children = [current])
//         }
//       })
//       // for (let i = 0; i < children.length;) {
//       //   if (children[i][parentKey] === parent[parentIDKey]) {
//       //     const temp = children.splice(i, 1)
//       //     typeof parent.children !== 'undefined' ? parent.children.push(...temp) : (parent.children = temp)
//       //     translator(temp, children)
//       //   } else {
//       //     i++
//       //   }
//       // }
//     })
//   }
//   translator(parent, children)
//   return parent
// }

export function translateDataToTreeAllTree (data, parentKey, parentIDKey) {
  let parent = data.filter((value) => Number(value[parentKey]) <= 0);// 父数据
  let children = data.filter((value) => Number(value[parentKey]) > 0);// 子数据
  //
  //
  let translator = (parent, children) => {
    parent.forEach((parent) => {
      parent.children = [];
      children.forEach((current, index) => {
        if (current[parentKey] === parent[parentIDKey] && current['type'] !== parent['type']) {
          const temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1);
          translator([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };
  translator(parent, children);
  return parent;
}

export function translateDataToTreeAllTreeMsg (data, parentKey, parentIDKey) {
  let parent = data.filter((value) => Number(value[parentKey]) <= 0);// 父数据
  let children = data.filter((value) => Number(value[parentKey]) > 0);// 子数据
  //
  //
  let translator = (parent, children) => {
    parent.forEach((parent) => {
      parent.children = [];
      children.forEach((current, index) => {
        if (current[parentKey] === parent[parentIDKey]) {
          const temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1);
          translator([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };
  translator(parent, children);
  return parent;
}

export function translateDataToTreeAll (arr, parentKey, key) {
  const map = {}
  const result = []
  arr.forEach(element => {
    const id = element[key]
    const pid = element[parentKey]
    if (map[id]) {
      map[id] = {
        ...element,
        children: map[id].children
      }
    } else {
      map[id] = {
        ...element,
        children: []
      }
    }
    const item = map[id]
    if (pid <= 0) {
      result.push(item)
    } else {
      if (map[pid]) {
        map[pid].children.push(item)
      } else {
        map[pid] = {
          children: [item]
        }
      }
    }
  })
  return result
}

// 模糊查询
export function findarrays (ar, feature, v) {
  var arr = []
  ar.forEach(res => {

  })
  for (var i = 0; i < ar.length; i++) {
    var atxt = ar[i][feature]
    var btxt = v
    var type = 0
    if (atxt.match(btxt) == btxt) {
      type = 1
    }
    if (type == 1) {
      arr.push(ar[i])
    }
  }
  // var arr = [];
  // for (var i = 0; i < ar.length; i++) {
  //   var atxt = ar[i][feature];
  //   var btxt = v;
  //   //		将字符串按某个字符切割成若干个字符串，并以数组形式返回
  //   var atxtarr = atxt;
  //   var btxtarr = btxt;
  //   var type = 0;
  //   // for (var k = 0; k < atxtarr.length; k++) {
  //   //   if (btxtarr[0].length >= atxtarr[k].length) {
  //   //     if (atxtarr[k] == btxtarr[0]) {
  //   //       type = 1;
  //   //     }
  //   //   }
  //   // }
  //   if (atxtarr == btxtarr) {
  //     type = 1;
  //   } else if (atxtarr.length > btxtarr.length) {
  //     for (var k = 0; k < atxtarr.length; k++) {
  //       if (btxtarr[0].length >= atxtarr[k].length) {
  //         if (atxtarr[k] == btxtarr) {
  //           type = 1;
  //         }
  //       }
  //     }
  //   }
  //   if (type == 1) {
  //     arr.push(ar[i]);
  //   }
  // }
  return arr
}

// 表单输入长度验证
function getRealLength (string) {
  let realLength = 0,
    len = string.length,
    charCode = -1
  for (let i = 0; i < len; i++) {
    charCode = string.charCodeAt(i)
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1
    } else {
      realLength += 2
    }
  }
  return realLength
}

export function lengthValidator (rule, value, callback) {
  value = value ?? ''
  const realLength = getRealLength(value)
  if (realLength === 0) {
    callback()
  } else if (rule.min && realLength < rule.min) {
    rule.message += `  ${realLength}/${rule.min}`
    callback(new Error('长度小于最小值'))
  } else if (rule.max && realLength > rule.max) {
    rule.message += `  ${realLength}/${rule.max}`
    callback(new Error('长度超出最大值'))
  } else {
    callback()
  }
}
/**
 * 是否合法IP地址
 * @param value
 * @param callback
 */
export function validateIP (rule, value, callback) {
  if (value === '' || typeof value === 'undefined' || value == null) {
    callback(new Error('请输入正确的IP地址'))
  } else {
    const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    if ((!reg.test(value)) && value !== '') {
      callback(new Error('请输入正确的IP地址'))
    } else {
      callback()
    }
  }
}

// 表单验证输入内容验证
export const regular = {
  integer: /^[0-9]*$/,
  positiveInteger: /^[1-9][0-9]*$/,
  name: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
  nameMessage: '只能包含中文、英文、数字和下划线且不能以下划线开头',
  url: /([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|[wW]{3}.|[wW][aA][pP].|[fF][tT][pP].|[fF][iI][lL][eE].)[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]/,
  urlMessage: '请输入正确地址'
}


export function isValue (arg) {
  if (Array.isArray(arg)) {
    return arg.length
  } else {
    if (typeof arg === 'object') {
      return Object.keys(arg).length
    } else {
      return false
    }
  }
}

function setItem (arr, parentKey, key) {
  arr.forEach((item) => {
    const datas = []
    if (item.children) {
      item.children.some((p) => {
        if (item[key] == p[parentKey]) {
          datas.push(p)
          item.children = datas
        }
      })
      setItem(item.children, parentKey, key)
    }
  })
  return arr
}

export function listToTree (data, parentKey, key) {
  const obj = {};
  data.forEach((item) => {
    obj[item[key]] = item;
  });
  const parentList = [];
  data.forEach((item) => {
    const parent = obj[item[parentKey]];
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(item);
    } else {
      parentList.push(item);
    }
  });
  return parentList;
}


export function setTree (arr, parentKey, key) {
  const datas = []
  const all = []
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i][key] == arr[j][parentKey]) {
        datas.push(_.cloneDeep(arr[j]))
        arr[i].children = _.cloneDeep(datas)
        all.push(_.cloneDeep(arr[j]))
      }
    }
  }
  const res = [...arr, ...all].filter(
    (item) =>
      !(
        arr.some((p) => item[key] == p[key]) &&
        all.some((c) => item[key] == c[key])
      )
  )
  const result = setItem(res, parentKey, key)
  return result
}

export function getAuthData (key) {
  const datas = store.state.auth.authArrs ?? []
  if (datas.length) {
    const type = datas.filter(item => item['auth_id'] == key)[0]['auth_type']
    const arrs = datas.filter(item => item['up_auth_id'] == key)
    return {
      type,
      arrs
    }
  } else {
    return {
      type: null,
      datas
    }
  }
}

export function formatOrder (arr, key = 'orderNumber') {
  const newDatas = _.cloneDeep(arr)
  const [n1, n2] = [[], []]
  const msgDatas = []
  newDatas.map((item, index) => {
    item.index = index
    msgDatas.push(item)
  })
  for (const p of msgDatas) {
    if (p[key] || p[key] == 0) {
      n1.push(p)
    } else {
      n2.push(p)
    }
  }
  const newN1 = n1.sort((a, b) => a[key] - b[key])
  const newN2 = n2.sort((a, b) => a.index - b.index)
  return [...newN1, ...newN2]
}

export const Format = (fmt, date) => {
  let o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};
