import wepy from '@wepy/core';
import {
  checkLogin
} from '@/service/user';
import moment from 'moment';

export default {
  genId,
  getGenderDesc,
  getTwoNum,
  getFutureDayList,
  getWeekDesc,
  getHourList,
  getHourObj,
  payItemsC2S,
  payItemsS2C,
  invitationS2C,
  formateTime,
  getHour12Desc,
  addUrlVersion,
  addUrlParams,
  getPeriodTimeDesc,
  getDateSimpleDesc,
  getDateDesc,
  debounce,
  formatepmValueToStatusText,
  getPmfromHttpResult,
  getUrlParams,
  // 刷新接口
  refreshCode,
  // 轮训获取
  getQrcode,
  formateEnvIndicatorValue,
  random,
  getTextHcho,
  getTextCO2,
  getTextHumidity,
  getTextPM,
  getEnvIndectorDesc,
  formatePassLinkToText,
  formatePassLinkItemToText,
  generateImgRandomStr,
  getSearchRegEx,
  formateInvitationPassLink,
  formateDateDurationTime,
  transformColorHex2Rgba,
  isDeepColor,
  previewAgreement
};

let seed = 0;

function genId() {
  return 'hx-' + Date.now() + ++seed;
}

function getGenderDesc(type) {
  let map = {
    man: '先生',
    woman: '女士',
    '': '贵宾',
  };
  return map[type] || map[''];
}

function getTwoNum(num) {
  let str = '' + num;
  if (num < 10) {
    str = '0' + str;
  }
  return str;
}

function getFutureDayList(num) {
  let result = [];
  let dateObj = new Date();
  let date = dateObj.getDate();
  result.push({
    date: date,
    dayDesc: '今天',
  });
  for (let i = 1; i < num; i++) {
    dateObj.setDate(date + i);
    result.push({
      date: dateObj.getDate(),
      dayDesc: getWeekDesc(dateObj.getDay()),
    });
  }
  return result;
}

function getWeekDesc(day) {
  let map = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    0: '周日',
  };
  return map[day] || '';
}

function getHourList(startHour, endHour) {
  let result = [];
  for (let i = startHour; i < endHour; i++) {
    result.push([getHourObj(i, 0), getHourObj(i, 30)]);
  }
  return result;
}

function getHourObj(hour, minutes) {
  let totalMinutes = hour * 60 + minutes;
  let newHour = parseInt(totalMinutes / 60);
  let newMinutes = totalMinutes % 60;
  return {
    value: totalMinutes / 60,
    desc: getTwoNum(newHour) + ':' + getTwoNum(newMinutes),
  };
}

// 将创建邀请函时为访客代支付的内容，由web端存储转换为后端存储
// 前端payItems: ['park', 'business', 'diningHall'],
// 后端：由三位组成，第一位表示停车费，第二位表示商业消费，第三位表示食堂，比如010
function payItemsC2S(payItems) {
  payItems = payItems || [];
  let strPark = payItems.indexOf('park') > -1 ? '1' : '0';
  let strBusiness = payItems.indexOf('business') > -1 ? '1' : '0';
  let strDiningHall = payItems.indexOf('diningHall') > -1 ? '1' : '0';
  return strPark + strBusiness + strDiningHall;
}

function payItemsS2C(payItemStr) {
  payItemStr = payItemStr || '';
  let payItems = [];
  if (payItemStr.match(/1../)) {
    payItems.push('park');
  }
  if (payItemStr.match(/.1./)) {
    payItems.push('business');
  }
  if (payItemStr.match(/..1/)) {
    payItems.push('diningHall');
  }
  return payItems;
}

