import $http from "./https";
import Cache from "./cache";
import httpConfig from "./httpConfig";
import Crypto from './aes.js'
const { CryptoJS } = Crypto;
const app = getApp();

// 检查是否选择医院
export function checkChooseHosp() {
    return new Promise((resolve, reject) => {
        const userData = Cache.get('userData');
        if (userData && !userData.hospID) {
            reject();
            uni.navigateTo({
                url: '/pages/index/pages/switchHospital/switchHospital'
            });
        } else {
            resolve();
        }
    });
}

// 获取医院数据
export function getHospList(app, hospital_code) {
    return new Promise((resolve, reject) => {
        let data = {
            params: []
        };
        $http.post('urlS', this, {
            code: '02010009',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
					Cache.set('allHospitalData', res.result, 2 * 60 * 60); // 缓存时效2小时
                    dealSwitchHospital(res.result, app)
						.then(resp => {
							resolve({result: res.result, hospData: !resp ? [] : resp});
						})
                    
                } else {
                    reject(res);
                }
            },
            error: function (error) {
                uni.hideLoading();
                uni.showToast({
                    title: '网络异常',
                    icon: 'none',
                    duration: 2000
                });
				reject(error);
            }
        });
    });
}

/** 
 * 传入的数据只有一家医院数据，则默认选中绑定该医院
 * @allHospData Array 
*/ 
export function dealSwitchHospital(allHospData, app, hospital_code) {
	return new Promise((resolve, reject) => {
		if (allHospData && allHospData.length === 1) {
			const hospData = allHospData[0]
		    switchHospital(hospData, app);
			Cache.set('refresh', 1)
			resolve(hospData)
		} else if (allHospData.length > 1) {
		    let isHosp = false;
		    let hospData = {};
		    for (var i = 0; i < allHospData.length; i++) {
		        if (allHospData[i].hisHospID === hospital_code) {
		            isHosp = true;
		            hospData = allHospData[i];
					resolve(hospData)
		            break;
		        }
		    }
		    if (isHosp) {
		        switchHospital(hospData, app);
		    }
		}
		resolve(false)
	})
}

// 处理医院数据
export function dealHospData(hospData, currentLatlng, province) {
    return new Promise(async (resolve, reject) => {
        const userData = Cache.get('userData');
        if (hospData && currentLatlng) {
            const hospDistanceData = hospData.map((item) => {
                console.log(item);
                const latLong = (currentLatlng + ',' + item.latitude + ',' + item.longitude).split(',');
                const resDistance = getDistanceInMeters('km', latLong);
                item['distance'] = resDistance.toFixed(2);
                return item;
            });
            console.log('hospDistanceData', hospDistanceData);
            Cache.set('allHospitalData', hospDistanceData); // 存储所有医院数据
            console.log('所有医院数据：', hospDistanceData);
            const currentProvinceHospArr = hospDistanceData.filter((item) => item.province.includes(province));
            console.log('当前省份医院数据：', currentProvinceHospArr);
            const otherProvinceHospArr = hospDistanceData.filter((item) => !item.province.includes(province));
            console.log('其他省份医院数据：', otherProvinceHospArr);
            const currentSelectedHospArr = hospDistanceData.filter((item) => item.hisHospID == userData.hisHospID);
            console.log('当前选择的医院数据：', currentSelectedHospArr);
            // 如果当前省份有多家医院，按距离进行排序
            if (currentProvinceHospArr.length > 1) {
                currentProvinceHospArr.sort((a, b) => a.distance - b.distance);
            }
            if (otherProvinceHospArr.length > 1) {
                otherProvinceHospArr.sort((a, b) => a.distance - b.distance);
            }
            const arr = currentProvinceHospArr.filter((item) => item.latitude && item.longitude);
            const calculateDistanceArr = arr.map((item) => item.latitude + ',' + item.longitude);
            if (calculateDistanceArr && calculateDistanceArr.length > 0) {
                await getQQlxgh(currentLatlng, calculateDistanceArr).then((data) => {
                    // console.log('计算距离后的数据', data)
                    if (data && data.length > 0) {
                        data.map((item, index) => {
                            currentProvinceHospArr[index].distance = (item.elements[0].distance / 1000).toFixed(2);
                        });
                    }
                });
            }
            let cacheHospData = Cache.get('cacheHospData');
            if (cacheHospData) {
                cacheHospData.currentHospList = currentSelectedHospArr;
                cacheHospData.currentProvinceHospList = currentProvinceHospArr;
                cacheHospData.otherProvinceHospList = otherProvinceHospArr;
            } else {
                cacheHospData = {
                    currentHospList: currentSelectedHospArr,
                    currentProvinceHospList: currentProvinceHospArr,
                    otherProvinceHospList: otherProvinceHospArr
                };
            }
            console.log('cacheHospData', cacheHospData);
            // 缓存处理后的医院数据
            Cache.set('cacheHospData', cacheHospData);
            resolve({
                cacheHospData,
                hospDistanceData
            });
        } else {
            const cacheHospData = {
                currentHospList: hospData.filter((item) => item.hisHospID == userData.hisHospID),
                currentProvinceHospList: ospData.filter((item) => item.province.includes(province)) ?? [],
                otherProvinceHospList: hospData.filter((item) => item.hisHospID != userData.hisHospID)
            };
            Cache.set('cacheHospData', cacheHospData);
            resolve({
                cacheHospData,
                hospDistanceData: []
            });
        }
    });
}

