import { numCapture } from "@/util/Filters.ts";


import keys from "./keys.js";

import config from '@/config/global.config.js'
import Vue from 'vue'

const defaultAvatar = () => {
  return config.staticUrl + '/czd/default-avatar.jpg'
  // return config.staticUrl + '/head-on.png'
}

const pathHint = () => {
  uni.showToast({
    icon: 'none',
    title: '敬请期待'
  })
}


// const skipApps = (path) => {
// 	if (path === "#") {
// 		pathHint()
// 		return false
// 	}
// 	uni.navigateTo({
// 		url: `/pages/web-view/Apps?path=${encodeURIComponent(path)}`
// 	});
// }

const skipAggregation = (themeId) => {
  if (themeId) {
    try {

    } catch (err) {
      console.log('未配置页面')
    }
  } else {
    uni.showToast({
      icon: 'none',
      title: '聚合页面配置错误'
    })
  }
}

const skipWeb = (path, title) => {
  if (path === "#") {
    pathHint()
    return false
  }
  uni.navigateTo({
    url: `/pages/web-view/Apps?path=${encodeURIComponent(path)}&title=${title || ''}`,
    complete: () => {
      oldApps = null;
    }
  });
}

const base64Encode = (input) => {
  const utf8 = unescape(encodeURIComponent(input));
  const base64 = btoa(utf8);
  return base64;
}

const toAuthPage = (val, appId) => {

}

const InternalPage = {

}

const tabbarPage = []
const antiShake = true; // 是否开启防抖

let oldApps = null;
let openApp = null;
const getAppLocation = (id, name, appId) => {
  openApp = id


}



// 定位授权
const getIsAuthLocation = async () => {
  return new Promise((resolve, reject) => {
    // 1、判断手机定位服务【GPS】 是否授权
    uni.getSystemInfo({
      success(res) {
        // console.log("判断手机定位服务是否授权:", res);
        let locationEnabled = res.locationEnabled; //判断手机定位服务是否开启
        let locationAuthorized = res.locationAuthorized; //判断定位服务是否允许微信授权
        // console.log("判断手机定位服务是否开启",locationEnabled);
        // console.log("判断定位服务是否允许微信授权",locationAuthorized);
        if (locationEnabled == false || locationAuthorized == false) {
          //手机定位服务（GPS）未授权
          uni.showToast({
            title: '请打开手机GPS',
            icon: 'none',
          });
          resolve(false);
        } else {
          //手机定位服务（GPS）已授权
          // 2、判断微信小程序是否授权位置信息
          // 微信小程序已授权位置信息
          uni.authorize({
            //授权请求窗口
            scope: 'scope.userLocation', //授权的类型
            success: async (res) => {
              resolve(await fnGetlocation());
            },
            fail: (err) => {
              err = err['errMsg'];
              uni.showModal({
                content: '需要授权位置信息',
                confirmText: '确认授权',
                success: (obj) => {
                  if (obj.confirm) {
                    uni.openSetting({
                      success: async (set) => {
                        if (set.authSetting['scope.userLocation']) {
                          // 授权成功
                          uni.showToast({
                            title: '授权成功',
                            icon: 'none',
                          });
                          resolve(await fnGetlocation());
                        } else {
                          // 未授权
                          uni.showToast({
                            title: '授权失败,请重新授权',
                            icon: 'none',
                          });
                          uni.showModal({
                            title: '授权',
                            content: '获取授权' + '失败,是否前往授权设置？',
                            success: function(result) {
                              if (result.confirm) {
                                uni.openSetting();
                              }
                            },
                            fail: function() {
                              uni.showToast({
                                title: '系统错误！',
                                icon: 'none',
                              });
                            },
                          });
                        }
                      },
                    });
                  } else {
                    resolve(false);
                    // 取消授权
                    uni.showToast({
                      title: '你拒绝了授权，无法获得周边信息',
                      icon: 'none',
                    });
                  }
                }
              })
            },
          });
        }
      },
    });
  });
};

