/*
 * @Descripttion: zx
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: zx
 * @Date: 2021-11-11 10:37:59
 * @LastEditors: OBKoro1
 * @LastEditTime: 2022-01-22 23:14:13
 */
const app = getApp()
const newPage = require('../../../utils/newPage')
import { base64 } from '../../../utils/base64'

import {
  fhGetFamilyMembers,
  fhGetFamilyMembersDetail,
  fhGetPatientInfo,
  fhGetPatientRecord
} from '../../../api/remote/index'
import { creatUrl } from '../../../utils/util'
const dayjs = require('../../../src/js/dayjs/index')
const pageOptions = {
  // 页面数据
  data: {
    isFirstOnShow: true, // 是否为首次执行onShow
    radio: null,
    familyList: [],
    chooseFamily: 0,
    change: 1, // 修改标识
    showShare: false,
    id: 0,
    options: [
      { name: '二维码分享', icon: 'qrcode' },
      { name: '微信', icon: 'wechat', openType: 'share' },
      { name: '复制链接', icon: 'link' }
    ],
    isLoadingEnd: false
  },
  // 分享框
  shareFamily() {
    this.setData({ showShare: true })
  },
  onClose() {
    this.setData({ showShare: false })
  },
  onSelect(event) {
    if (event.detail.index === 0) {
      wx.navigateTo({
        url: `/remote/patient/QrShare/index`
      })
    } else if (event.detail.index === 1) {
      console.log('微信分享')
    } else {
      this.getUrl()
    }
    this.onClose()
  },
  // 获取分享的url
  async getUrl() {
    try {
      app.Loading('获取URL中...')
      const { memberId } = app?.globalData?.baseInfo
      const url = await creatUrl(
        '/pages/pages-patient/patient-login/patient-login',
        {
          rid: this.data.id
        }
      )
      app.hLoading()
      wx.setClipboardData({
        data: this.getShareText(this.patientInfo?.name || '', url)
      })
    } catch (e) {
      console.log('获取分享链接错误', e)
    }
  },
  // 单选框
  onChange(event) {
    console.log(event, 123)

    this.data.familyList.forEach(item => (item.checked = false))
    this.data.familyList[event.currentTarget.dataset.index].checked = true

    this.setData({
      familyList: this.data.familyList
    })
    wx.$setGlobalData('familyMemberId', event.target.dataset.id)
    wx.$setGlobalData(
      'familyMemberInfo',
      this.data.familyList[event.currentTarget.dataset.index]
    )

    if ([1, '1'].includes(this.data.chooseFamily)) {
      wx.navigateBack({
        delta: 1
      })
    }
  },
  // 获取患者详情
  async fhGetPatientInfo() {
    try {
      const { memberId } = app?.globalData?.baseInfo
      const { results } = await fhGetPatientInfo({}, memberId)
      this.patientInfo = results
      if (!results) {
        return Promise.reject()
      }
      return results
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 获取患者家属列表
  async fhGetFamilyMembers() {
    const form = []
    const memberId = app.globalData.baseInfo.memberId
    try {
      app.Loading('加载中...')
      const { results } = await fhGetFamilyMembers(form, memberId)
      results.results.forEach(
        item => (item.checked = item.id === +this.options.id)
      )
      app.hLoading()
      this.setData({
        familyList: results.results
      })
    } catch (e) {
      console.log('debug axios', e)
    }
    this.setData({
      isLoadingEnd: true
    })
  },
  // 获取患者家属详情
  async fhGetFamilyMembersDetail() {
    const form = []
    const memberId = app.globalData.baseInfo.memberId
    const familyMemberId = app.globalData.familyMemberId
    try {
      const { results } = await fhGetFamilyMembersDetail(
        form,
        memberId,
        familyMemberId
      )

      this.setData({
        form: results
      })
      wx.$setGlobalData('familyMemberInfo', results)
      this.editFlag = true
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  async getPatientRecord() {
    const form = []
    const memberId = app.globalData.baseInfo.memberId
    const hospitalId = app.globalData.hospitalInfo.hospitalId
    try {
      const { results } = await fhGetPatientRecord(form, memberId, hospitalId)
      this.setData({
        id: results.id
      })
      return results
    } catch (e) {
      return e
    }
  },
  // 新增家属
  toAddFamily() {
    if (this.data.familyList.length >= 10) {
      wx.showModal({
        title: '提示',
        content: '家属数最多同时存在10个，请删除后重新添加',
        showCancel: false
      })
      return
    }
    wx.navigateTo({
      url: '/remote/patientsMember/addMember/index'
    })
  },
  // 修改家属
  toChangeFamily(e) {
    wx.navigateTo({
      url: `/remote/patientsMember/addMember/index?id=${e.currentTarget.dataset.id}`
    })
  },
  // 获取分享文案
  getShareText(userName, shareUrl) {
    return `复制链接内容
    ${userName} 邀请您加入家属
    邀请人：${userName}
    邀请时间：${dayjs().format('YYYY/MM/DD')}
    
    点击链接进入家属邀请界面：
    ${shareUrl}`
  },
  // 页面载入时
  async onLoad(e) {
    this.options = e
    this.getPatientRecord()
  },
  // 页面初始化
  async init() {
    try {
      await this.fhGetPatientInfo()
      this.fhGetFamilyMembers()
      this.setData({
        chooseFamily: this.options.chooseFamily
      })
    } catch (error) {
      wx.showModal({
        title: '提示',
        content: '需要先完善个人信息',
        showCancel: false,
        success: ({ confirm }) => {
          if (confirm) {
            wx.redirectTo({
              url: '/pages/health-record/index'
            })
          }
        }
      })
    }
    wx.stopPullDownRefresh()
  },
  // 页面准备好时
  onReady() {},
  // 页面显示时
  async onShow() {
    const { isFirstOnShow } = this.data

    this.init()

    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false
      })
      return
    }
  },
  // 页面隐藏时
  onHide() {
    this.setData({
      radio: null
    })
  },
  // 页面卸载时
  onUnload() {},
  // 下拉页面时
  onPullDownRefresh() {
    this.init()
  },
  // 到达页面底部时
  onReachBottom() {},
  // 页面滚动时
  onPageScroll() {},
  // 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
  onShareAppMessage() {
    const title = app.globalData?.patientInfo?.name + '邀请你成为家属'
    const { memberId } = app?.globalData?.baseInfo
    const path = `/pages/pages-patient/patient-login/patient-login?scene=rid-${this.data.id}`
    // const path = `remote/family-member/info/index?scene=pmId-${memberId}_type-addFm`

    const imageUrl =
      'https://ybm-public.oss-cn-beijing.aliyuncs.com/image/banner.png'

    return {
      title,
      path,
      imageUrl
    }
  }
}

newPage(pageOptions)