// 邀请函数据转换：服务端->客户端
function invitationS2C(serverData) {
  let clientData = Object.assign(serverData, {
    applyStatus: 1, //1-是通过, 2-是失效
  });

  try {
    clientData.visitSite = JSON.parse(serverData.addr);
  } catch (e) {
    clientData.visitSite = {};
  }
  if (serverData.startTime) {
    clientData.startTime = formateResultDate(serverData.startTime);
  } else {
    clientData.startTime = null;
  }
  if (serverData.endTime) {
    let endTime = formateDateToDateObj(serverData.endTime);
    // 例: 8月20日 00:00 改为 8月19日24:00
    if (endTime.getHours() == 0 && endTime.getMinutes() == 0) {
      let time = new Date(endTime.getTime() - 60 * 1000);
      clientData.endTime = {
        abbrDate: `${time.getMonth() + 1}月${time.getDate()}日`,
        hour: '24:00',
        time  // 时间对象
      }
    } else {
      clientData.endTime = formateResultDate(serverData.endTime);
    }
  } else {
    clientData.endTime = null;
  }
  clientData.visitStatus = (serverData.status + 3) % 4;
  clientData.visitorType = serverData.type;
  clientData.visitorName = serverData.title;
  clientData.payItems = payItemsS2C(serverData.payType);

  if (serverData.sex === 1) {
    clientData.gender = 'man';
  } else if (serverData.sex === 0) {
    clientData.gender = 'woman';
  } else {
    clientData.gender = '';
  }

  return clientData;
}

/* eslint-disable one-var */
function formateTime(time) {
  let year = time.getFullYear(),
    month = time.getMonth() + 1,
    date = time.getDate();
  let timeStr = time.toTimeString().split(' ')[0];
  month = month < 10 ? '0' + month : month;
  date = date < 10 ? '0' + date : date;
  return [year, month, date].join('/') + '  ' + timeStr;
}

// 将日期转换为12小时制
function getHour12Desc(time) {
  let result;
  time = (time || '').replace(/-/g, '/');

  var date = new Date(time);
  let hour = date.getHours();
  let minutes = date.getMinutes();
  //   let seconds = date.getSeconds();

  if (hour <= 12) {
    result = '上午 ' + getTwoNum(hour) + ':' + getTwoNum(minutes);
  } else {
    hour -= 12;
    result = '下午 ' + getTwoNum(hour) + ':' + getTwoNum(minutes);
  }
  return result;
}

// 给嵌入的H5页面地址加上参数，以避免缓存
function addUrlVersion(url) {
  const regExp = /([?&])t=.+(&)?/;
  let parameter = 't=' + Date.now();
  if (regExp.test(url)) {
    url = url.replace(regExp, '$1' + parameter + '$2');
  } else {
    if (url.indexOf('?') > -1) {
      url += '&' + parameter;
    } else {
      url += '?' + parameter;
    }
  }
  return url;
}

function addUrlParams(url, key, value, isRefresh) {
  const regExp = new RegExp('([?&]' + key + '=).+(&)?');
  if (regExp.test(url)) {
    if (isRefresh) {
      // 已存在该参数，做替换处理
      url = url.replace(regExp, '$1' + value + '$2');
    }
  } else {
    if (url.indexOf('?') > -1) {
      url += `&${key}=${value}`;
    } else {
      url += `?${key}=${value}`;
    }
  }
  return url;
}

function formateDateToDateObj(date) {
  if (!(date instanceof Date)) {
    if (/^\d+$/.test(date)) {
      date = Number(date);
    } else {
      // 部分手机不支持 yyyy-MM-dd 这种格式
      date = (date || '').replace(/-/g, '/');
    }
    date = new Date(date);
  }
  return date;
}

function getPeriodTimeDesc(startDate, endDate) {
  startDate = formateDateToDateObj(startDate);
  endDate = formateDateToDateObj(endDate);

  let startDateDesc = getDateDesc(startDate);
  let endDateDesc = '';
  // 将结束时间的00:00改为头天晚上的24:00
  if (endDate.getHours() == 0 && endDate.getMinutes() == 0) {
    endDate = new Date(endDate.getTime() - 60 * 1000);
    endDateDesc = getDateDesc(endDate);
    endDateDesc = endDateDesc.replace(/ \d+[^\d]*\d+/, ' 24:00');
  } else {
    endDateDesc = getDateDesc(endDate);
  }
  // 去掉相同的月日部分
  if (startDateDesc.split(' ')[0] == endDateDesc.split(' ')[0]) {
    endDateDesc = endDateDesc.replace(/.+ /, '');
    return `${startDateDesc} - ${endDateDesc}`;
  } else {
    let result = `${startDateDesc} - ${endDateDesc}`;
    // 如果跨天了，则改为由.来分割，以缩短界面占用
    result = result.replace(/[年月]/g, '.');
    result = result.replace(/[日]/g, '');
    return result;
  }
}

