import Taro from '@tarojs/taro';

export function times(n) {
  return n > 0 ? '*'.repeat(n - 1).split('*') : []
}

/**
 * 
 * @param {*} img 
 * @param {*} quality  仅支持 70,50,30,5
 */
export function getThumbnail(img, quality) {
  if (!img) return img

  if (img.indexOf('https://estateagents.oss-cn-shanghai.aliyuncs.com') === 0) {
    return `${img}?x-oss-process=style/compress${quality || 30}`
  }

  return img
}

/**
 * 解析 queryString   a=b&c=d  ==> { a:b, c:d }
 * @param {*} queryString 
 */
export function parseQueryString(queryString) {
  if (!queryString || '?' === queryString) return undefined

  const query = queryString.indexOf('?') === 0 ? queryString.replace(/^\?/, '') : queryString
  
  return query.split('&').filter(x => x).reduce((acc, it) => {
    const [k, v] = it.split('=')
    const val = Object.prototype.hasOwnProperty.call(acc, k) ? [...([].concat(acc[k])), v] : v

    return {
      ...acc,
      [`${k}`]: val,
    }
  }, {})
}

/**
 * 格式化剩余时间为 xx天xx小时xx分xx秒
 * @param {int} leftTime 时间毫秒数
 */
export function formateLeftTime(leftTime) {
  const nd = 1000 * 24 * 60 * 60;
  const nh = 1000 * 60 * 60;
  const nm = 1000 * 60;
  const ns = 1000;

  const day = Math.floor(leftTime / nd);
  const hour = Math.floor(leftTime % nd / nh);
  const min = Math.floor(leftTime % nd % nh / nm);
  const sec = Math.floor(leftTime % nd % nh % nm / ns);

  return `${day}天${hour}小时${min}分${sec}秒`
}

export function getDownloadURL(url, type) {
  if (!url) return url

  switch (type) {
    case 'avatar':
      return url.replace('https://wx.qlogo.cn/', `${HOST}/qlogo/`);
    case 'alioss':
      return url.replace('https://estateagents.oss-cn-shanghai.aliyuncs.com/', `${HOST}/alioss/`);
    default:
      return url;
  }
}

/**
 * @description 获取当前页url
 */
export const getCurrentPageUrl = () => {
  let pages = Taro.getCurrentPages()
  let currentPage = pages[pages.length - 1]
  let url = currentPage.route
  return url
};

export const pageToLogin = () => {
  let path = getCurrentPageUrl()
  if (!path.includes('login')) {
    Taro.navigateTo({
      url: "/pages/login/login"
    });
  }
}

let endTime;
export function throttle(callback, time = 500) {
  const startTime = new Date().getTime();
  if (startTime - endTime > time || !endTime) {
    callback();
    endTime = startTime;
  }
}

export const wait = function (time = 500) {
  return new Promise(res => {
    setTimeout(() => {
      res();
    }, time);
  });
};

export const getQueryString = function (str, name) {
  var regex = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = str.match(regex);
  if (r != null) return unescape(r[2]);
  return null;
}
// 项目详情海报
export const makeProjectPoster = (res) => {
  return new Promise(resolve => {

    const { poster, qrcode, nickname, avatarurl, canvasName } = res
    const ctx = Taro.createCanvasContext(canvasName);
    const _avatarurl = getDownloadURL(avatarurl, 'avatar');
    const _poster = getDownloadURL(poster, 'alioss');

    Promise.all([
      Taro.downloadFile({ url: _poster }),
      Taro.downloadFile({ url: qrcode }),
      Taro.downloadFile({ url: _avatarurl })
    ]).then(list => {


      ctx.setFillStyle("#ffffff")
      ctx.fillRect(0, 0, 640, 1136)

      // 背景海报
      ctx.drawImage(list[0].tempFilePath, 0, 0, 640, 1136);


      //绘制名字
      ctx.setFontSize(30);
      ctx.setFillStyle('#fff');
      ctx.setTextAlign('left');
      ctx.fillText(nickname, 160, 920, 250);
      ctx.stroke();
      ctx.save();
      ctx.arc(500, 910, 60, 0, 2 * Math.PI)
      ctx.strokeStyle = "#ffffff";
      ctx.setFillStyle('#fff');
      ctx.fill();
      ctx.clip(); //裁剪上面的圆形
      ctx.drawImage(list[1].tempFilePath, 0, 0, 430, 430, 440, 850, 120, 120);
      ctx.restore()

      //绘制头像
      ctx.arc(96, 906, 50, 0, 2 * Math.PI) //画出圆
      ctx.strokeStyle = "#ffffff";
      ctx.clip(); //裁剪上面的圆形
      ctx.drawImage(list[2].tempFilePath, 46, 856, 100, 100);
      ctx.draw(false, function () {
        Taro.canvasToTempFilePath({
          canvasId: canvasName, success: function ({ tempFilePath }) {
            resolve(tempFilePath)
          }
        })
      });
    })
  })
}