// 切换医院，设置userData数据缓存
export function switchHospital(hospData, app) {
    let userData = Cache.get('userData');
    Cache.set('userData', {
        ...userData,
    	province: hospData.province,
    	latitude: hospData.latitude,
    	longitude: hospData.longitude,
        businessHoursInfo: hospData.businessHoursInfo,
        emergBusTimeInfo: hospData.emergBusTimeInfo,
        nightBusTimeInfo: hospData.nightBusTimeInfo,
        hospID: hospData.hospID,
        hospDesc: hospData.hospDesc,
        hisHospID: hospData.hisHospID,
        hospAddress: hospData.hospAddress,
        telephone: hospData.telephone,
        menuMode: hospData.menuMode,
        serviceCall: hospData.serviceCall,
        serviceCallTips: hospData.serviceCallTips,
        upLoadUrl: hospData.upLoadUrl,
        downLoadUrl: hospData.downLoadUrl,
        logoUrl: hospData.logoUrl,
		cosultFile: hospData.cosultFile,
		consultFileUpload: hospData.consultFileUpload,
		pubAccountDate: hospData?.pubAccountDate || {},
    	ifHLWConsultation: hospData?.ifHLWConsultation || '', // 智能导诊
    	guideHospConfig: hospData.guideHospConfig, // 医院是否有就诊指引tabBar菜单
        // 医保相关参数 start
        insuType: hospData.insuType,
        bizType: hospData.bizType,
        cityCode: hospData.cityCode,
        channel: hospData.channel,
        orgChnlCrtfCodg: hospData.orgChnlCrtfCodg,
        orgCodg: hospData.orgCodg,
        orgAppId: hospData.orgAppId,
        sourceapp: hospData.sourceapp,
        insuTestFlag: hospData.insuTestFlag
        // 医保相关参数 end
    });
	
	// 设置医保参数
	// Utils.setInsuStorage(hospOneData)
    
    app.globalData.tabBarSettings.guideHospConfig = hospData.guideHospConfig;
    app.globalData.SDKAPPID = +hospData.imAppID;
    app.globalData.SECRETKEY = hospData.imSecret;
}

// 检查医院列表数据是否已经存在
export function checkHospitalDataAlready(self) {
    let { checkHospitalCount } = self;
    return new Promise((resolve) => {
        const allHospitalData = Cache.get('allHospitalData');
        if (allHospitalData) {
            self.setData({
                checkHospitalCount: 10
            });
            resolve();
        } else {
            if (checkHospitalCount == -1) {
                uni.showToast({
                    title: '医院数据获取失败，请联系管理员'
                });
                return;
            }
            setTimeout(() => {
                checkHospitalDataAlready(self).then(() => {
                    resolve();
                });
                checkHospitalCount--;
                self.setData({
                    checkHospitalCount
                });
            }, 500);
        }
    });
}