function getDateDesc(date) {
  let result = '';
  let today = new Date();
  today.setHours(0, 0, 0, 0);
  const differMilliseconds = date.getTime() - today.getTime();
  const differDays = parseInt(differMilliseconds / 86400000);
  const todayDay = today.getDay();
  if (differMilliseconds < 0 || differDays > 6) {
    result = date.getMonth() + 1 + '月' + date.getDate() + '日';
  } else {
    if (differDays <= 2) {
      const map = {
        0: '今天',
        1: '明天',
        2: '后天',
      };
      result = map[differDays];
    } else {
      const newDays = (todayDay + differDays) % 7;
      if (todayDay + differDays > 7) {
        result = '下' + getWeekDesc(newDays);
      } else {
        result = getWeekDesc(newDays);
      }
    }
  }
  return (
    result +
    ' ' +
    getTwoNum(date.getHours()) +
    ':' +
    getTwoNum(date.getMinutes())
  );
}

function debounce(callback, interval) {
  let timer = ''
  return function (args) {
    if (timer) return
    timer = setTimeout(() => {
      callback(args)
      timer = ''
    }, interval)
  }
}

function getDateSimpleDesc(date) {
  let today = new Date();
  today.setHours(0, 0, 0, 0);
  const differMilliseconds = date.getTime() - today.getTime();
  const differDays = parseInt(differMilliseconds / 86400000);
  let result;
  if (differDays <= 0) {
    return '今天';
  } else if (differDays <= 2) {
    const map = {
      0: "今天",
      1: "明天",
      2: "后天",
    };
    result = map[differDays];
  } else {
    result = (date.getMonth() + 1) + "月" + date.getDate() + "日" + ' ';
  }
  return result;
}


function formatepmValueToStatusText(value) {
  if (value === undefined) {
    return;
  }
  if (!value.toString()) return '良'; //防止为0跳出判断
  value = parseFloat(value); //防止字符串，将他转为小数点的数字
  let str = '';
  switch (true) {
    case value <= 35:
      str = '优';
      break;
    case value <= 75:
      str = '良';
      break;
    case value <= 150:
      str = '中';
      break;
    default:
      str = '差';
      break;
  }
  return str;
}

function getPmfromHttpResult(str) {
  // str如 "build:A座,floor:7,PM:11.41"
  let reg = /build:([^,]+),floor:(\d+),PM:(\d+(?:\.\d+)?)/gm;
  let matchResult = reg.exec(str);
  if (matchResult && matchResult.length && matchResult[3]) {
    return matchResult[3];
  } else {
    return '';
  }
}

function getUrlParams(str) {
  let params = {};
  if (!str) {
    return params;
  }

  let paramsStartIndex = str.indexOf('?');
  if (paramsStartIndex == -1) {
    return params;
  };

  let paramStr = str.slice(paramsStartIndex + 1);
  let paramsArray = paramStr.split('&');
  paramsArray.forEach(item => {
    let value = item.split('=');
    let key = value[0];
    let parmasValue = value[1];
    params[key] = parmasValue;
  })
  return params;
}


function formatePassLinkToText(links) {
  if (!links.length) {
    return '';
  }
  let areas = [];
  links.forEach(link => {
    areas.push(formatePassLinkItemToText(link));
  })

  return areas.join('、');
}

function formatePassLinkItemToText(link) {
  // let str = `${link.areaAuth || ''}${link.entrance || ''}`;
  // if (link.floor) {
  //   str = `${str}-${link.floor}层`;
  // }
  let str = link.name || '';
  return str;
}
/**
 * 
 * @param {本地缓存的key } storageKey 
 * @param {发送请求的接口} httpFun 
 * @param {规定超时的时长 单位为s} timeout 
 */
function refreshCode(storageKey, httpFun, timeout) {
  if (!httpFun) {
    return Promise.reject();
  }

  timeout = timeout || 10; // 默认超过10s 视为过期
  let catchData = null; // 如果有缓存数据，则拿缓存数据先进行判断
  if (storageKey) {
    catchData = wx.getStorageSync(storageKey);
  }

  if (!catchData) {
    return getQrcode(storageKey, httpFun, timeout);
  } else {
    // 有缓存数据 判断是否过期，
    let expireTime = new Date(catchData.expireTime).getTime() - 24 * 60 * 60 * 1000; //提前1天过期拿新接口
    let now = new Date().getTime();
    // 当前时间早于过期时间，即为未过期
    if (now <= expireTime) {
      return Promise.resolve(catchData);
    } else { //过期需要重新拉取数据
      return getQrcode(storageKey, httpFun, timeout);
    }
  }


}

