import { fhGetBanners, fhGetAnnouncements } from '../../api/actives/index'
import { fhGetArticleCategories, fhGetArticles } from '../../api/hospital/index'
import {
  fhGetRemoteVisitsList,
  fhGetRemoteVisitsSetting
} from '../../api/remote/index'
import { fhGetnewbornSettings } from '../../api/newborn/index'
import { __FAIL_FN } from '../../utils/network'
const baseUrl = require('../../api/index.js').config
const masses = require('../../api/masses.js')
const app = getApp()
const { watch, Loading, hLoading, bus } = app
import {
  fhIsVerityPatientVerty,
  fhHospitalSet,
  fhPatientVerty,
} from '../../api/sign/index'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    franchiseId: 101,
    hospitalId: 1,
    adArr: [],
    noticeData: [],
    articleType: [],
    hosiptalName: '',
    articleTypeId: 0,
    articleData: [],
    loading: true,
    // 查询条件
    query: {
      pageSize: 10,
      pageNumber: 1
    },
    remoteVisitsList: [], //进行时的远程探视
    // 远程探视设置
    remoteSetting: null,
    // 新生儿探视设置
    newbornSettings:null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    bus.on('loadHospitalInfoEnd', this.initPatientInfo.bind(this))
    wx.removeStorageSync('tempPatientInfo')
  },
  onShow() {
    if(app.globalData.baseInfo !== null){
      if (app.globalData.baseInfo.memberId) {
        setTimeout(() => { 
          this.handleAuthedIdent();
          if(!wx.getStorageSync('hospitalFlag')) this.getRemoteVisitsList()
        }, 1000)
      }
    }
  },
  onReady() {
    watch('patientInfo', this.initPatientInfo.bind(this))
  },
  // 下拉页面时
  onPullDownRefresh() {
    this.initPatientInfo()
  },
  /**广告列表 */
  async getAds() {
    try {
      const { results } = await fhGetBanners({ type: 1 })
      this.setData({
        adArr: results
      })
    } catch (e) {
      console.error('获取轮播图 error:', e)
    }
  },
  enterRoom() {
    wx.navigateTo({
      url: `/remote/patient/visitApplication/index?id=${this.data.remoteVisitsList[0].id}`
    })
  },
  /**获取公告 */
  async getNotice() {
    try {
      const { results } = await fhGetAnnouncements()
      this.setData({ noticeData: results || [] })
    } catch (e) {
      console.error('获取公告错误 error:', e)
    }
  },
  /**首页文章分类 */
  async getArticleTitle() {
    try {
      const { results } = await fhGetArticleCategories()
      this.setData({ articleType: results || [] })
      if (results.length > 0) {
        const { id } = results[0]
        this.setData({
          articleTypeId: id
        })
        this.getArticleList(id)
      } else {
        wx.stopPullDownRefresh()
        this.setData({
          loading: false
        })
      }
    } catch (e) {
      console.error('获取文章分类 error:', e)
      wx.stopPullDownRefresh()
      this.setData({
        loading: false
      })
    }
  },
  /**切换文章分类 */
  articleTypeClick({ currentTarget: { dataset } }) {
    const { id } = dataset
    this.setData(
      {
        query: {
          pageSize: 10,
          pageNumber: 1
        },
        articleTypeId: id
      },
      () => {
        this.getArticleList(id)
      }
    )
  },
  /**文章列表*/
  async getArticleList(id) {
    try {
      !this.data.loading && Loading()
      const {
        results: { results }
      } = await fhGetArticles({
        articleCategoryId: id,
        ...this.data.query
      })
      this.setData({ articleData: results })
    } catch (e) {
      console.error('获取文章 error:', e)
    }
    wx.stopPullDownRefresh()
    hLoading()
    this.setData({
      loading: false
    })
  },
  // 检验是否授权
  verifyAuth() {
    return new Promise((resolve, reject) => {
      const ifAuth = wx.getStorageSync('anflag')
      if (ifAuth) {
        wx.$routerTo('/pages/authorization/authorization')
        reject('未登录')
      } else {
        resolve()
      }
    })
  },
  async mainNavClick({ currentTarget: { dataset } }) {
    try {
      if (!wx.getStorageInfoSync().keys.includes('anflag')) {
        return
      }
      await this.verifyAuth()
      let { path, type } = dataset
      const isIcon = wx.getStorageSync('hospitalFlag')
      console.log(isIcon, 'isIcon')
      
      if (isIcon) {
        if(path){
          if(path.includes('newBorn')){
            wx.reLaunch({
              url: path
            })
          }else{
            wx.showToast({
              title: '请使用微信扫码病床上的医便民服务二维码',
              icon: 'none'
            })
          }
        }else{
          wx.showToast({
            title: '此功能正在升级中，敬请期待',
            icon: 'none'
          })
        }
        return
      } else{
        if (path) {
          if (type === 'nurse' && !getApp().globalData.patientInfo.name) {
            path =
              '/pages/health-record/index?from=home&nextPath=%2Fnurse%2Fpages%2Fappointment%2Findex'
          }
          wx.reLaunch({
            url: path
          })
        } else {
          wx.showToast({
            title: '此功能正在升级中，敬请期待',
            icon: 'none'
          })
        }
      }
    } catch (e) {}
  },
  // 跳转到文章详情页
  nav({ currentTarget: { dataset } }) {
    const { path, id } = dataset
    wx.$routerTo({
      url: path,
      query: {
        id
      }
    })
  },
  // 监听获取患者档案是否完成
  async initPatientInfo() {
    Promise.all([this.getAds(), this.getNotice(), this.getArticleTitle(), this.feathGetHosptalSet(),this.getnewbornSettings()])
    // await this.getAds()
    // await this.getNotice()
    // await this.getArticleTitle()
    // await this.feathGetHosptalSet()
    // await this.getnewbornSettings()
    wx.getStorageSync('hospitalFlag')?   null:await this.getRemoteVisitsSetting()
    this.setData({
      loading: false,
      hosiptalName: wx.getStorageSync('exactaddress')
    })
  },
   // 重新选择医院病床
  selectHosiptal() {
    wx.navigateTo({
      url: '/store/pages/hospital/index'
    })
  },
  // 轮播图跳转
  async bannerNav({ currentTarget: { dataset } }) {
    try {
      await this.verifyAuth()
      const { type, jumpcontext } = dataset
      if (type == 1) {
        this.takeMerchantid(jumpcontext)
        wx.setStorageSync('noid', 'disagree')
      } else if (type == 2) {
        ;/^\//.test(jumpcontext) &&
          wx.navigateTo({
            url: jumpcontext
          })
      }
    } catch (e) {}
  },

  takeMerchantid(merchantid, foodid, skuid) {
    var that = this
    const lat = wx.getStorageSync('latitude')
    const lon = wx.getStorageSync('longitude')
    masses.getMerchantid(
      baseUrl.waimaiUrl + '/merchants/' + merchantid,
      {
        lat: lat,
        lon: lon
      },
      {},
      '加载中',
      function (res) {
        var result = res.results
        if (result != null) {
          that.setData({
            salesroomid: result
          })
          wx.setStorageSync('storeid', result)
          wx.setStorageSync('merchantid', merchantid)
          wx.navigateTo({
            url: '/store/pages/lunch/index?foodid=' + foodid + '&skuid=' + skuid
          })
        } else {
        }
      },
      function (err) {
        __FAIL_FN({
          res: err
        })
      }
    )
  },

  //获取列表信息
  async getRemoteVisitsList() {
    const form = {}
    form.memberType = 'PATIENT'
    form.pageNumber = 1
    form.pageSize = 1
    form.visitStateList = 'DOING'
    const memberId = app.globalData.baseInfo.memberId
    try {
      const { results } = await fhGetRemoteVisitsList(memberId, form)

      this.setData({
        remoteVisitsList: results.results
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 获取医院远程探视的配置
  async getRemoteVisitsSetting() {
    try {
      const { hospitalId, sickroomId } = getApp().globalData.hospitalInfo
      const { results } = await fhGetRemoteVisitsSetting(hospitalId, sickroomId)
      getApp().globalData.remoteSetting = results
      this.setData({
        remoteSetting: results
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  },

  // 获取医院新生儿探视的配置
  async getnewbornSettings() {
    try {
      const hospitalInfo= wx.getStorageSync('hospital-info')
      console.log(hospitalInfo, 'hospitalInfo123')
      const { results } = await fhGetnewbornSettings(hospitalInfo.hospitalId)
      console.log(results,'.🤣🤣🤣');
      // 医院端和平台端的新生儿开关
      if(results.hospitalBabyVisitSwitch && results.platformBabyVisitSwitch) {
        getApp().globalData.newbornSetting = results
        console.log(getApp().globalData.newbornSetting, 'getApp().globalData.newbornSettings')
        this.setData({
        newbornSettings: results
      })
      }else{
        getApp().globalData.newbornSetting = null
        this.setData({
        newbornSettings: null
      })
      }
    } catch (e) {
      console.log('debug axios', e)
    }
  },

  
  /***
   * 患者是否认证过
   */
   async handleAuthedIdent(){
    try{
      const memberId = getApp().globalData.baseInfo.memberId
      // const anflag = wx.getStorageSync('anflag')
      // 如果有患者id，才能进行验证实名认证
      const patientInfo = getApp().globalData.patientInfo
      if(patientInfo.id !== null){
        const params ={
          patientId:memberId
        }
        const {results} = await fhIsVerityPatientVerty(params);
        wx.setStorageSync('authedFlag',results.flag)
      }
    }catch(e){
      wx.setStorageSync('authedFlag',false)
      console.log(e)
    }
  },
  /**
   * 获取医院相关设置
   */
  async feathGetHosptalSet(){
    try{
      const { hospitalId } = wx.getStorageSync('hospital-info')
      if (hospitalId) {
        const {results} = await fhHospitalSet(hospitalId);
      getApp().globalData.advanceTime = results.advanceTime
      console.log(results)
      }
    }catch(e){
      console.error(e,'error')
    }
  }
})
