import { SitLang, StandardStatus, RoomType, OrderType, DinnerType, HotelType, SendType } from './../@types/index';
import { i18n } from '../boot/i18n'
const {t} =i18n.global
/**
 * @description 按照需要写入 必要可以注入全局
 */

interface enumObj {
  key: string
  value: number
}

export interface DateType{
  id:number,
  bg:string,
  color:string,
  text:string
}

/**
 * @description 转化html
 */
 export function GetHtml(str: string) {
  if (str && str != "") {
    return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
      .replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, "'");
  }
  return str;
}

/**
 * @description 添加月份
 */
 export function AddMonth(dateStr: string, month: any) {
  var v = new Date(dateStr);
  if (v) {
    var t = new Date(v.getFullYear(), v.getMonth(), v.getDate(), v.getHours(), v.getMinutes(), v.getSeconds(), v.getMilliseconds());
    t.setMonth(v.getMonth() + month);
    if (t.getDate() != v.getDate()) {
      t.setDate(0);
    }
    return t;
  }
}

/**
 * @description 格式化日期
 */
 export function formatDate(year: string, month: any, day: any) {
  var y = year;
  var m = month;
  if (m < 10) m = "0" + m;
  var d = day;
  if (d < 10) d = "0" + d;
  return y + "-" + m + "-" + d;
}

/**
 * @description 格式化日期二
 */
 export function formatDate2(dateStr: string) {
  var date = new Date(dateStr);
  return {
    CYear: date.getFullYear(),
    CMonth: (date.getMonth() + 1),
    CDay: date.getDate(),
  }
}

/**
 * @description 计算日期
 */
 export function createCalendar(dateStr: any) {
  var days = [];
  var date:any;
  if (dateStr) {
    date = new Date(dateStr);
  } else {
    var now = new Date();
    date =  new Date(formatDate(String(now.getFullYear()), now.getMonth() + 1, 1));
  }
  var currentDay = date.getDate();
  var currentYear = date.getFullYear();
  var currentMonth = date.getMonth() + 1;
  var currentWeek = date.getDay(); // 1...6,0

  var str = formatDate(
    currentYear,
    currentMonth,
    currentDay
  );

  days.length = 0;
  // 当月第一天是周日，放在第一行第1个位置，前面0个
  //初始化第一周
  for (var i = currentWeek; i >= 0; i--) {
    var d = new Date(str);
    d.setDate(d.getDate() - i);
    var dayobject = {} as any;
    dayobject.day = d;
    days.push(dayobject); //将日期放入data 中的days数组 供页面渲染使用
  }

  //其他周
  var temp = 35;
  if (
    currentWeek +
    new Date(currentYear, currentMonth, 0).getDate() > 35
  ) {
    temp = 41;
  }
  for (var i: any = 1; i < temp - currentWeek; i++) {
    var d = new Date(str);
    d.setDate(d.getDate() + i);
    var dayobject = {} as any;
    dayobject.day = d;
    days.push(dayobject);
  }
  return {
    DayArray: days,
    CurrentDay: currentDay,
    CurrentMonth: currentMonth,
    CurrentYear: currentYear,
    CurrentWeek: currentWeek
  };
}

/**
 * @description 获取URL中参数
 */
 export function getUrlKey(name: string, url: string) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
}

/**
 * @description 计算距离天数
 */
export function dateDiffer(DateEnd: string) {
  //date1结束时间
  let date1 = new Date(DateEnd);
  //date2当前时间
  let date2 = new Date();
  date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
  date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
  const diff = date1.getTime() - date2.getTime(); //目标时间减去当前时间
  const diffDate = diff / (24 * 60 * 60 * 1000);  //计算当前时间与结束时间之间相差天数
  return diffDate
}

/**
 * @description 将枚举转为数组
 * @param objEnum 枚举对象
 * @returns 转化后的数组
 */
export function formatEnum(objEnum: any): Array<enumObj> {
  const array: Array<enumObj> = new Array<enumObj>()
  for (const key in objEnum) {
    if (!isNaNModified(key)) continue
    const tempEnumObj: enumObj = {
      key,
      value: objEnum[key] as number
    }
    array.push(tempEnumObj)
  }
  return array
}