/**
 * 
 * @param {发送请求的接口} httpFun 
 * @param {规定超时的时长 单位为} timeout 
 */
function getQrcode(storageKey, httpFun, timeout) {
  // 记录请求时间，以判断是否超时
  let startTime = new Date().getTime();

  return checkLogin().then(res => {
    return getQrcodeHttp(storageKey, httpFun, startTime, timeout);
  })
}

function getQrcodeHttp(storageKey, httpFun, startTime, timeout) {
  let now = new Date().getTime();
  // 如果轮训在10s内，继续查询，超出就显示网络异常
  if ((now - startTime) / 1000 >= timeout) {
    return Promise.reject({ reason: '循环超出时间了' })
  }
  return httpFun().then(res => {
    // 有缓存key,则需进行缓存
    if (storageKey) {
      wx.setStorageSync(storageKey, res.data);
    }

    return Promise.resolve(res.data);
  }, (res) => {
    // 网络异常 直接展示异常信息
    if (res && res.reason && res.reason == 'wxRequestFail') {
      return Promise.reject({ ...res })
    } else { //其他服务端异常信息，再次请求
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(getQrcodeHttp(storageKey, httpFun, startTime, timeout));
        }, 1000);
      });

    }
  })
}


function formateEnvIndicatorValue(key, value) {
  if (!key) {
    return '';
  }
  if (value == undefined || value == null || !(value.toString().length)) {
    return '';
  }

  let formatedValue;
  switch (key) {
    case 'co2':
      formatedValue = parseInt(value);
      break;
    case 'pm25':
      formatedValue = value == 0 ? 0 : parseFloat(value).toFixed(1);
      break;
    case 'hcho':
      formatedValue = value == 0 ? 0 : parseFloat(value).toFixed(2);
      break;
    case 'tvoc':
      formatedValue = value == 0 ? 0 : parseFloat(value).toFixed(1);
      break;
    case 'humidity':
      formatedValue = value == 0 ? 0 : parseFloat(value).toFixed(1);
      break;
    case 'temperature':
      formatedValue = value == 0 ? 0 : Math.round(parseFloat(value) * 10) / 10;
      break;
    case 'nh3':
      formatedValue = value == 0 ? 0 : Math.round(parseFloat(value) * 100) / 100;
      break;
    case 'h2S':
      formatedValue = value == 0 ? 0 : Math.round(parseFloat(value) * 10000) / 10000;
      break;
    default:
      formatedValue = parseInt(value);
  }

  return formatedValue.toString();
}

