const ObjectId = require('mongoose').Types.ObjectId;
const createError = require('http-errors');
const moment = require('moment');

/**
 * 验证ID
 */
function validateId(id, errMsg) {
  errMsg = errMsg || 'ID错误!';
  if (!ObjectId.isValid(id)) {
    throw createError(400, errMsg);
  }
}

const phoneRegex = /^1[\d]{10}$/;
function validatePhone(phone, errMsg) {
  errMsg = errMsg || '手机号格式错误'
  if (!phoneRegex.test(phone)) {
    throw createError(400, errMsg)
  }
}

const usernameRegex = /^[a-zA-Z0-9_\.]{5,}$/;
function validateUsername(username, errMsg) {
  errMsg = errMsg || '用户名格式错误'
  if (!usernameRegex.test(username)) {
    throw createError(400, errMsg)
  }
}

const passwordRegex = /^.{8,}$/
function validatePassword(password, errMsg) {
  errMsg = errMsg || '密码格式错误'
  if (!passwordRegex.test(password)) {
    throw createError(400, errMsg)
  }
}

function validateName(name, errMsg) {
  if (!name || name.length < 2) {
    throw createError(400, errMsg || '名字最少两位')
  }
}

const idNoRegex = /^[\d]{17}[\dx]$/i
function validateIdNo(no, errMsg) {
  if (!idNoRegex.test(no))
    throw createError(400, '身份证格式错误');
}

let vinRegex = /^[A-HJ-NPR-Z0-9]{17}$/;
function validateVIN(vin) {
  if (!vinRegex.test(vin))
    throw createError(400, 'vin错误')
}

let DATE_FORMAT = ['YYYYMMDD', 'YYYY-MM-DD', 'YYYY/MM/DD'];
function validateDate(date) {
  let mmt = moment(date, DATE_FORMAT, true);
  if (!mmt.isValid()) throw createError(400, '日期格式错误')
  let startOfDay = mmt.startOf('day').toDate();
  let endOfDay = mmt.endOf('day').toDate();
  return [startOfDay, endOfDay];
}


function isValidDate(d) {
  return d instanceof Date && !isNaN(d);
}


module.exports = {
  validateId,
  validatePhone,
  validateName,
  validateIdNo,
  validateVIN,
  validateDate,
  validatePassword,
  validateUsername,
  isValidDate,
}
