// 获取位置信息
// var QQMapWX = require('mixins/js/qqmap-wx-jssdk.js')
import QQMapWX from '@/common/js/qqmap-wx-jssdk.js';

var qqmapsdk = null;
import log from './log';
// import store from '@/store/install.js'
import { kipAllCities } from '@/utils/api-kip.js';
import { isKOMiniApp, isKOBrand } from './utils.js';
import CacheTool from '@/utils/cache-tool.js';

export function location(that, mallid, scene, key) {
  if (!mallid && (that.globalData.mallid || that.globalData.mallid !== '')) {
    that.$isResolve();
    return false;
  }
}

// 	if (that.globalData.marketList.length == 0) {
// 		kipAllCities().then(resp => {
// 			if (!resp || !resp.hasOwnProperty("data")) {
// 				uni.showToast({
// 					title: "无法获取商场",
// 					icon: "none",
// 					duration: 2300
// 				})
// 				return
// 			}
// 			const result = resp.data;
// 			if (result && result.code === '000000') {
// 				console.log('===> 请求所有商场')
// 				const marketList = getMarketList(result.data);
// 				that.globalData.marketList = marketList
// 				if (marketList.length > 0) {
// 					let defaultMarket = marketList[0]
// 					log.info(`===> 设置第一个默认商场: ${defaultMarket.groupId} ${defaultMarket.mallid} ${defaultMarket.name}`)
// 					that.globalData.mallid = defaultMarket.mallid
// 					that.globalData.marketName = defaultMarket.name
// 					that.globalData.groupId = defaultMarket.groupId
// 					// 根据商场经纬度设置距离自己最近的商场
// 					getDefualtLocation(that);
// 					that.$isResolve()
// 				}
// 			} else {
// 				uni.showToast({
// 					icon: "none",
// 					title:"请求商场失败"
// 				});
// 			}
// 		}).catch(err => {
// 			console.error(err);
// 			uni.showToast({
// 				icon: "none",
// 				title:"请求商场失败"
// 			});
// 		})

// 	} else {
// 		that.globalData.mallid = that.globalData.marketList[0].mallid
// 		that.globalData.marketName = that.globalData.marketList[0].name
// 		that.globalData.groupId = that.globalData.marketList[0].groupId
// 		that.$isResolve()
// 	}
// };

// function getMarketList(result) {
// 	let marketList = [];
// 	if (result && result.length > 0) {
// 		result.forEach(item => {
// 			if (item.lbs && item.lbs.length > 0) {
// 				item.lbs.forEach(e => {
// 					// CRM 筛选出所有的商场
// 					if (e.format === 'RETAIL') {
// 						marketList.push({
// 							groupId: e.brand.id,
// 							mallid: e.id,
// 							latitude: e.lat,
// 							longitude: e.lng,
// 							name: e.name,
// 							defaultFlag: e.defaultFlag
// 						});
// 					}
// 				});
// 			}
// 		});
// 	}
// 	return marketList;
// }

// function getDefualtLocation(app, callbackFun) {
// 	const mapKey = app.globalData.key;
// 	qqmapsdk = new QQMapWX({
// 		key: mapKey // 必填
// 	})
// 	const marketList = app.globalData.marketList;
// 	var to = ""
// 	marketList.forEach(item => {
// 		if (item && item.latitude && item.longitude) {
// 			to += (item.latitude + ',' + item.longitude + ';')
// 		}
// 	})
// 	to = to.slice(0, to.length - 1)
// 	uni.getLocation({
// 		 type: 'wgs84',
// 		 success (res) {
// 			const latitude = res.latitude
// 			const longitude = res.longitude
// 			const location = latitude + ','+longitude
// 			app.globalData.location = location;
// 			qqmapsdk.calculateDistance({
// 				from: location,
// 				to: to,
// 				success: (mapres) => {
// 					console.log('===> 请求位置信息并计算最近的商场')
// 					for (let element of mapres.result.elements) {
// 						for (let market of marketList) {
// 							var latitude = parseFloat(market.latitude)
// 							var longitude = parseFloat(market.longitude)

// 							if (element.to.lat == latitude && element.to.lng ==
// 								longitude) {
// 								if (element.distance === 0) {
// 									console.log(market)
// 								}
// 								market.distance = element.distance
// 								break
// 							}
// 						}
// 					}
// 					// 移除无效的商场
// 					marketList.sort(compare('distance'))
// 					setDefault(app, marketList, () => {
// 						let curMarket = marketList[0]
// 						if (curMarket) {
// 							store.commit('changeCurMarket', curMarket)
// 						}