// 生成随机数
function random(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function getTextHcho(value) {
  if (!value) {
    return;
  }
  value = Number(value);
  let msg;
  switch (true) {
    case value <= 0.08:
      msg = '符合国标';
      break;

    case value <= 2:
      msg = '轻度超标';
      break;

    case value > 2:
      msg = '严重超标';
      break;
  }
  return msg;
}
function getTextHumidity(value) {
  if (!value) {
    return;
  }
  value = Number(value);
  let msg;
  switch (true) {
    case value <= 30:
      msg = '有点干燥';
      break;

    case value <= 80:
      msg = '体感舒适';
      break;

    case value > 80:
      msg = '有点潮湿';
      break;
  }
  return msg;
}
function getTextCO2(value) {
  if (!value) {
    return;
  }

  let msg;
  value = Number(value);
  switch (true) {
    case value <= 450:
      msg = '氧气充沛';
      break;

    case value <= 1000:
      msg = '通风良好';
      break;

    case value <= 2000:
      msg = '轻度污染';
      break;
    case value <= 5000:
      msg = '重度污染';
      break;
    case value > 5000:
      msg = '严重污染';
      break;
  }
  return msg;
}
function getTextPM(value) {
  if (!value) {
    return;
  }

  value = Number(value);

  let msg;
  switch (true) {
    case value <= 35:
      msg = '优秀';
      break;

    case value <= 75:
      msg = '良';
      break;

    case value <= 115:
      msg = '轻度污染';
      break;
    case value <= 150:
      msg = '中度污染';
      break;
    case value <= 250:
      msg = '重度污染';
      break;
    case value > 250:
      msg = '严重污染';
      break;
  }
  return msg;
}

function getTextNH(value) {
  if (!value) {
    return;
  }

  value = Number(value);

  let msg;
  switch (true) {
    case value <= 0.1:
      msg = '环境清新';
      break;

    case value <= 0.6:
      msg = '较为清新';
      break;

    case value <= 10:
      msg = '轻度异味';
      break;
    case value > 10:
      msg = '异味严重';
      break;
  }
  return msg;
}

function getTextH2S(value) {
  if (!value) {
    return;
  }

  value = Number(value);

  let msg;
  switch (true) {
    case value <= 0.0005:
      msg = '环境清新';
      break;

    case value <= 0.06:
      msg = '较为清新';
      break;

    case value <= 0.7:
      msg = '轻度异味';
      break;
    case value > 0.7:
      msg = '异味严重';
      break;
  }
  return msg;
}

function getTextTemperature(value) {
  if (!value) {
    return;
  }

  value = Number(value);

  let msg;
  switch (true) {
    case value <= 18:
      msg = '偏冷';
      break;

    case value <= 28:
      msg = '舒适';
      break;

    case value > 28:
      msg = '偏热';
      break;
  }
  return msg;
}

function getEnvIndectorDesc(id, value) {
  let des = ''
  switch (id) {
    case 'hcho':
      des = getTextHcho(value);
      break;
    case 'humidity':
      des = getTextHumidity(value);
      break;
    case 'co2':
      des = getTextCO2(value);
      break;
    case 'pm25':
      des = getTextPM(value);
      break;
    case 'nh3':
      des = getTextNH(value);
      break;
    case 'h2S':
      des = getTextH2S(value);
      break;
    case 'temperature':
      des = getTextTemperature(value);
      break;
  }
  return des;
}

/* 生成图片随机字符串 */
function generateImgRandomStr() {
  return `?-v=${Math.random().toString(36).slice(-8)}`;
}


/**
 * 拼接邀请函地址信息
 * @param {空间信息} spaceInfo 
 */
function formateInvitationPassLink(spaceInfo) {
  if (!spaceInfo) {
    return '';
  }
  const {
    building = '',
    officeBuilding = {},
    floor,
    roomNo,
    project = {}
  } = spaceInfo;
  const { name = '' } = project;
  let { isVirtual } = officeBuilding;
  return `${name}${!isVirtual ? (building || '') : ''}${floor || ''}${roomNo || ''}`;
}

/**
 * 
 * @param {根据keyword 转移成正则表达式}} text
 * @param {正则表达式匹配模式}} regFlags
 */
function getSearchRegEx(text, regFlags = 'i') {
  let result = '.*';
  const length = text.length;
  // 需转义的字符

  for (let i = 0; i < length; i++) {
    let character = text.substring(i, i + 1);
    character = transEharacter(character);
    // result += "(" + character + ")" + ".*";
    result += character + '.*';
  }
  return new RegExp(result, regFlags)
}

// 对特殊字符做转义处理
function transEharacter(character) {
  const escapeEharacters = '$().*+[{?|^';
  if (escapeEharacters.indexOf(character) > -1) {
    return `\${character}`;
  }
  if (character == '\\') {
    return `\\\\`;
  }
  return character;
}

/**
 * 返回 6月22日 14:00-16:00 | 12月1日 12:00 - 12月3日 10:00
 * @param {开始日期字符串} startTimeStr
 * @param {结束日期字符串} endTimeStr
 */
function formateDateDurationTime(startTimeStr, endTimeStr) {
  if (!startTimeStr || !endTimeStr) {
    return '';
  }
  let startTime = moment(startTimeStr);
  let endTime = moment(endTimeStr);
  let isSameDate = startTime.format('YYYY-MM-DD') === endTime.format('YYYY-MM-DD');
  if (isSameDate) {
    let date = startTime.format('M月D日');
    let time = `${startTime.format('HH:mm')} - ${endTime.format('HH:mm')}`
    return `${date} ${time}`
  } else {
    return `${startTime.format('M月D日 HH:mm')} - ${endTime.format('M月D日 HH:mm')}`
  }
}

/**
 * 返回 {abbrDate: '6月22日', hour: '12:54', time: 时间对象}
 * @param {时间字符串或者时间对象} date  
 */
export function formateResultDate(date) {
  if (!date) {
    return null;
  }
  let time, timeStr;
  if (!(date instanceof Date)) {
    if (/^\d+$/.test(date)) {
      date = Number(date);
    } else {
      // 部分手机不支持 yyyy-MM-dd 这种格式
      date = (date || '').replace(/-/g, '/');
    }
    time = new Date(date);
    timeStr = date;
  } else {
    time = date;
  }

  const abbrDate = `${time.getMonth() + 1}月${time.getDate()}日`;
  const hour = `${getTwoNum(time.getHours())}:${getTwoNum(time.getMinutes())}`;
  return {
    abbrDate,
    hour,
    time // 时间对象
  }
}
/**
 *  颜色数值从16进制转换为rgba 3个数值
 * @param color 
 */
function transformColorHex2Rgba(color) {
  if (!color) {
    return '';
  }
  var sColor = color.toLowerCase();
  //十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (var i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
      }
      sColor = sColorNew;
    }

    //处理六位的颜色值
    var sColorChange = [];
    for (var i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
    }
    return "rgba(" + sColorChange.join(",") + ")";
  } else {
    return sColor;
  }
}

