/**
 * 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 translateDataToTreeAll(data, parentKey, parentIDKey) {
//   const parent = data.filter(value => Number(value[parentKey]) <= 0) // 父数据
//   const children = data.filter(value => Number(value[parentKey]) > 0) // 子数据
//   // console.log('--parent', parent)
//   // console.log('--children', children)
//   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 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 => {
    console.log(res.feature)
  })
  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 randomNum(start, end) {
  return Math.floor(Math.random() * (Number(end) - Number(start)) + start)
}

// 字母随机
function randomAlp(arr, count) {
  let shuffled = arr.slice(0),
    i = arr.length,
    min = i - count,
    temp,
    index
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random())
    temp = shuffled[index]
    shuffled[index] = shuffled[i]
    shuffled[i] = temp
  }
  return shuffled.slice(min)
}

/**
 * @param {minLen} 密码最小长度
 * @param {maxLen} 密码最大长度
 * @param {struc} 密码规则
 * @returns {Object}
 * 4位密码规则 1111 = 大写 小写 特殊字符 数字 都开启
 */
export function pwdProduce(minLen, maxLen, struc) {
  // 密码规则转化
  const pwdStruc = typeof struc === 'string' ? struc.split('') : `${struc}`.split('')
  // 字母
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'
  // 特殊字符
  const special = ['~', '!', '@', '#', '$', '%', '^', '&', '*', '_', '+', '.']
  // 数字
  const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  // 密码随机长度
  const pwdLen = randomNum(minLen, maxLen)
  const datas = []

  if (pwdStruc.length) {
    let typeLong = Number(pwdStruc[0]) + Number(pwdStruc[1]) + Number(pwdStruc[2]) + Number(pwdStruc[3])
    let passLong = Math.ceil(pwdLen / typeLong)
    let dis = ''
    if (pwdStruc[0] == 1) {
      let arr = alphabet.toLocaleUpperCase().split('')
      let v = randomAlp(arr, passLong)
      for (let i = 0; i < passLong; i++) {
        dis += v[i]
      }
    }
    if (pwdStruc[1] == 1) {
      let arr = alphabet.split('')
      let v = randomAlp(arr, passLong)
      for (let i = 0; i < passLong; i++) {
        dis += v[i]
      }
    }
    if (pwdStruc[2] == 1) {
      let arr = special
      let v = randomAlp(arr, passLong)
      for (let i = 0; i < passLong; i++) {
        dis += v[i]
      }
    }
    if (pwdStruc[3] == 1) {
      let arr = numbers
      let v = randomAlp(arr, passLong)
      for (let i = 0; i < passLong; i++) {
        dis += v[i]
      }
    }
    return dis
    // 缓存当前的密码规则
    // pwdStruc.forEach((item, index) => {
    //   if (item == 1) {
    //     datas.push(index)
    //   }
    // })
    // // 只有一种规则时
    // if (datas.length === 1) {
    //   const num = datas[0]
    //   const dis = randomAlp(alphabet.split('')).splice(0, pwdLen).join('')
    //   switch (num) {
    //     case 0:
    //       return dis.toLocaleUpperCase()
    //       break;
    //     case 1:
    //       return dis
    //       break;
    //     default:
    //       break;
    //   }
    // }
  } else {
    return new Error('密码规则转换失败')
  }
}

// 表单输入长度验证
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: '请输入正确地址'
}