export function isNaNModified(inputStr: string) {
  const numericRepr = parseFloat(inputStr)
  return isNaN(numericRepr) || numericRepr.toString().length != inputStr.length
}

export function getDayOfWeek(day:number){
  let weekLang=[t('dayOfWeek.mon'),t('dayOfWeek.tues'),t('dayOfWeek.wed'),t('dayOfWeek.thur'),t('dayOfWeek.fri'),t('dayOfWeek.sat'),t('dayOfWeek.sun')]
  return weekLang[day-1]
}

export function getHotelOrderStatus():Array<StandardStatus>{
  let status=[] as Array<StandardStatus>
  let text = [t('hotelorder.orderStatus.normal'),t('hotelorder.orderStatus.apply'),t('hotelorder.orderStatus.check'),t('hotelorder.orderStatus.cancel'),t('hotelorder.orderStatus.sun')]
  let color = ['','positive','dark','orange','negative']
  let icons = ['','update','done','offline_bolt','cached']
  text.forEach((x,i:number)=>{
    status.push({
      StatusId:i,
      StatusName:x,
      Icon:icons[i],
      Color:`text-${color[i]}`
    })
  })


  return status
}

export function getStrokeStatus():Array<StandardStatus>{
  let status=[] as Array<StandardStatus>
  let text = [t('v102.vehicle.strokestatus.d1'),t('v102.vehicle.strokestatus.d2'),t('v102.vehicle.strokestatus.d3')]
  // ,'positive'
  // ,'update'
  let color = ['','dark','orange','negative']
  let icons = ['','done','offline_bolt','cached']
  text.forEach((x,i:number)=>{
    status.push({
      StatusId:i+1,
      StatusName:x,
      Icon:icons[i],
      Color:`text-${color[i]}`
    })
  })


  return status
}

export function getScatteredHotelOrderStatus():Array<StandardStatus>{
  let status=[] as Array<StandardStatus>
  let text = [t('hotelorder.orderStatus.normal'),t('v101.scatteredOrderList.state1'),t('v101.scatteredOrderList.state2'),t('v101.scatteredOrderList.state3')]
  let color = ['','positive','dark','orange','negative']
  let icons = ['','update','done','offline_bolt','cached']
  text.forEach((x,i:number)=>{
    status.push({
      StatusId:i,
      StatusName:x,
      Icon:icons[i],
      Color:`text-${color[i]}`
    })
  })


  return status
}