// 删除本地缓存文件
export const removeLocalFile = (callback) => {
  Taro.getSavedFileList().then(res => {
    if (res.fileList.length > 0) {
      res.fileList.map(file => {
        Taro.removeSavedFile({ filePath: file.filePath })
      })
      callback && callback()
    } else {
      callback && callback()
    }
  })
}


// 把当前画布指定区域的内容导出生成指定大小的图片
export const canvasToTempFilePath = (canvasName, callback) => {
  Taro.canvasToTempFilePath({
    canvasId: canvasName,
    success: function (data) {
      var tempFilePath = data.tempFilePath
      callback(tempFilePath)
    },
    fail: function (res) {
      console.log(res);
    }
  });
}
// 保存文件到本地
export const saveFile = (tempFilePath, callback) => {
  Taro.saveFile({
    tempFilePath,
    success(res1) {
      Taro.hideLoading()
      console.log('成功' + res1.savedFilePath)
      callback(res1.savedFilePath);
    },
    fail: function (res) {
      console.log('失败');
    }
  })
}
// 下载文件
export const downloadFile = (imgUrl, callback) => {
  Taro.downloadFile({
    url: imgUrl,
    success: function (param) {
      if (param.statusCode === 200) {

        callback(param)
      }
    },
    fail: function (res) {
      console.log('生成失败请稍后重试');
    }
  })
}

// 生成名片海报
export const makeCardPoster = (data) => {
  return new Promise(resolve => {
    const { bgImg, qrcodeImg, name, nickname, avatarurl, company, post, canvasName } = data
    const ctx = Taro.createCanvasContext(canvasName);
    const _qrcodeImg = getDownloadURL(qrcodeImg, 'alioss');
    const _avatarurl = getDownloadURL(avatarurl, 'avatar');

    Promise.all([
      Taro.downloadFile({ url: _avatarurl }),
      Taro.downloadFile({ url: _qrcodeImg }),
    ]).then(list => {

      // 绘制背景
      ctx.setFillStyle("#ffe200")
      ctx.fillRect(0, 0, 640, 1040)
      ctx.drawImage(bgImg, 0, 0, 640, 1040);

      // 绘制小程序码
      ctx.drawImage(qrcodeImg, 170, 530, 290, 290);

      //绘制名字
      ctx.setFontSize(35);
      ctx.setFillStyle('#000');
      ctx.setTextAlign('center');
      ctx.fillText(name, 320, 356, 450);
      ctx.stroke();

      // 绘制圆角矩形
      roundRect(ctx, 220, 180, 320, 80, 10);
      ctx.strokeStyle = "#7ff724";
      ctx.setFillStyle("#7ff724")
      ctx.fill();
      ctx.stroke()

      //推荐语
      ctx.setFontSize(20);
      ctx.setFillStyle('#000');
      ctx.setTextAlign('left');

      // 文字换行
      var str = nickname + ':给你推荐个人,Ta特别靠谱~'
      var lineWidth = 0;
      var canvasWidth = 260;//文字宽度
      var initHeight = 213;//绘制字体距离canvas顶部初始的高度
      var lastSubStrIndex = 0; //每次开始截取的字符串的索引
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          ctx.fillText(str.substring(lastSubStrIndex, i), 250, initHeight);//绘制截取部分
          initHeight += 30;//20为字体的高度
          lineWidth = 0;
          lastSubStrIndex = i;
        }
        if (i == str.length - 1) {//绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), 250, initHeight);
        }
      }
      ctx.stroke();
      //绘制职位
      ctx.setFontSize(25);
      ctx.setFillStyle('#606060');
      ctx.setTextAlign('center');
      ctx.fillText(post, 320, 446, 450);
      ctx.stroke();
      //绘制公司
      ctx.setFontSize(25);
      ctx.setFillStyle('#606060');
      ctx.setTextAlign('center');
      ctx.fillText(company, 320, 500, 450);
      ctx.stroke();
      //长按或扫一扫了解Ta
      ctx.setFontSize(20);
      ctx.setFillStyle('#a5a5a5');
      ctx.setTextAlign('center');
      ctx.fillText('长按或扫一扫了解Ta', 320, 860, 450);
      ctx.stroke();
      ctx.save()

      // 绘制头像
      ctx.arc(146, 216, 50, 0, 2 * Math.PI) //画出圆
      ctx.strokeStyle = "#ffffff";
      ctx.clip(); //裁剪上面的圆形
      ctx.drawImage(list[0].tempFilePath, 96, 166, 100, 100);
      ctx.restore()

      // 绘制二维码
      ctx.save()
      ctx.arc(315, 675, 65, 0, 2 * Math.PI) //画出圆
      ctx.strokeStyle = "#ffffff";
      ctx.clip();
      ctx.drawImage(list[1].tempFilePath, 50, 0, 400, 400, 249, 610, 130, 130);
      ctx.draw(false, function () {
        Taro.canvasToTempFilePath({
          canvasId: canvasName, success: function ({ tempFilePath }) {
            resolve(tempFilePath)
          }
        })
      });
    })
  })
}