// 切换就诊人
export function switchAdmPatient (admListData, hisPatID, self) {
  this.judgeWhetherThePatientExists(admListData, hisPatID).then(res => {
    const userData = Cache.get('userData')
    setTimeout(() => {
      self.setData({
        showPopup: false,
        admListData: res.admListData,
        selectedItem: userData
      })
    }, 200)
  })
}

// 获取就诊人下拉数据
export function getAdmSelectData(self) {
    return new Promise((resolve, reject) => {
        let data = {
            params: [{}]
        }
        $http.post("urlS", self, {
            code: "01030001",
            data: data,
            success: function(res) {
                if (+res.errorCode === 0) {
                    app.globalData.isUpdatePatList = false;
                    let admSelectData = res.result.rows && res.result.rows.length > 0 ? res.result.rows : [];
                    for (var i = 0; i < admSelectData.length; i++) {
                        admSelectData[i].value = admSelectData[i].patID;
                        admSelectData[i].key = i;
                    }
                    resolve(admSelectData)
                } else {
                    resolve(false)
                }
            },
            fail(err) {
                reject(err)
            }
        })
    })
}

/* 判断就诊人数据中是否包含storage中选中的数据
* @admListData: 就诊人列表数据
* @hisPatID:  患者ID
*/
export function judgeWhetherThePatientExists(admListData, hisPatID) {
  return new Promise((resolve) => {
    let userData = Cache.get('userData');
    let isExistence = false;
    let newData;
    if(hisPatID) {
      for (var i = 0; i < admListData.length; i++) {
        if (hisPatID && (admListData[i].hisPatID == hisPatID)) {
          isExistence = true;
          admListData[i].selected = true
          console.log(admListData[i])
          newData = admListData[i];
        } else {
          admListData[i].selected = false
        }
      }
    } else {
      if(admListData.length > 0) {
        isExistence = true;
        admListData[0].selected = true
        newData = admListData[0];
      }
    }
    if(newData) {
      resolve({admSelectedData: newData, admListData})
    }
    if (!isExistence) {
      Cache.set('userData', {
        ...userData,
        idCardNo: '',
        imUserID: '',
        patDesc: '',
        patID: '',
        hisPatNo: '',
        hisPatID: '',
        mobile: '',
        patValue: '',
        patSexDesc: '',
        medCardID: ''
      })
    } else {
      Cache.set('userData', {
        ...userData,
        idCardNo: newData.idCardNo || '',
        imUserID: newData.imUserID || '',
        patDesc: newData.patName || '',
        patID: newData.patID || '',
        hisPatNo: newData.hisPatNo || '',
        hisPatID: newData.hisPatID || '',
        mobile: newData.mobile || '',
        patValue: newData.key || '',
        patSexDesc: newData.patSexDesc || '',
        medCardID: newData.medCardID || ''
      });
    }
  })
}

///调接口获取科室列表
export function getLocList(self) {
    return new Promise((resolve, reject) => {
        const hisHospID = Cache.get('userData').hisHospID
        let data = {
            params: [{
                hospCode: hisHospID,
                imageFlag: "Y",
                videoFlag: "Y"
            }]
        }
        $http.post("urlS", self, {
            namespace: "Y",
            code: "03100219",
            data: data,
            success: function(res) {
                console.log(res)
                if (+res.errorCode === 0) {
                    var allLoc = [{
                        id: '',
                        descripts: "全部科室"
                    }]
                    resolve(allLoc.concat(res.data))
                } else {
                    resolve([])
                }
            },
            fail(err) {
                reject(err)
            }
        })
    })
}

// 页面loading处理,验证接口请求是否完成
export function loadCheckStatus(self) {
    return new Promise((resolve, reject) => {
        if (self.loads.indexOf(true) == -1) {
            uni.hideLoading()
            resolve(true)
        } else {
            setTimeout(() => {
                uni.hideLoading()
                resolve(true)
            }, 30e3)
        }
    })
}