export function groupBy(array: any[], f: any){
  const groups: {
      [key: string]: any[];
  } = {};
  array.forEach((item) => {
      const group = JSON.stringify(f(item));
      groups[group] = groups[group] || [];
      groups[group].push(item);
  });
  return Object.keys(groups).map((group) => {
      return {
        key:group.replace(/\"/g,""),
        data:groups[group]
      };
  });
}

export function getDateType(){
  let types=[] as Array<DateType>
  types.push({
    id:1,
    text:t('hotel.datetype.red'),
    color:'text-white',
    bg:'bg-red-9'
  })
  types.push({
    id:2,
    text:t('hotel.datetype.pink'),
    color:'text-white',
    bg:'bg-pink-4'
  })
  types.push({
    id:3,
    text:t('hotel.datetype.avg'),
    color:'text-white',
    bg:'bg-indigo-6'
  })
  types.push({
    id:4,
    text:t('hotel.datetype.dan'),
    color:'text-dark',
    bg:'bg-grey-3'
  })
  types.push({
    id:5,
    text:t('hotel.datetype.spe'),
    color:'text-white',
    bg:'bg-green'
  })
  types.push({
    id:6,
    text:t('hotel.datetype.xing'),
    color:'text-white',
    bg:'bg-brown'
  })

  return types
}

export function getHotelRoomType(getNormal:boolean = false):Array<RoomType>{
  let rooms = [] as Array<RoomType>
  if(getNormal){
    rooms.push({
      TypeId:0,
      TypeName:t('hotel.rooms.default')
    })
  }
  let roomLangs=[t('hotel.rooms.normal'),t('hotel.rooms.big'),t('hotel.rooms.sing'),t('hotel.rooms.three'),t('hotel.rooms.driver')]
  let fileds = ['CostPrice', 'BidroomPrice', 'SingleroomPrice', 'AddBedPrice', 'GuideRoomPrice']
  roomLangs.forEach((x:string,i:number)=>{
    rooms.push({
      TypeId:(i+1),
      TypeName:x,
      Field:fileds[i]
    })
  })
  return rooms
}
export function moneyFormat (num:any, decimal = 2, split = ','):any {
  function thousandFormat (num:any):any{
    const len = num.length
    return len <= 3 ? num : thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
  }
  if (isFinite(num)) { // num是数字
    if (num === 0) { // 为0
      return num.toFixed(decimal)
    } else { // 非0
      var res = ''
      var dotIndex = String(num).indexOf('.')
      if (dotIndex === -1) { // 整数
        res = thousandFormat(String(num)) + '' + '0'.repeat(decimal)
      } else {
        const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入，然后固定保留2位小数
        const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
        res = thousandFormat(numStr.slice(0, dotIndex)) + decimals
      }
      return res
    }
  } else {
    return '--'
  }
}
export function getHotelOrderType(getNormal:boolean = false):Array<OrderType>{
  let types = [] as Array<OrderType>
  if(getNormal){
    types.push({
      TypeId:0,
      TypeName:t('hotelorder.orderType.default')
    })
  }
  let typeLangs=[t('hotelorder.orderType.guest'),t('hotelorder.orderType.tour')]
  typeLangs.forEach((x:string,i:number)=>{
    types.push({
      TypeId:(i+1),
      TypeName:x
    })
  })
  return types
}

export function getTicketOrderType(getNormal:boolean = false):Array<OrderType>{
  let types = [] as Array<OrderType>
  if(getNormal){
    types.push({
      TypeId:-1,
      TypeName:t('hotelorder.orderType.default')
    })
  }
  let typeLangs=[t('v102.ticket.zq'),t('v102.ticket.yj')]
  typeLangs.forEach((x:string,i:number)=>{
    types.push({
      TypeId:i+1,
      TypeName:x
    })
  })
  return types
}

export function getDinners():DinnerType[]{
  let dinners = [] as Array<DinnerType>
  let dinStr = [t('dinner.a'),t('dinner.b'),t('dinner.c')]
  dinStr.forEach((x:string,i:number)=>{
    dinners.push({
      Id:i+1,
      Name:x
    })
  })
  return dinners
}

export function getSendType():SendType[]{
  let sendType = [] as Array<SendType>
  let sendStr = [t('v102.to.ps.p1'),t('v102.to.ps.p2')]
  let colors = ['text-negative','text-positive']
  sendStr.forEach((x:string,i:number)=>{
    sendType.push({
      Id:i+2,
      Name:x,
      Color:colors[i]
    })
  })
  return sendType
}

export function getHotelType():HotelType[]{
  let hotelTypes = [] as Array<HotelType>

  let types=[t('hotelType.a'),t('hotelType.b'),t('hotelType.c'),t('hotelType.c')]
  types.forEach((x:string,i:number)=>{
    hotelTypes.push({
      Id:i+1,
      Name:x
    })
  })

  return hotelTypes
}

export function getLangs() {
  const zhTw:SitLang={
    langLocale:"zhTW",
    langName:"中文繁体",
    quasarLang:'zh-TW'
  }
  const zhSw:SitLang={
    langLocale:"zhSW",
    langName:"中文简体"
  }
  const enUs:SitLang={
    langLocale:"enUs",
    langName:"English"
  }
  const koHG:SitLang={
    langLocale:"koHG",
    langName:"한국어",
    quasarLang:'ko-KR'
  }
  const jaRB:SitLang={
    langLocale:"jaRB",
    langName:"日本語",
    quasarLang:'zh-TW'
  }
  let langs:SitLang[]=[]
  // zhSw,enUs
  langs.push(zhTw,koHG,jaRB)
  return langs
}