// 圆角矩形
export const roundRect = (ctx, x, y, w, h, r) => {
  if (w < 2 * r) r = w / 2;
  if (h < 2 * r) r = h / 2;
  ctx.beginPath();
  ctx.moveTo(x + r, y);
  ctx.arcTo(x + w, y, x + w, y + h, r);
  ctx.arcTo(x + w, y + h, x, y + h, r);
  ctx.arcTo(x, y + h, x, y, r);
  ctx.arcTo(x, y, x + w, y, r);
  ctx.closePath();
}

export const makeCardShareImg = (data) => {
  return new Promise(resolve => {

    const { bgImg, post, name, phoneImg, phone, picture, addrImg, company, canvasName } = data
    const ctx = Taro.createCanvasContext(canvasName);
    const _picture = getDownloadURL(picture, 'alioss');
    Promise.all([
      Taro.downloadFile({ url: _picture })
    ]).then(list => {

      ctx.setFillStyle("#ffffff")
      ctx.fillRect(0, 0, 750, 400)

      // 背景海报
      ctx.drawImage(bgImg, 0, 0, 750, 600);

      //职位
      ctx.setFontSize(28);
      ctx.fillText(post, 50, 90);

      //姓名
      ctx.setFontSize(60);
      ctx.fillText(name, 50, 170);

      ctx.setFontSize(30);

      // 导航图片
      ctx.drawImage(addrImg, 50, 400, 28, 28);
      //公司
      ctx.fillText(company, 100, 425);

      // 手机图片
      ctx.drawImage(phoneImg, 48, 450, 36, 36);
      //手机号码
      ctx.fillText('TEL: ' + phone, 100, 478);

      //绘制头像
      ctx.arc(550, 200, 100, 0, 2 * Math.PI) //画出圆
      ctx.strokeStyle = "#ffffff";
      ctx.stroke()

      ctx.clip(); //裁剪上面的圆形
      ctx.drawImage(list[0].tempFilePath, 450, 100, 200, 200, 400, 100);

      ctx.draw(false, function () {
        Taro.canvasToTempFilePath({ canvasId: canvasName, quality: 1 }).then(({ tempFilePath }) => {
          resolve(tempFilePath)
        })
      });
    })
  })
}

export const isObject = function (value) {
  var type = typeof value;
  return value != null && type === 'object';
}

//使用递归的方式实现数组、对象的深拷贝
export const deepClone = function (obj) {
  if (!isObject(obj)) {
    throw new Error('obj 不是一个对象！')
  }
  let isArray = Array.isArray(obj)
  let cloneObj = isArray ? [] : {}
  for (let key in obj) {
    cloneObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key]
  }

  return cloneObj
}


export const validateAuth = function (name, callback) {
  Taro.getSetting().then(res => {
    const hasAuth = res.authSetting[name]
    if (hasAuth) {
      callback && callback(true)
    } else {
      callback && callback(false)
    }
  })
}

/**
 * 检测 `phoneNumber` 是否是中国的手机号码。
 *
 * @param phoneNumber 要检测的电话号码
 * @param strict 是否严格模式
 * @returns `phoneNumber` 是中国的手机号码返回 `true`，否则返回 `false`
 */
export const isChineseMobilePhoneNumber = function (phoneNumber, strict) {
  if (strict === undefined) {
    strict = false;
  }
  return (strict ? /^1(?:3[0-9]|4[5-9]|5[0-9]|6[12456]|7[0-8]|8[0-9]|9[0-9])[0-9]{8}$/ : /^1[3-9][0-9]{9}$/).test(phoneNumber.toString());
}

/**
 * 检查 `value` 是否是一个邮件地址。
 *
 * @param value 要检查的值
 * @returns `value` 是邮件地址返回 `true`，否则返回 `false`
 * @see http://emailregex.com/
 */
export const isEmail = function (value) {
  var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(value);
}

/**
 * 转换海报的数据库配置为可用配置
 * @param {*} config 
 * @param {*} params 
 */
export function getCanvasConfig(config, params) {
  if (!config || !params) {
    throw new Error('转换海报配置出错: config 或 params 不能为空')
  }

  const { basic, items } = typeof config === 'string' ? JSON.parse(config) : config

  const itemConf = items.reduce((conf, item) => {
    const { type, remark, value, variable, ...others } = item
    const settingOfType = conf[type] || []
    let val = variable ? params[variable] : value

    let mainVal = {}
    switch (type) {
      case 'texts':
        mainVal = { text: val }
        break;
      case 'images':
        mainVal = { url: val }
        break;
      default:
        val = true
        break;
    }

    if (val) {
      settingOfType.push({
        ...mainVal,
        ...others,
      })
      conf[type] = settingOfType
    }
    
    return conf
  }, {})

  return {
    ...basic,
    ...itemConf,
  }
}