// touch 事件 获取市场人员ID等
export function userScanTouch(recommendObj) {
  console.log('recommendObj', recommendObj)
  let data = {
    params: [{
      markPersonID: recommendObj?.marketerID,
      posterID: recommendObj?.poster_id,
      posterType: recommendObj?.poster_type
    }]
  }
  $http.post("urlS", self, {
    code: '01060001',
    data: data,
    success(res) {
      // console.log('01060001:', res)
    },
    error(err) {
      console.log('01060001 err：', err)
    }
  })
}

// 添加就诊人完成时，处理当前就诊人+openID绑定+市场人员绑定
export function bindMarketerPatient(self, hisPatID) {
    return new Promise((resolve, reject) => {
        const {
            activityObj
        } = app.globalData
        let data = {
            params: [{
                markPersonID: activityObj && activityObj.marketerID || '',
                hisPatID: hisPatID || ''
            }]
        }
        $http.post("urlS", self, {
            code: '01060002',
            data: data,
            success(res) {
                console.log('01060002 success', res)
                resolve()
            },
            error(err) {
                reject(err)
                console.log('01060002 error', err)
            }
        })
    })
}

// 添加切换就诊人时，处理当前就诊人和openID绑定
export function addOrSwitchPatient(self, visitPatID) {
    return new Promise((resolve, reject) => {
        let data = {
            params: [{
                visitPatID: visitPatID
            }]
        }
        $http.post("urlS", self, {
            code: '01060003',
            data: data,
            success(res) {
                console.log('01060003 success:', res)
                resolve()
            },
            error(err) {
                console.log('01060003 error:', err)
                reject()
            }
        })
    })
}

// 判断是否在当前医院有就诊记录
export function checkCurrentHospitalAdmRecord(self) {
    return new Promise((resolve, reject) => {
        $http.post("urlS", self, {
            code: '01060007',
            data: {},
            success(res) {
                console.log('01060007 success:', res)
                resolve(res)
            },
            error(err) {
                console.log('01060007 error:', err)
                reject()
            }
        })
    })
}

// 获取地球两个经纬度的距离，以米为单位
export function getDistanceInMeters(type, arr) {
  var R = type == 'km' ? 6371 : 6371000; // Radius of the earth in meters  
  var dLon = deg2rad((+arr[2]) - (+arr[0]));
  var dLat = deg2rad((+arr[3]) - (+arr[1])); // deg2rad below  
  var a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(+arr[0])) * Math.cos(deg2rad(+arr[2])) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var distance = R * c; // Distance in meters  
  // console.log('arr', arr)
  // console.log('两个点的距离', distance +'km')
  return distance;
}

export function deg2rad(deg) {
  return deg * (Math.PI / 180)
}

// 就近医院选择弹窗是否显示
export function nearHospitalModalOpen() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1  
  const day = String(date.getDate()).padStart(2, '0');
  const arr = [year, month, day]
  // console.log(arr)
  let timeMap = new Date(arr.join('/') + ' 23:59:59').getTime()
  this.$cache.set('isHospModal', timeMap)
}

// 获取视频权限
export function videoAuthorize() {
    return new Promise((resolve, reject) => {
        uni.authorize({
            scope: 'scope.camera',
            success() {
                resolve();
                console.log('用户已经同意小程序使用摄像头功能');
            },
            fail() {
                reject();
            }
        });
    });
}

// 获取录音权限
export function audioAuthorize() {
    return new Promise((resolve, reject) => {
        uni.authorize({
            scope: 'scope.record',
            success() {
                resolve();
                // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                console.log('用户已经同意小程序使用录音功能');
            },
            fail() {
                reject();
            }
        });
    });
}