// 定位获取
const fnGetlocation = async () => {
  return new Promise((resolve, reject) => {
    let that = this;
    let bindList = {
      long: '',
      lat: '',
      longlat: '',
      isLocated: false,
    };
    uni.getLocation({
      type: 'wgs84', //默认为 wgs84 返回 gps 坐标
      geocode: 'true',
      isHighAccuracy: 'true',
      accuracy: 'best', // 精度值为20m
      success: function(res) {
        let platform = uni.getSystemInfoSync().platform;
        if (platform == 'ios') {
          //toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
          bindList.long = res.longitude.toFixed(6);
          bindList.lat = res.latitude.toFixed(6);
        } else {
          bindList.long = res.longitude;
          bindList.lat = res.latitude;
        }
        resolve(bindList);
      },
      fail(err) {
        if (
          err.errMsg ===
          'getLocation:fail 频繁调用会增加电量损耗，可考虑使用 wx.onLocationChange 监听地理位置变化'
        ) {
          uni.showToast({
            title: '请勿频繁定位',
            icon: 'none',
          });
        }
        if (err.errMsg === 'getLocation:fail auth deny') {
          // 未授权
          uni.showToast({
            title: '无法定位，请重新获取位置信息',
            icon: 'none',
          });
          authDenyCb && authDenyCb();
          bindList.isLocated = false;
          resolve(bindList);
        }
        if (err.errMsg === 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF') {
          uni.showModal({
            content: '请开启手机定位服务',
            showCancel: false,
          });
        }
      },
    });
  });
};



