/*
 * @Descripttion: zx
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: zx
 * @Date: 2021-11-16 11:14:12
 * @LastEditors: OBKoro1
 * @LastEditTime: 2022-01-23 17:06:06
 */
const { visitStateEnumeration } = require('../../../utils/enumMap.js')
const dayjs = require('../../../src/js/dayjs/index')
const NewPage = require('../../../utils/newPage')
const app = getApp()
import {
  fhGetPatientInfo,
  fhSaveRemoteVisits,
  fhChangeRemoteVisits,
  fhGetRemoteVisitsDetail,
  fhGetFamilyMembers,
  fhGetPatientRecord
} from '../../../api/remote/index'
import { creatUrl, sceneDecode } from '../../../utils/util'
const pageOptions = {
  // 页面数据
  data: {
    isNotEidt: false,
    loading: true,
    btnLoading: false,
    visitStartTime: dayjs().format('YYYY-MM-DD'),
    dayjs,
    visitStateEnumeration,
    show: false, // 出示二维码
    showState: false, // 跟踪状态
    isFirstOnShow: true, // 是否为首次执行onShow
    patientInfo: {}, // 患者信息
    familyMemberInfo: null, // 家属信息
    chooseFamily: 1, // 选择家属
    id: null, // 房间id
    addressDetail: null,
    form: {},
    changeForm: null,
    doctorName: null, // 医生名
    active: 0, // 1:申请提交
    stepIndex: 1,
    steps: [
      {
        desc: '申请探视'
      },
      {
        desc: '医生确认'
      },
      {
        desc: '准备探视'
      },
      {
        desc: '完成探视'
      }
    ],
    visitState: null, // 状态
    time: '2021-02-03',
    step: [
      {
        text: '申请已提交'
      },
      {
        text: '医生已扫码'
      },
      {
        text: '医生已确认',
        desc: ''
      },
      {
        text: '医生修改申请',
        desc: '描述信息'
      },
      {
        text: '远程探视开始'
      },
      {
        text: '远程探视已完结'
      }
    ],
    list: [
      { time: '11月02日  11:11' },
      { time: '11月02日  11:11' },
      { time: '11月02日  11:11' },
      { time: '11月02日  11:11' },
      { time: '11月02日  11:11' },
      { time: '11月02日  11:11' }
    ],
    showRemoteShare: false,
    remoteShareOptions: [
      { name: '微信', icon: 'wechat', openType: 'share' },
      { name: '复制链接', icon: 'link' }
    ],

    disabledText: false,
    isNotCanEnterRoom: true,
    visitEndTime: dayjs(dayjs().valueOf() + 86400000 * 7).format('YYYY-MM-DD')
  },
  // 选择家属跳转
  toFamily() {
    if (!['END'].includes(this.data.visitState) && !this.data.form.familyName) {
      wx.navigateTo({
        url: `/remote/patientsMember/management/index?chooseFamily=${
          this.data.chooseFamily
        }&id=${
          app.globalData.familyMemberInfo
            ? app.globalData.familyMemberInfo.id
            : ''
        }`
      })
    }
  },
  // 出示二维码
  showCode() {
    this.setData({ show: true })
  },
  // 状态跟踪
  showState() {
    this.setData({ showState: true })
  },
  // 关闭二维码弹框
  close() {
    this.setData({ show: false, showState: false })
  },
  // 获取患者详情
  async fhGetPatientInfo() {
    const form = []
    const memberId = app.globalData.baseInfo.memberId
    try {
      const { results } = await fhGetPatientInfo(form, memberId)
      this.setData({
        patientInfo: results
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 预约远程探视
  async saveRemoteVisits() {
    const { form } = this.data
    if (!app.globalData.familyMemberInfo) {
      wx.showToast({ title: '请先选择家属～', icon: 'none' })
      return
    }
    if (this.data.btnLoading) {
      return
    }
    if (!form.visitDate) {
      wx.showToast({ title: '请先选择远程探视日期～', icon: 'none' })
      return
    }
    this.setData({ btnLoading: true })
    // const {bedNumber: bedName, } = app.globalData.hospitalInfo
    form.patientSex = app.globalData.patientInfo.sex
    form.bedName = app.globalData.hospitalInfo.bedNumber
    const sickroomId = app.globalData.hospitalInfo.sickroomId
    const hospitalId = app.globalData.hospitalInfo.hospitalId
    form.familyName = app.globalData.familyMemberInfo.familyMemberName
    form.hospitalName = this.data.patientInfo.lastHospitalName
    form.inHospitalNumber = parseInt(this.data.patientInfo.lastHospitalId)
    form.patientName = this.data.patientInfo.name
    form.patientBirthday = this.data.patientInfo.birthday
    form.patientPhoneNumber = this.data.patientInfo.phone
    form.sickroomName = this.data.patientInfo.lastSickroomName
    const patientRemoveList = {}
    const familyRemoveList = {}
    form.remoteVisitMemberDTOList = []
    patientRemoveList.memberId = app.globalData.baseInfo.memberId
    patientRemoveList.memberName = this.data.patientInfo.name
    patientRemoveList.memberPhoneNumber = this.data.patientInfo.phone
    patientRemoveList.memberType = 'PATIENT'
    familyRemoveList.memberId = app.globalData.familyMemberInfo.familyMemberId
    familyRemoveList.memberName =
      app.globalData.familyMemberInfo.familyMemberName
    familyRemoveList.memberPhoneNumber =
      app.globalData.familyMemberInfo.familyMemberPhone
    familyRemoveList.memberType = 'FAMILY_MEMBER'
    form.remoteVisitMemberDTOList.push(patientRemoveList)
    form.remoteVisitMemberDTOList.push(familyRemoveList)
    try {
      const { results } = await fhSaveRemoteVisits(form, hospitalId, sickroomId)
      this.setData({
        form: {},
        active: 1,
        id: results.id
      })
      this.options.id = results.id
      this.getRemoteVisitsDetail(results.id)
    } catch (e) {
      console.log('debug axios', e)
    }
    this.setData({ btnLoading: false })
  },
  async changeRemoteVisits() {
    if (!this.data.form.familyName && !app.globalData.familyMemberInfo) {
      wx.showToast({ title: '请先选择家属～', icon: 'none' })
      return
    }
    if (this.data.btnLoading) {
      return
    }
    wx.showLoading({ title: '保存中...' })
    this.setData({ btnLoading: true })
    try {
      const { results } = await fhChangeRemoteVisits(
        this.options.id,
        app.globalData?.baseInfo?.memberId,
        {
          ...this.data.form,
          ...(this.data.changeForm ? this.data.changeForm : {}),
          remoteVisitMemberDTOList: app.globalData.familyMemberInfo
            ? [
                {
                  memberId: app.globalData.familyMemberInfo.familyMemberId,
                  memberName: app.globalData.familyMemberInfo.familyMemberName,
                  memberPhoneNumber:
                    app.globalData.familyMemberInfo.familyMemberPhone,
                  memberType: 'FAMILY_MEMBER'
                }
              ]
            : []
        }
      )
      wx.showToast({ icon: 'none', title: '修改成功～' })
      this.setData({
        form: {},
        changeForm: null,
        id: results.id
      })
      this.getRemoteVisitsDetail(results.id)
      console.log(results)
    } catch (error) {
      wx.hideLoading()
      console.log(error)
    }
    this.setData({ btnLoading: false })
  },
  // 远程探视详情
  async getRemoteVisitsDetail(id) {
    try {
      app.Loading('获取远程探视详情中...')
      const { results } = await fhGetRemoteVisitsDetail(id)
      results.start = {
        date: dayjs(results.visitStartTime).format('YYYY年MM月DD日'),
        time: dayjs(results.visitStartTime).format('HH:mm')
      }
      results.end = {
        date: dayjs(results.visitEndTime).format('YYYY年MM月DD日'),
        time: dayjs(results.visitEndTime).format('HH:mm')
      }
      // wx.$setGlobalData('patientInfo', results)

      const memberId = app.globalData?.baseInfo?.memberId
      const { remoteVisitMemberDTOList } = results || {}
      const currMember = remoteVisitMemberDTOList.filter(
        i => i.memberId === memberId
      )
      const { memberType = 'FAMILY_MEMBER' } = currMember?.[0] || {}
      this.memberType = memberType

      results.remoteVisitStatusDTOList.forEach(item => {
        item.remoteUpdateTime = dayjs(item.remoteUpdateTime).format(
          'MM月DD日 HH:mm'
        )

        if (item.visitStartTime && item.visitEndTime) {
          item.visitStartTime = dayjs(item.visitStartTime).format('YYYY-MM-DD')

          item.timeInterval = `${dayjs(item.visitStartTime).format(
            'HH:mm'
          )}~${dayjs(item.visitEndTime).format('HH:mm ')}`
        }
      })

      if (results.visitState === 'TO_BE_CONFIRM') {
        this.setData({
          active: 1
        })
      }

      if (results.visitState === 'CONFIRM_DOING') {
        this.setData({
          active: 2,
          stepIndex: 2
        })
      }

      if (['TO_BE_START', 'DOING'].includes(results.visitState)) {
        const toBeStartTimes =
          dayjs(results.visitStartTime).valueOf() - dayjs().valueOf()
        this.setData({
          stepIndex: 4,
          active: 3,
          isNotCanEnterRoom: !(toBeStartTimes < 5 * 60 * 1000)
        })
      }

      if (['END'].includes(results.visitState)) {
        this.setData({
          active: 5,
          stepIndex: 5
        })
      }

      if (['FAILURE'].includes(results.visitState)) {
        this.setData({
          active: 6,
          stepIndex: 5
        })
      }

      app.hLoading()

      if (
        !results.remoteVisitMemberDTOList
          .map(item => item.memberId)
          .includes(app.globalData.baseInfo.memberId)
      ) {
        wx.showModal({
          title: '提示',
          content:
            '暂无权限加入该远程探视，请到我的-我的远程探视，关注属于您的远程探视！',
          showCancel: false,
          confirmText: '确定',
          success: ({ confirm }) => {
            if (confirm) {
              wx.switchTab({
                url: '/pages/home/index'
              })
            }
          }
        })
        return
      }

      if (
        !results.familyName &&
        !this.data.familyMemberInfo &&
        results.visitState !== 'END'
      ) {
        wx.showModal({
          title: '提示',
          content:
            '您的远程探视还未邀请家属参与，请选择或新增家属参与远程探视。',
          showCancel: false,
          success: ({ confirm }) => {
            if (confirm) {
              this.toFamily()
            }
          }
        })
      }

      this.setData({
        loading: false
      })

      this.setData({
        form: results,
        isNotEidt: [
          'TO_BE_START',
          'DOING',
          'END',
          'CONFIRM_DOING',
          'CONFIRM',
          'FAILURE'
        ].includes(results.visitState),
        step: results.remoteVisitStatusDTOList.map(item => ({
          text: item.remoteDescription,
          time: item.remoteUpdateTime,
          desc:
            item.visitStartTime && item.visitEndTime
              ? `远程探视时间:${item.visitStartTime}～${item.visitEndTime}`
              : ''
        })),
        visitState: results.visitState,
        visitEndTime: results.updateMaxDate
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 输入
  onInputChange({ currentTarget: { dataset }, detail }) {
    console.log({ currentTarget: { dataset }, detail })
    const { key, formKey = 'form' } = dataset
    let { value } = detail
    if (key === 'sex') value = +value
    if (this.data.form.id) {
      this.setData(
        {
          changeForm: {}
        },
        () => {
          this.setData({
            [`changeForm.${key}`]: typeof detail === 'string' ? detail : value
          })
        }
      )
    } else {
      this.setData({
        [`${formKey}.${key}`]: typeof detail === 'string' ? detail : value
      })
    }
    console.log(this.data.form)
  },
  // 进入远程探视房间
  joinFamilyRoom() {
    if (this.data.isNotCanEnterRoom) {
      return
    }
    if (!this.data.form.familyName) {
      wx.showModal({
        title: '提示',
        content: '您的远程探视还未邀请家属参与，请选择或新增家属参与远程探视。',
        showCancel: false
      })
      return
    }
    // const url = `/remote/room/room?roomID=${app.globalData.id}&userID=${app.globalData.familyMemberId}&template=grid&memberType=${this.memberType}`
    this.checkDeviceAuthorize()
      .then(result => {
        wx.navigateTo({
          url: `/remote/entrance/index?id=${this.data.id}&memberType=${this.memberType}&template=grid`
        })
      })
      .catch(error => {
        console.log('没有授权', error)
      })
  },
  checkDeviceAuthorize: function () {
    this.hasOpenDeviceAuthorizeModal = false
    return new Promise((resolve, reject) => {
      if (!wx.getSetting || !wx.getSetting()) {
        // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
        resolve()
      }
      wx.getSetting().then(result => {
        console.log('getSetting', result)
        this.authorizeMic = result.authSetting['scope.record']
        this.authorizeCamera = result.authSetting['scope.camera']
        if (
          result.authSetting['scope.camera'] &&
          result.authSetting['scope.record']
        ) {
          // 授权成功
          resolve()
        } else {
          // 没有授权，弹出授权窗口
          // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
          console.log('getSetting 没有授权，弹出授权窗口', result)
          wx.authorize({
            scope: 'scope.record'
          })
            .then(res => {
              console.log('authorize mic', res)
              this.authorizeMic = true
              if (this.authorizeCamera) {
                resolve()
              }
            })
            .catch(error => {
              console.log('authorize mic error', error)
              this.authorizeMic = false
            })
          wx.authorize({
            scope: 'scope.camera'
          })
            .then(res => {
              console.log('authorize camera', res)
              this.authorizeCamera = true
              if (this.authorizeMic) {
                resolve()
              } else {
                this.openConfirm()
                reject(new Error('authorize fail'))
              }
            })
            .catch(error => {
              console.log('authorize camera error', error)
              this.authorizeCamera = false
              this.openConfirm()
              reject(new Error('authorize fail'))
            })
        }
      })
    })
  },
  // 探视申请

  // 页面载入时
  onLoad(e) {
    const scene = typeof e === 'string' ? e : e?.scene || ''
    const obj = sceneDecode(scene)
    this.options = {
      ...e,
      ...obj
    }
    const { id } = this.options

    if (id) {
      this.getRemoteVisitsDetail(id)
    } else {
      this.fhGetFamilyMembers()
      this.setData({
        loading: false
      })
    }
    this.fhGetPatientRecord()

    this.fhGetPatientInfo()
    this.setData({
      id
    })
  },
  async fhGetPatientRecord() {
    const form = []
    const memberId = app.getMemberId()
    const hospitalId = app.globalData.hospitalInfo.hospitalId
    try {
      const { results } = await fhGetPatientRecord(form, memberId, hospitalId)
      this.setData({
        addressDetail: results.sickArea + results.bedNumber
      })
    } 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)
      const defaultStatusData = results.results.find(item => item.defaultStatus)
      if (defaultStatusData) {
        this.setData({
          familyMemberInfo: defaultStatusData
        })
        app.globalData.familyMemberInfo = defaultStatusData
      }
    } catch (e) {
      console.log('debug axios', e)
    }
    app.hLoading()
  },
  onShareRemote() {
    this.setData({
      showRemoteShare: true
    })
  },
  onSelectRemoteShare(e) {
    if (e.detail.index === 1) {
      this.getUrl()
    }
    console.log(e)
  },
  // 获取分享的url
  async getUrl() {
    try {
      app.Loading('获取URL中...')
      const url = await creatUrl('remote/patient/visitApplication/index', {
        id: this.options.id
      })
      app.hLoading()
      wx.setClipboardData({
        data: this.getShareText(
          app.globalData.patientInfo.patientName || '',
          url
        ),
        success: () => {
          wx.showToast({ icon: 'none', title: '复制成功' })
          this.setData({
            showRemoteShare: false
          })
        }
      })
    } catch (e) {
      console.log('获取分享链接错误', e)
    }
  },
  // 获取分享文案
  getShareText(userName, shareUrl) {
    return `复制链接内容
    ${userName} 邀请您加入远程探视
    邀请人：${userName}
    邀请时间：${dayjs().format('YYYY/MM/DD')}
    
    点击链接进入家属邀请界面：
    ${shareUrl}`
  },
  onCloseRemoteShare() {
    this.setData({
      showRemoteShare: false
    })
  },
  onOpenArea() {
    this.setData({
      disabledText: false
    })
  },
  onCloseArea() {
    this.setData({
      disabledText: true
    })
  },
  // 页面准备好时
  onReady() {},
  // 页面显示时
  onShow() {
    const { isFirstOnShow } = this.data
    // if (this.data.stepIndex === 2) {
    //   this.getRemoteVisitsDetail();
    // }
    if (!app.globalData?.baseInfo?.memberId) {
      wx.navigateTo({
        url: '/pages/authorization/authorization'
      })
      return
    }

    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false
      })
      return
    }
    if (this.options.id) {
      this.getRemoteVisitsDetail(this.options.id)
    }
    if (app.globalData.familyMemberInfo) {
      this.setData(
        {
          familyMemberInfo: app.globalData.familyMemberInfo
        },
        () => {
          if (this.data.form.id) {
            this.changeRemoteVisits()
          }
        }
      )
      if (Object.keys(this.data.form).length) {
        this.setData({
          changeForm: {
            ...(this.data.changeForm || {})
          }
        })
      }
    }
  },
  // 页面隐藏时
  onHide() {},
  // 页面卸载时
  onUnload() {
    app.globalData.familyMemberInfo = null
  },
  // 下拉页面时
  onPullDownRefresh() {},
  // 到达页面底部时
  onReachBottom() {},
  // 页面滚动时
  onPageScroll() {},
  // 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
  onShareAppMessage() {
    return {
      title: `${app.globalData.patientInfo.cName}邀请您参加远程探视`,
      path: `/remote/patient/visitApplication/index?id=${this.options.id}&scene=id-${this.options.id}`,
      imageUrl: ''
    }
  }
}

NewPage(pageOptions)
