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;
  }

  //检测是否微信浏览器
  isWeiXin(){
    let ua:any = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
      return true;
    }else{
      return false;
    }
  }

  /**
   * 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标记
  }

  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')
      };
    });
  }

  //获取星期
  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 '周日';
    }
  }

  scrollTo() {
    window.scrollTo(0, 0);
  }

  /**
   * 通过起保日期
   * 计算年龄
   * effectiveStartDate,
   * @param year
   * @param month
   * @param day
   * @returns {any}
   */
  ages(year, month, day) {
    // 是否从投保日计算生日1.是 0.不是 默认值0
    let effectiveStartBirthday;
    const selectedProduct = localStorage.getItem('selectedProduct');
    if (selectedProduct) {
      if (JSON.parse(selectedProduct).planPara &&
        (JSON.parse(selectedProduct).planPara.effectiveStartBirthday || (JSON.parse(selectedProduct).planPara.effectiveStartBirthday == 0))) {
        effectiveStartBirthday = JSON.parse(selectedProduct).planPara.effectiveStartBirthday;
      } else {
        effectiveStartBirthday = 0;
      }
    }
    let policyStartDate;
    const timeRange = sessionStorage.getItem('timeRange');
    if (timeRange) {
      policyStartDate = JSON.parse(timeRange).startDate;
    } else {
      (policyStartDate = new Date()).setDate(new Date().getDate() + 1);
    }
    // 'Y'是年，'D'是天
    const age = {
      age: null,
      ageUnit: 'Y'
    };
    let d;
    let returnAge;
    const birthYear = year;
    const birthMonth = month;
    const birthDay = day;
    if (effectiveStartBirthday == 0) {
      d = new Date(policyStartDate);
    } else {
      d = new Date();
    }
    const nowYear = d.getFullYear();
    const nowMonth = d.getMonth() + 1;
    const nowDay = d.getDate();
    if (nowYear === birthYear) {
      returnAge = (new Date(nowYear + '/' + nowMonth + '/' + nowDay).getTime() - new Date(year + '/' + month + '/' + day).getTime()) / (24 * 3600 * 1000);
      age.ageUnit = 'D';
    } else {
      const ageDiff = nowYear - birthYear; // 年之差
      if (ageDiff > 0) {
        if (nowMonth === birthMonth) {
          const dayDiff = nowDay - birthDay; // 日之差
          if (dayDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        } else {
          const monthDiff = nowMonth - birthMonth; // 月之差
          if (monthDiff < 0) {
            returnAge = ageDiff - 1;
          } else {
            returnAge = ageDiff;
          }
        }
      } else {
        returnAge = -1; // 返回-1 表示出生日期输入错误 晚于今天
      }
    }
    age.age = returnAge;
    return age; // 返回周岁年龄
  }

   /**
   * 身份证号码校验，并获取生日、性别、年龄
   * @param code
   * @returns {{pass: boolean, msg: string, birthDay: number, gender: null, age: null, ageUnit: string}}
   * @constructor
   */
  IdCodeValid(code) {
    if (code) {
      // 身份证号合法性验证
      // 支持15位和18位身份证号
      // 支持地址编码、出生日期、校验位验证
      const city = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江 ',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北 ',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏 ',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        81: '香港',
        82: '澳门',
        83: '台湾',
        91: '国外 '
      };
      // 出生年月日校验   前正则限制起始年份为1900;
      const year = code.substr(6, 4); // 身份证年
      const month = code.substr(10, 2); // 身份证月
      const date = code.substr(12, 2); // 身份证日
      const birth = new Date(year + '-' + month + '-' + date);
      const time = Date.parse(year + '-' + month + '-' + date); // 身份证日期时间戳date
      const now_time = Date.parse(new Date().toDateString());
      const dates = (new Date(year, month, 0)).getDate(); // 身份证当月天数
      const gender = code.substr(16, 1);
      let row = {
        'pass': true,
        'msg': '验证成功',
        'birthDay': time,
        'gender': null,
        'age': null,
        'ageUnit': 'Y'
      };
      if (parseInt(gender % 2 + '', 0) === 1) {
        row.gender = '1';
      } else {
        row.gender = '2';
      }
      row.age = this.ages(birth.getFullYear(), birth.getMonth() + 1, birth.getDate()).age;
      row.ageUnit = this.ages(birth.getFullYear(), birth.getMonth() + 1, birth.getDate()).ageUnit;
      if (!code || !/^\d{6}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
        row = {
          'pass': false,
          'msg': '身份证号格式错误',
          'birthDay': null,
          'gender': null,
          'age': null,
          'ageUnit': 'Y'
        };
      } else if (!city[code.substr(0, 2)]) {
        row = {
          'pass': false,
          'msg': '身份证号地址编码错误',
          'birthDay': null,
          'gender': null,
          'age': null,
          'ageUnit': 'Y'
        };
      } else if (time > now_time || date > dates) {
        row = {
          'pass': false,
          'msg': '出生日期不合规',
          'birthDay': null,
          'gender': null,
          'age': null,
          'ageUnit': 'Y'
        }
      } else {
        // 18位身份证需要验证最后一位校验位
        if (code.length == 18) {
          code = code.split('');
          // ∑(ai×Wi)(mod 11)
          // 加权因子
          const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
          // 校验位
          const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
          let sum = 0;
          let ai = 0;
          let wi = 0;
          for (let i = 0; i < 17; i++) {
            ai = code[i];
            wi = factor[i];
            sum += ai * wi;
          }
          if (parity[sum % 11] != code[17].toUpperCase()) {
            row = {
              'pass': false,
              'msg': '身份证号校验位错误',
              'birthDay': null,
              'gender': null,
              'age': null,
              'ageUnit': 'Y'
            };
          }
        }
      }
      return row;
    }
  }

    /**
   * 姓名正则(包含公司名)
   */
  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);
  }

  /**
   * 邮箱正则
   */
  emailValid(email) {
    const EMAIL_REGEXP = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
    return EMAIL_REGEXP.test(email);
  }
  //检测字符串是否只有中文、英文、数字
  checkCEN(val) {
    const cen_reg = /^[A-Za-z0-9\u4e00-\u9fa5]+$/;
    return cen_reg.test(val);
  }
  /**
   * 检测统一社会信用代码只能是数字和字母
   * @param val
   * @returns {boolean}
   */
  checkTaxNo(val) {
    const taxNo_reg = /[a-zA-Z0-9]{5,20}/;
    return taxNo_reg.test(val);
  }
}