export default {
  install(Vue) {
    Vue.prototype.$keys = keys;
    Vue.prototype.$skeletonTime = 500; // 骨架屏幕过度事件
    Vue.prototype.$defaultHadPhoto = config.defaultHadPhoto;
    Vue.prototype.$defaultAvatar = defaultAvatar;
    Vue.prototype.$getIsAuthLocation = getIsAuthLocation;



    Object.defineProperty(Vue.prototype, '$skipWeb', {
      value: (path, title) => {
        skipWeb(path, title)
      }
    });


    /**
     * 图片连接封装， 地址拼接
     * 
     */
    Object.defineProperty(Vue.prototype, '$getImgPath', {
      value: (path = '') => {
        let img = ""
        if (path.indexOf('http://') !== 0 && path.indexOf('https://') !== 0) {
          if (path.indexOf('/') !== 0) {
            img = config.staticUrl + '/' + path
          } else {
            img = config.staticUrl + path
          }

        }
        return img || path
        // return path
      }
      // value: (path = '', str = 'http') => {
      //   return filePathHandle(path, str)
      // }
    })

    Object.defineProperty(Vue.prototype, '$onDesensitization', {
      value: (type, text) => {
        let val = '';
        if (text) {
          switch (type) {
            case 'name':
              let arr = text.split("")
              arr = arr.map((v, i) => {
                return i > 0 ? '*' : v
              })
              val = `${arr.join("")}`;
              // val = `**${text.substring(text.length - 1)}`;
              break;
            case 'tel':
              const tel = '' + text;
              val = tel.substring(0, 3) + '****' + tel.substring(tel.length - 4);
              break;
          }
        }
        return val
      }
    })


    Object.defineProperty(Vue.prototype, '$editorFile', {
      value: (content = '') => {
        // const regex = /src="([^"]*)"/g;  
        const regex = /<image\s+[^>]*src="([^"]*)"/g;
        const updatedText = content.replace(regex, `<image src="${config.staticUrl}$1"`);
        return updatedText
      }
    })



    /**
     * 校验是否已登录
     * redirect : 是否需要重定向，true时直接跳转登录页面，false 则不跳转，通过Promise.reject返回错误，页面自行处理，
     * 默认为true
     */
    Object.defineProperty(Vue.prototype, '$VerifyLogin', {
      value: (redirect = true) => {
        return Promise.resolve()
        // return Promise.reject(345)
      }
    });





    // export const ApiCallback = async (Api, params) => {
    // 	const {
    // 		path,
    // 		method
    // 	} = Api;
    // 	let data = null
    // 	switch (method) {
    // 		case 'get':
    // 			data = await http.get(path, params);
    // 			break;
    // 		case 'post':
    // 			data = await http.post(path, params);
    // 			break;
    // 	}

    // 	if (data && data.code === 200) {
    // 		return Promise.resolve(data)
    // 	} else {
    // 		return Promise.reject(2)
    // 	}
    // }


    /**
     * 消息跳转
     * type 
     * applicationId 第三方应用 appid
     * linkAddress 第三方应用地址
     */
    Object.defineProperty(Vue.prototype, '$openMessage', {
      value: (messageInfo) => {
        if (messageInfo.type == 1) {
          getMessageAppLocation(messageInfo.applicationId, messageInfo.linkAddress)
        }
      }
    });


    /**
     * 唤醒小程序
     * 人脸识别
     * typeValue 0 纯唤醒小程序 1 授权登录 2 人脸识别
     */
    Object.defineProperty(Vue.prototype, '$openWXminiprogram', {
      value: (data = {}, typeValue = 0, auth = false) => {
        return new Promise((resolve, reject) => {
          plus.share.getServices(result => {
            let sweixin = '';
            for (var i = 0; i < result.length; i++) {
              let t = result[i];
              if (t.id == 'weixin') {
                sweixin = t;
              }
            }
            if (sweixin) {
              let id = ''
              let path = ''
              let type = 0
              switch (typeValue) {
                case 0:
                  id = data.appletOriginalId
                  path = data.address
                  break;
                case 1:
                  id = 'gh_9b86ebba08b0'
                  type = 0
                  path = `/pages/authLogin/authLogin?appName=宜格服务`
                  break;
                case 2:
                  id = 'gh_9b86ebba08b0'
                  type = 0
                  path =
                    `/pages/identify/face_indentify?name=${data.realName}&idCardNumber=${data.identityCard}&channel=app`
                  break;
              }
              sweixin.launchMiniProgram({
                  // id:"gh_9b86ebba08b0", // 要跳转小程序的原始ID
                  // type: 2, // 微信小程序版本类型可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
                  // path: `pages/identify/face_indentify?name=${data.realName}&idCardNumber=${data.identityCard}&channel=app`
                  id: id,
                  type: type,
                  path: path
                },
                // 目标小程序点击返回App后执行的回调，在此接收微信小程序传递的参数
                res => {
                  let resData = JSON.parse(res)
                  if (typeValue == 1) {
                    resolve(resData)
                  } else if (typeValue == 2) {
                    if (auth) {
                      resolve(resData)
                    } else {
                      facRedirectHandle(data, resData)
                    }
                  }

                },
                err => {
                  console.log(err)
                  uni.showToast({
                    icon: 'none',
                    title: '当前环境不支持微信操作!'
                  })
                }
              );
            } else {
              // 没有获取到微信分享服务
              uni.showToast({
                icon: 'none',
                title: '当前环境不支持微信操作!'
              })
            }
          }, error => {
            // 获取分享服务列表失败
            console.log(error)
          })
        })
      }
    });
    /**
     * 任务状态说明
     * checkStatus 审状态（0未提交,1待审核,2驳回,3审核通过）
     */
    Object.defineProperty(Vue.prototype, '$TaskStatusText', {
      value: (status) => {
        let text = "";
        if (status >= 0) {
          switch (status) {
            case 0:
              text = "未提交";
              break;
            case 1:
              text = "待审核";
              break;
            case 2:
              text = "驳回";
              break;
            case 3:
              text = "审核通过";
              break;
          }
        }
        return text
      }
    })

    // 判断图片是否 大于 20kb
    Object.defineProperty(Vue.prototype, '$getImageSize', {
      value: (url) => {
        return new Promise((resolve, reject) => {
          uni.downloadFile({
            url: url, //仅为示例，并非真实的资源
            success: (res) => {
              if (res.statusCode === 200) {
                console.log('下载成功==>', res);
                const tempFilePath = res.tempFilePath
                uni.getFileInfo({
                  filePath: tempFilePath,
                  success: (resFile) => {
                    console.log('获取文件信息成功==>', resFile)
                    const sizeKB = resFile && resFile
                      .size / 1024 || 0
                    console.log('sizeKB==>', sizeKB)
                    if (sizeKB > 20) {
                      resolve(true)
                    } else {
                      resolve(false)
                    }
                  },
                  fail: (fail) => {
                    resolve(false)
                  }
                })
              }
            },
            fail: (fail) => {
              resolve(false)
            }
          })
        })
      }
    })
  }

}