/*
 * @Descripttion:
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-11-26 09:44:09
 * @LastEditors: OBKoro1
 * @LastEditTime: 2022-01-23 14:06:26
 */
import {
  fhGetPatientInfo,
  fhGetFamilyMembersDetail,
  fhSaveFamilyMembers,
  fhGetPatientIdRecord
} from '../../../api/remote/index'
import { relationArr } from '../../../utils/enumMap'
import { sceneDecode } from '../../../utils/util'
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog'
const pageOptions = {
  // 页面数据
  data: {
    isFirstOnShow: true, // 是否为首次执行onShow
    // 当前用户是否需要提示
    needTip: true,
    steps: [
      {
        desc: '确认患者关系'
      },
      {
        desc: '填写家属信息'
      }
    ],
    stepIndex: 1,
    // 表单数据
    formData: {
      // 与患者的关系
      relation: null
    },
    show: false,
    // 家属与患者关系
    columns: relationArr,
    // 患者信息
    patientInfo: {},
    bedNumber: '',
    addressDetails: ''
  },
  // 页面载入时
  onLoad(e) {
    this.load(e)
    const hospitalInfo = wx.getStorageSync('hospital-info')
    this.setData({
      bedNumber: hospitalInfo.bedNumber
    })
  },

  async load(e) {
    const scene = typeof e === 'string' ? e : e?.scene || ''
    const obj = sceneDecode(scene)
    const { rid, pmId } = obj
    this.pageIntoParameter = obj
    let memberId
    if (rid) {
      const data = await fhGetPatientIdRecord(rid)
      this.setData({
        addressDetails: data.results.sickArea + data.results.bedNumber
      })
      memberId = data.results.memberId
    } else {
      memberId = pmId
    }
    const { results } = await fhGetPatientInfo({}, memberId)
    this.setData({
      memberId,
      patientInfo: results
    })
  },

  // 页面准备好时
  onReady() {
    // 获取表单实例
    this.InfoForm = this.selectComponent('#info-form')
    this.init()
  },
  // 页面显示时
  onShow() {
    const { isFirstOnShow } = this.data

    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false
      })
      return
    }
  },
  // 页面隐藏时
  onHide() {},
  // 页面卸载时
  onUnload() {},
  // 下拉页面时
  onPullDownRefresh() {},
  // 到达页面底部时
  onReachBottom() {},
  // 页面滚动时
  onPageScroll() {},
  // 获取当前用户的memberId
  getFamilyMemberId() {
    return getApp().globalData?.baseInfo?.memberId || null
  },
  // 进入页面获取相关信息
  // 页面初始化
  async init() {
    if (getApp().globalData.patientInfo) {
      this.InfoForm.updateForm(getApp().globalData.patientInfo)
    }
    try {
      let familyMemberId = this.getFamilyMemberId()
      // 用户没有授权
      if (!familyMemberId) {
        this.needAuth = true
        await this.certificationPrompt()
        familyMemberId = this.getFamilyMemberId()
      } else {
        this.needAuth = false
      }

      // 这个接口只是判断用户是否与当前分享的患者绑定关系
      const { pmId } = this.pageIntoParameter || {}
      const { results: fpInfo } =
        (await this.getFamilyMembersDetail(pmId)) || {}
      wx.hideToast()
      if (!fpInfo) {
        await this.certificationPrompt()
      }

      this.setData({
        needTip: false,
        patientInfo: results
      })
    } catch (e) {}
  },
  // 获取患者家属信息
  async getFamilyMembersDetail(patientId) {
    try {
      const familyMemberId = this.getFamilyMemberId()
      const { resulst } = await fhGetFamilyMembersDetail(
        {},
        patientId,
        familyMemberId
      )
      console.log('debug', resulst)
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 未认证提示
  // certificationPrompt() {
  //   return new Promise((resolve, reject) => {
  //     Dialog.confirm({
  //       title: '认证提醒',
  //       message:
  //         '为了保证患者就医安安全，维护医院正常医疗秩序，按国家网络安全要求，所有患者及家属必须进行实名认证。',
  //       showCancelButton: false,
  //       beforeClose: action => this.confirm(action, resolve, reject)
  //     })
  //   })
  // },
  // 用户点击认证提醒弹窗的确认按钮
  /**
   *
   * @param {String} action 当前用户点击弹窗的时间，confirm代表确认
   * @param {Promise} dResolve 弹窗的Promise的resolve
   * @param {Promise} dReject 弹窗的Promise的dReject
   */
  confirm(action, dResolve, dReject) {
    return new Promise(resolve => {
      if (action === 'confirm') {
        if (this.needAuth) {
          wx.navigateTo({
            url: '/pages/authorization/authorization'
          })
          // dResolve(true);
          // resolve(true);
        } else {
          this.setData({
            needTip: false
          })
          dResolve(true)
          resolve(true)
        }
      }
    })
  },
  // 显示选择关系弹窗
  showPopup() {
    this.setData({ show: true })
  },
  // 关闭选择关系弹窗
  onClose() {
    this.setData({ show: false })
  },
  // 修改关系
  confirmRelation({ detail: { value } }) {
    this.setData(
      {
        'formData.relation': value
      },
      this.onClose
    )
  },
  // 下一步
  nextStep() {
    const { stepIndex, steps } = this.data

    // 保存
    if (stepIndex === steps.length) {
      this.saveFamilyMembers()
      return
    }

    this.setData({
      stepIndex: stepIndex + 1
    })
  },
  // 保存家属
  async saveFamilyMembers() {
    try {
      const form = this.InfoForm.validateForm()
      if (!form) {
        return
      }
      const familyMemberId = this.getFamilyMemberId()
      await fhSaveFamilyMembers(
        { ...this.data.formData, ...form, familyMemberId },
        this.data.memberId
      )
      wx.showTabBar({ icon: 'none', title: '保存成功～' })
      wx.reLaunch({
        url: '/remote/my-remote-visitation/index'
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  }
}

Page(pageOptions)