// 登录
export function loginFun(self, globalData) {
  return new Promise((resolve, reject) => {
    uni.login({
      success(wxRes) {
        if (wxRes.code) {
          let code = wxRes.code
          const accountInfo = wx.getAccountInfoSync();
          let data = {
            params: [{
              code,
              appID: accountInfo.miniProgram.appId
            }]
          }
		  //#ifdef MP-ALIPAY
		  data.params[0]['userCode'] = 'alisf'
		  //#endif
          globalData.isLogin = true
          $http.post("urlS", self, {
            code: "01050001",
            data: data,
            success: function (res) {
              let newUserData = {};
              let userData = Cache.get('userData');
			  if (userData && userData.openid) delete userData.openid
			  // if (userData && userData.openID) return // 正式发布时，注释掉 
              if (+res.errorCode === 0) {
                newUserData = {
                	...userData,
                	openID: res.result.openid,
                	pubAccCode: res.result.minPrgCode,
                	session_key: res.result.session_key,
                	...(delete res.result.open_id, res.result)
                };
              } else {
                newUserData = {
                	...userData,
                	openID: "",
                	pubAccCode: "",
                	session_key: ""
                };
              }
              Cache.set('userData', {
                ...newUserData
              });
              resolve(res.result)
            },
            error() {
              reject()
            }
          });
        } else {
          uni.showModal({
            title: '提示',
            content: '微信登录code获取失败，请退出程序重新进入小程序。',
            showCancel: false,
            success (res) {
              if (res.confirm) {
                uni.exitMiniProgram();
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          reject()
        }
      },
      fail(err){
        uni.showModal({
          title: '提示',
          content: '微信登录失败，请退出程序重新进入小程序。',
          showCancel: false,
          success (res) {
            if (res.confirm) {
              uni.exitMiniProgram();
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  })
}

// 更新tabbar的Badge数据
export function updateTabBarBadge(app) {
  // 这个方法会通知当前 Tab 页去更新 TabBar
  // 注意：只有在 Tab 页面才能直接更新 TabBar
  // 如果当前不是 Tab 页面，切换到 Tab 页面时，其 onShow 方法会自动更新
  // #ifdef MP
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (typeof currentPage.getTabBar === 'function') {
    const { tabBarBadge: { messageCount, triageUnreadMessageCount }, tabBarVisiableHospital } = app.globalData.tabBarSettings
    const userData = Cache.get('userData')
    currentPage.getTabBar().setData({
      // 这里可以根据 globalData 更新 list
      'list[3].badge': messageCount > 99 ? '...' : messageCount > 0 ? messageCount : '',
      'list[1].visiable': userData && tabBarVisiableHospital.indexOf(userData.hisHospID) > -1,
      'list[1].badge': triageUnreadMessageCount > 99 ? '...' : triageUnreadMessageCount > 0 ? triageUnreadMessageCount : '',
    });
  }
  // #endif
}

//获取智能导诊未读消息
export function triageUnreadMessages(app) {
  return new Promise((resolve, reject) => {
    const userData = Cache.get('userData')
    if (!(userData && userData.hisPatID)) return;
    let data = {
      params: [{
        patID: userData.hisPatID || ""
      }]
    }
    $http.post("urlS", this, {
      code: "01010035",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          console.log('triageUnreadMessages === ', res)
          app.globalData.tabBarSettings.tabBarBadge.triageUnreadMessageCount = res.result
          resolve()
        } else {
          reject(res)
        }
      },
      fail(err) {
        reject(err)
      }
    });
  })
}

// 
export function getQQlxgh(latLng, toArr) {
  return new Promise((resolve, reject) => {
    const sig = qqMapSign('/ws/distance/v1/matrix', latLng, toArr.join(';'))
    uni.request({
      method: 'GET',
      url: '/ws/distance/v1/matrix',
      data: {
        mode: 'driving',
        key: httpConfig.qqmapKey,
        from: latLng,
        to: toArr.join(';'), // lat,lng 格式
        sig
      },
      success(res) {
        if (res.statusCode && res.data.status == 0) {
          resolve(res.data.result.rows)
        } else {
          reject(res)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

export function qqMapSign(url, from, to) {
  return CryptoJS.MD5(url + '?from=' + from + '&key=' + httpConfig.qqmapKey + '&mode=driving&to=' + to + httpConfig.qqmapSk).toString()
}