// 是否为rgb颜色值
function isRgb(color) {
  return /^rgb/.test(color);
}
// 是否为十六进制颜色值
function isHex(color) {
  return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color);
}
// 是否为hsl颜色值
function isHsl(color) {
  return /^hsl/.test(color);
}

function getColorGrayLevel(color) {
  color = isRgb(color)
    ? color
    : transformColorHex2Rgba(color);

  var left = color.indexOf('(') + 1;
  var right = color.indexOf(')');

  let arr = color.slice(left, right).split(',');

  var r = arr[0],
    g = arr[1],
    b = arr[2];
  let grayLevel = r * 0.299 + g * 0.587 + b * 0.114; // 值越大越浅
  return grayLevel;
}

/**
 * @param {目标颜色} color
 * @param {判断颜色} juggeColor
 */

function isDeepColor(color, juggeColor) {
  if (!(color && juggeColor)) {
    return false;
  }
  let colorGrayLevel = getColorGrayLevel(color);
  let juggeColorLevel = getColorGrayLevel(juggeColor);
  return colorGrayLevel < juggeColorLevel;// 值越大越浅
}

function getCachedAgreement(url, serviceAgreementTitle, cacheKey) {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: `${cacheKey}-${url}`,
      success: res => {
        if (res.data) {
          let catchedFilePath = res.data

          const fs = wx.getFileSystemManager();
          fs.access({
            path: catchedFilePath,
            success: () => {
              // 文件存在
              console.log('文件存在', catchedFilePath);
              resolve(catchedFilePath);
            },
            fail: () => {
              console.log('文件不存在', catchedFilePath);
              // 文件不存在或其他错误, 需要重新下载
              getAgreementUrl(url, serviceAgreementTitle, cacheKey, resolve, reject);
            }
          });
        } else {
          console.log('---没有缓存')
          getAgreementUrl(url, serviceAgreementTitle, cacheKey, resolve, reject);
        }
      },
      fail: () => {
        console.log('---读取缓存失败')
        getAgreementUrl(url, serviceAgreementTitle, cacheKey, resolve, reject);
      }
    });
  });
}
function getAgreementUrl(url, serviceAgreementTitle, cacheKey, resolve, reject) {
  wx.showLoading({
    title: '', //提示的内容,
    mask: true, //显示透明蒙层，防止触摸穿透,
    success: res => { }
  });

  wx.downloadFile({
    url,
    success: res => {
      const filePath = res.tempFilePath;
      wx.setStorage({
        key: `${cacheKey}-${url}`,
        data: filePath
      });
      resolve && resolve(filePath);
      wx.hideLoading({ noConflict: true });
    },
    fail: (res) => {
      console.log('下载文件失败', res);
      reject();
      wx.hideLoading({ noConflict: true });
    }
  });
}

function previewAgreement(url, serviceAgreementTitle, cacheKey) {
  return new Promise((resolve, reject) => {
    getCachedAgreement(url, serviceAgreementTitle, cacheKey).then(filePath => {
      wx.openDocument({
        filePath: filePath,
        success: function () {
          resolve();
          console.log('打开文档成功');
        },
        fail: (res) => {
          reject('打开文档失败');
          console.log('打开文档失败', 'res');
        }
      });
    }).catch((res) => {
      reject('打开文档失败');
      console.log('---', res);
    });
  })
}