// 					});
// 				},
// 				fail: (err) => {
// 					log.error(err);
// 					const list = marketList.filter(e => e.defaultFlag)
// 					setDefault(app, list, () => {
// 						let curMarket = list[0]
// 						if (curMarket) {
// 							store.commit('changeCurMarket', curMarket)
// 						}
// 					})
// 				}
// 			})
// 		},
// 		fail () {
// 			console.warn("用户取消位置授权")
// 			log.warn('用户取消位置授权')
// 			const list = marketList.filter(e => e.defaultFlag)
// 			console.log(list)
// 			setDefault(app, list, () => {
// 				let curMarket = list[0]
// 				if (curMarket) {
// 					store.commit('changeCurMarket', curMarket)
// 				}
// 			})
// 		}
// 	})
// }

// function setDefault(app, marketList, callbackFun) {
// 	if (!marketList || !Array.isArray(marketList) || marketList.length == 0) return;

// 	app.globalData.marketList = marketList;

// 	const curMarket = marketList[0];
// 	app.globalData.mallid = curMarket.mallid
// 	app.globalData.marketName = curMarket.name
// 	app.globalData.marketAddress = curMarket.address
// 	app.globalData.groupId = curMarket.groupId

// 	uni.setStorageSync("groupId", curMarket.groupId);
// 	uni.setStorageSync("mallid", curMarket.mallid);

// 	console.info(`===> 计算商场距离并设置默认商场: ${curMarket.mallid} ${curMarket.name}`)
// 	log.info(`===> 计算商场距离并设置默认商场: ${curMarket.mallid} ${curMarket.name}`)
// 	if (callbackFun) {
// 		callbackFun();
// 	}
// }

export function compare(property) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  };
}

export function getLocationAndSetDefaultMarket(app, store, setDefaultMarket) {
  const mapKey = app.globalData.key;
  qqmapsdk = new QQMapWX({
    key: mapKey, // 必填
  });
  let marketList =
    uni.getStorageSync('marketList') || app.globalData.marketList;
  // crm 只保留定位杭州
  if (!isKOMiniApp()) {
    let crmArry = [];
    marketList.map((item) => {
      if (!isKOBrand(item.groupId)) {
        crmArry.push(item);
      }
    });
    marketList = crmArry;
  }
  const curMarket = uni.getStorageSync('curMarket');
  if (curMarket) {
    const { mallid } = curMarket;
    console.log(`===>获取到缓存中的商场信息, 缓存中的商场: ${mallid}`);
    console.log(curMarket);
    setDefaultMarket(app, store, marketList, mallid);
    return;
  }
  var to = '';
  marketList.forEach((item) => {
    if (item && item.latitude && item.longitude) {
      to += item.latitude + ',' + item.longitude + ';';
    }
  });
  to = to.slice(0, to.length - 1);
  uni.getLocation({
    type: 'wgs84',
    success(res) {
      const latitude = res.latitude;
      const longitude = res.longitude;
      const location = latitude + ',' + longitude;
      app.globalData.location = location;
      qqmapsdk.calculateDistance({
        from: location,
        to: to,
        success: (mapres) => {
          console.log('===> 请求位置信息并计算最近的商场1');
          for (let element of mapres.result.elements) {
            for (let market of marketList) {
              var latitude = parseFloat(market.latitude);
              var longitude = parseFloat(market.longitude);

              if (element.to.lat == latitude && element.to.lng == longitude) {
                if (element.distance === 0) {
                  console.log(market);
                }
                market.distance = element.distance;
                break;
              }
            }
          }
          // 移除无效的商场
          marketList.sort(compare('distance'));
          uni.setStorageSync('marketList', marketList);
          let curMarket = marketList[0] || {};
          const { mallid } = curMarket;
          setDefaultMarket(app, store, marketList, mallid);
        },
        fail: (err) => {
          log.error(err);
          console.error(
            `===> 计算最近距离失败(getLocationAndSetDefaultMarket)：使用默认商场`
          );
          uni.showModal({
            title: '提示',
            content: '计算距离错误,请手动选择商场',
            confirmText: '去选择',
            showCancel: false,
            success() {
              setTimeout(() => {
                if (app.$isResolve) {
                  app.$isResolve();
                  console.log('===>location $isResolve');
                }
                uni.navigateTo({
                  url: '/pages/chooseProject/chooseProject',
                });
              }, 1500);
            },
          });
          // const list = marketList.filter(e => e.defaultFlag)
          // let curMarket = list[0] || marketList[0]
          // const { mallid } = curMarket
          // setDefaultMarket(app, store, marketList, mallid)
        },
      });
    },
    fail() {
      console.warn('===> 用户取消位置授权0');
      log.warn('用户取消位置授权0');
      if (app.$isResolve) {
        app.$isResolve();
        console.log('===>location $isResolve');
      }
      uni.navigateTo({
        url: '/pages/chooseProject/chooseProject',
      });
      // const list = marketList.filter(e => e.defaultFlag)
      // let curMarket = list[0]  || marketList[0]
      // const { mallid } = curMarket
      // setDefaultMarket(app, store, marketList, mallid)
    },
  });
}

