import { Injectable } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Meta, Title } from '@angular/platform-browser';
import { Subject } from "rxjs/index";
import * as dayjs from 'dayjs'
declare var wx: any;
@Injectable({
  providedIn: 'root'
})
export class LifeCommonService {
  private shareStatusSource = new Subject<string>();
  shareStatus$ = this.shareStatusSource.asObservable();
  weekArr: Array<any>;
  constructor(private datePipe: DatePipe,
    private titleService: Title,
    private metaService: Meta) {
    this.weekArr = [{ week: '', day: '' }, { week: '', day: '' }, { week: '', day: '' }, { week: '', day: '' }, { week: '', day: '' }, { week: '', day: '' }, { week: '', day: '' }]
  }

  // 向订阅者发布分享结果
  // 0.关闭分享引导页
  // 1.用户点击分享
  // 2.已经分享过了
  shareStatusPublish(type) {
    this.shareStatusSource.next(type);
  }

  /**
   * 检测操作系统
   */
  checkOs() {
    let os;
    const isWin = (navigator.platform === 'Win32') || (navigator.platform === 'Windows');
    const isMac = (navigator.platform === 'Mac68K') ||
      (navigator.platform === 'MacPPC') ||
      (navigator.platform === 'Macintosh') ||
      (navigator.platform === 'MacIntel');
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
      os = 1;
      return os; // 这是iOS平台下浏览器
    } else if (/android/i.test(navigator.userAgent)) {
      os = 2;
      return os; // 这是Android平台下浏览器
    } else if (isWin) {
      os = 3;
      return os; // 这是Android平台下浏览器
    } else if (isMac) {
      os = 4;
      return os; // 这是mac系统
    } else if (/Linux/i.test(navigator.userAgent)) {
      os = 5;
      return os; // 这是Linux平台下浏览器
    } else {
      os = 6;
      return os;
    }
  }

  /**
   * 检测设备信息
   * deviceType:PC为1,移动端为2,微信为3
   */
  checkDeviceType() {
    let deviceType = null;
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {

      if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
        deviceType = '3';
      } else {
        deviceType = '2';
      }
    } else {
      deviceType = '1';
    }
    return deviceType;
  }

  /**
   * shareCode生成器
   */
  generateShareCode(jsonParams?: any) {
    const shareCode = {
      shareType: '1',
      os: this.checkOs(),
      channel: '0',
      isOrder: 0,
      jsonParams: JSON.stringify(jsonParams)
    };
    return shareCode;
  }

  // 设置title
  setTitle(title) {
    this.titleService.setTitle(title);
  }

  // 更新meta标签
  updateMeta(keywords, description) {
    this.metaService.updateTag({ content: keywords }, 'name=keywords');
    this.metaService.updateTag({ content: description }, 'name=description');
  }

  wxShare(title: string, desc: string, link: string, imgUrl: string) {
    const shareData = {
      title: title, // 分享标题
      desc: desc, // 分享描述
      link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: imgUrl, // 分享图标
      success: () => {
        this.shareStatusPublish(0);
      }
    };
    wx.ready(() => {   // 需在用户可能点击分享按钮前就先调用
      wx.updateAppMessageShareData(shareData);
      wx.updateTimelineShareData(shareData);
    });
  }

  // 根据开始时间设置结束时间,天数应减1，当日~当日是一天
  setInitDate(dayCount) {
    let dt;
    let dtEnd;
    (dt = new Date()).setDate(dt.getDate() + 1);
    (dtEnd = new Date(dt)).setDate(dt.getDate() + dayCount * 1 - 1);
    const initDate = {
      startDate: Date.parse(dt.toDateString()),
      endDate: Date.parse(dtEnd.toDateString())
    };
    sessionStorage.removeItem('timeRange');
    sessionStorage.setItem('initDate', JSON.stringify(initDate));
    const date = {
      startDate: dt,
      endDate: dtEnd
    };
    return date;
  }

  // 判断一年是365还是366
  yearDayCount(days, disableCalc?: boolean) {
    if (days === 365 || days === 366) {
      const y = new Date().getFullYear();
      const isLeap = (0 === y % 4) && (0 !== y % 100) || (0 === y % 400);
      days = isLeap ? 366 : 365;
      if (disableCalc) {
        days = 365;
      }
    }
    return days;
  }

  dateFormat(date: any, format?: string) {
    return this.datePipe.transform(date, format);
  }

  delHtmlTag(str) {
    return str.replace(/<[^>]+>/g, "");//去掉所有的html标记
  }

  /**
 * 姓名正则
 */
  nameValid(name) {
    const NAME_REGEXP = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·()（）。]{0,48}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,48}[a-zA-Z]{1}$)/;
    return NAME_REGEXP.test(name);
  }
  /**
   * 手机号码正则
   * @param no
   * @returns {boolean}
   */
  mobileNoValid(no) {
    const MOBILE_REGEXP = /^(1)\d{10}$/;
    return MOBILE_REGEXP.test(no);
  }

  getFileName(str) {
    let strArr = str.split('?');
    let k = strArr[0], appU = k.split('/');
    let L = appU[appU.length - 1];
    return L;
  }

  toPercent(point) {
    if (point == 0) {
      return 0 + '%';
    }
    let result = String(point * 100);
    let idx = result.indexOf(".");
    if (idx == -1 || result.substr(idx + 1).length <= 2) {
      return result + "%";
    }
    return result.substr(0, idx + 2) + "%";
  }

  transform(value: any, args?: any): any {
    if ((value + "").trim() == "") {
      return "";
    }
    if (typeof value == 'string') {
      value = value.replace(/,/gi, '');
    }
    if ((value + "").trim() == "") {
      return "";
    }
    if (isNaN(value)) {
      return "";
    }
    value = value + "";
    if (/^.*\..*$/.test(value)) {
      let pointIndex = value.lastIndexOf(".");
      let intPart = value.substring(0, pointIndex);
      let pointPart = value.substring(pointIndex + 1, value.length);
      intPart = intPart + "";
      const re = /(-?\d+)(\d{3})/
      while (re.test(intPart)) {
        intPart = intPart.replace(re, "$1,$2")
      }
      value = intPart + "." + pointPart;
    } else {
      value = value + "";
      var re = /(-?\d+)(\d{3})/
      while (re.test(value)) {
        value = value.replace(re, "$1,$2")
      }
    }
    return value;
  }

  getDate(str) {
    str = String(str)
    const newStr = str.substr(0, 4) + '年' + str.substr(4, 2) + '月';
    return newStr;
  }

  //获取本周日期
  makeDate(date?:any) {
    const now = dayjs(date);
    return this.weekArr.map((day, idx) => {
      return {
        week: now.day(idx).day(),
        day: now.day(idx).date(),
        date:  now.day(idx).format('YYYY-MM-DD')
      };
    });




    // var date = new Date();
    // var year = date.getFullYear();
    // var month = date.getMonth();
    // var week = date.getDay();
    // // if(week ==0){
    // //   week = 7;
    // // }
    // var month = month + 1;
    // //获取今天是几号
    // var day = date.getDate();
    // // 本周内今天的前几天的数量
    // var leftNum = week;
    // // 本周内今天的后几天的数量
    // var rightNum = 6 - week;
    // // 本周内今天的前几天
    // for (var i = 1; i <= leftNum; i++) {
    //   this.weekArr[i].week = week- i
    //     this.weekArr[i].day = day - i;
    //     this.weekArr[i]['date'] = year + '-' + (month>9?month:'0'+month) + '-' +  (day - i);
    // }
    // // 本周内今天的后几天
    // for (var i = 1; i <= rightNum; i++) {
    //   this.weekArr[i + week].week = week + i ;
    //   this.weekArr[i + week].day = day + i ;
    //   this.weekArr[i + week]['date'] = year + '-' + (month>9?month:'0'+month) + '-' + (day + i);
    // }
    // // 今天
    // this.weekArr[week].week = week;
    // this.weekArr[week].day = day;
    // this.weekArr[week]['date'] = year + '-' + (month>9?month:'0'+month) + '-' + day;
    // this.weekArr[week].selected = true;
    // return this.weekArr;
  }

  //获取星期
  getWeek(str){
    if(str==1){
      return '周一';
    }
    if(str ==2){
      return '周二';
    }
    if(str ==3){
      return '周三';
    }
    if(str==4){
      return '周四';
    }
    if(str ==5){
      return '周五';
    }
    if(str==6){
      return '周六';
    }
    if(str ==0){
      return '周日';
    }
  }
}