export function getMarketListDefault(marketList) {
  if (!marketList) return null;
  const list = marketList.filter((e) => e.defaultFlag);
}

/**
 * 如果当前缓存中没有mallid则获取会员位置并计算最近的商场并将商场为默认mallid
 * @param {Object} app
 * @param {Object} store
 * @param {Object} isQrcode
 * @param {Object} setDefaultMarket
 */
export function getLocationAndSetDefaultMarketNotUseCache(
  app,
  store,
  setDefaultMarket,
  isQrcode
) {
  const mapKey = app.globalData.key;
  qqmapsdk = new QQMapWX({
    key: mapKey, // 必填
  });
  let marketList =
    uni.getStorageSync('marketList') || app.globalData.marketList;
  // crm杭州小程序
  if (!isKOMiniApp()) {
    let crmArry = [];
    marketList.map((item) => {
      if (!isKOBrand(item.groupId)) {
        crmArry.push(item);
      }
    });
    marketList = crmArry;
  }
  var to = '';
  marketList.forEach((item) => {
    if (item && item.latitude && item.longitude) {
      to += item.latitude + ',' + item.longitude.trim() + ';';
    }
  });
  to = to.slice(0, to.length - 1);
  uni.getLocation({
    type: 'wgs84',
    success(res) {
      const latitude = res.latitude;
      const longitude = res.longitude;
      const location = latitude + ',' + longitude;
      app.globalData.location = location;
      qqmapsdk.calculateDistance({
        from: location,
        to: to,
        success: (mapres) => {
          console.log('===> 请求位置信息并计算最近的商场2');
          for (let element of mapres.result.elements) {
            for (let market of marketList) {
              var latitude = parseFloat(market.latitude);
              var longitude = parseFloat(market.longitude.trim());

              if (element.to.lat == latitude && element.to.lng == longitude) {
                if (element.distance === 0) {
                  console.log(market);
                }
                market.distance = element.distance;
                break;
              }
            }
          }
          // 移除无效的商场
          marketList.sort(compare('distance'));
          uni.setStorageSync('marketList', marketList);
          // 如果没有商场则设置最近的商场否则只计算不保存
          const currentMallid = uni.getStorageSync('mallid');
          if (!currentMallid) {
            let curMarket = marketList[0] || {};
            const { mallid } = curMarket;
            setDefaultMarket(app, store, marketList, mallid, isQrcode);
          }
        },
        fail: (err) => {
          log.error(err);
          console.error(
            `===> 计算最近距离错误(getLocationAndSetDefaultMarketNotUseCache)：使用默认商场`
          );
          uni.showModal({
            title: '提示',
            content: '计算距离错误,请手动选择商场',
            confirmText: '去选择',
            showCancel: false,
            success() {
              setTimeout(() => {
                if (app.$isResolve) {
                  app.$isResolve();
                  console.log('===>location1 $isResolve');
                }
                uni.navigateTo({
                  url: '/pages/chooseProject/chooseProject',
                });
              }, 1500);
            },
          });
          // const list = marketList.filter(e => e.defaultFlag)
          // let curMarket = list[0] || marketList[0]
          // const { mallid } = curMarket
          // setDefaultMarket(app, store, marketList, mallid, isQrcode)
        },
      });
    },
    fail() {
      console.warn('===> 用户取消位置授权1');
      log.warn('用户取消位置授权1');
      if (app.$isResolve) {
        app.$isResolve();
        console.log('===>location1 $isResolve');
      }
      uni.navigateTo({
        url: '/pages/chooseProject/chooseProject',
      });
      // const currentMallid = uni.getStorageSync("mallid");
      // if (!currentMallid) {
      // 	const list = marketList.filter(e => e.defaultFlag)
      // 	let curMarket = list[0]  || marketList[0]
      // 	const { mallid } = curMarket
      // 	setDefaultMarket(app, store, marketList, mallid, isQrcode)
      // }
    },
  });
}

// 过滤 KO 的商城
export function filterKOMarket(marketList) {
  if (!isKOMiniApp()) {
    let crmArry = [];
    marketList.map((item) => {
      if (!isKOBrand(item.groupId)) {
        crmArry.push(item);
      }
    });
    return crmArry;
  }
  return marketList;
}

// 构建 腾讯地图-计算距离 需要用到的参数
export function buildQQMapSdkCalculateParams(marketList) {
  let to = '';
  marketList.forEach((item) => {
    if (item && item.latitude && item.longitude) {
      to += item.latitude + ',' + item.longitude + ';';
    }
  });
  to = to.slice(0, to.length - 1);
  return to;
}

// 设置商城与当前会员定位的距离，如有 限制距离 则根据限制距离过滤
export function setMarketDistanceByLbsCalculResult(
  marketList,
  calculResult,
  limitDistance
) {
  for (let element of calculResult) {
    for (let market of marketList) {
      const latitude = parseFloat(market.latitude);
      const longitude = parseFloat(market.longitude);
      if (element.to.lat == latitude && element.to.lng == longitude) {
        market.distance = element.distance;
        break;
      }
    }
  }
  marketList.sort(compare('distance'));
  uni.setStorageSync('marketList', marketList);
  let newLbsList = [];
  if (limitDistance && limitDistance > 0) {
    const km = limitDistance * 1000;
    if (marketList && marketList.length > 0) {
      marketList.forEach((item) => {
        if (item.distance <= km) {
          newLbsList.push(item);
        }
      });
    }
  } else {
    newLbsList = marketList;
  }
  return newLbsList;
}

export function getLocationIsLimit(preGetLocationTime) {
  const curTime = new Date().getTime();
  if (!preGetLocationTime) {
    return false;
  }
  const limit = curTime - preGetLocationTime;
  const REQ_lOCATION_TIME_LIMIT =
    CacheTool.getCurEnvConst().REQ_lOCATION_TIME_LIMIT;
  if (limit < REQ_lOCATION_TIME_LIMIT) {
    return true;
  } else {
    return false;
  }
}

export function getLocation(app, store, marketList) {
  return new Promise((resolve, reject) => {
    const isLimit = getLocationIsLimit(store.state.getLocationTime);
    if (isLimit) {
      const REQ_lOCATION_TIME_LIMIT =
        CacheTool.getCurEnvConst().REQ_lOCATION_TIME_LIMIT;
      const s = REQ_lOCATION_TIME_LIMIT / 1000;
      reject(`获取定位太频繁，请间隔${s}秒`);
    } else {
      marketList = filterKOMarket(marketList);
      // 检查定位权限
      uni.getSetting({
        success(res) {
          if (res.authSetting['scope.userLocation']) {
            getLocationByPromise(app, store, marketList, resolve, reject);
          } else if (!res.authSetting['scope.userLocation']) {
            // 请求获取定位权限
            uni.authorize({
              scope: 'scope.userLocation',
              success(res) {
                getLocationByPromise(app, store, marketList, resolve, reject);
              },
              fail() {
                // 手动打开定位权限
                uni.showModal({
                  title: '提示',
                  content: '是否打开定位',
                  success(res) {
                    if (res.confirm) {
                      uni.openSetting({
                        success(res) {
                          log.info('打开授权成功');
                          console.info('===>打开授权成功');
                          reject('授权定位成功,请重新定位');
                        },
                        fail() {
                          reject('打开定位失败');
                        },
                      });
                    }
                  },
                });
              },
            });
          }
        },
        fail() {
          reject('获取授权信息失败');
        },
      });
    }
  });
}

export function getLocationByPromise(app, store, marketList, resolve, reject) {
  uni.showLoading({
    mask: true,
  });
  uni.getLocation({
    type: 'wgs84',
    success(res) {
      const latitude = res.latitude;
      const longitude = res.longitude;
      const location = latitude + ',' + longitude;
      const to = buildQQMapSdkCalculateParams(marketList);
      const mapKey = app.globalData.key;
      qqmapsdk = new QQMapWX({
        key: mapKey,
      });
      qqmapsdk.calculateDistance({
        from: location,
        to: to,
        success: (mapres) => {
          const calculResult = mapres.result.elements;
          const LOCATION_DISTANCE_RANGE =
            CacheTool.getCurEnvConst().LOCATION_DISTANCE_RANGE;
          const newLbsList = setMarketDistanceByLbsCalculResult(
            marketList,
            calculResult,
            LOCATION_DISTANCE_RANGE
          );
          if (newLbsList && newLbsList.length > 0) {
            resolve(newLbsList);
          } else {
            reject(`您附近${LOCATION_DISTANCE_RANGE}公里范围内无位置信息`);
          }
          store.commit('saveGetLocationTime');
        },
        fail: (err) => {
          log.error(err);
          console.error(`===> 计算最近距离失败(getLocation)`);
          store.commit('saveGetLocationTime');
          reject('计算距离失败');
        },
      });
    },
    fail() {
      console.warn('===> 用户取消位置授权(getLocation)');
      log.warn('用户取消位置授权(getLocation)');
      store.commit('saveGetLocationTime');
      reject('位置授权失败');
    },
  });
}

// export default {
// 	getLocationAndSetDefaultMarket,
// 	compare,
// 	getLocationAndSetDefaultMarketNotUseCache,
// 	getLocation,
// };
