<template>
  <view class="detail">
    <view class="details-step">
      <u-steps mode="number" :list="stepList" :current="stepCurrent" />
    </view>
    <view class="line" />
    <!-- 表单内容 -->
    <Contents :select-time="selectTime" :disable="disable" :details="details" :rule="rule" @on-open-status="statusVisible = true" @submitFrom="submitFrom" @cancelVisit="cancelVisit" />
    <!-- 状态变更历史 -->
    <status-list v-model="statusVisible" :details="details" />
  </view>
</template>

<script>
import { fhGetVisitDetails, fhCreateVisit, fhPutModifyVisit, fhGetRules, fhGetnewbornSettings } from '../../../../mainWeixinMp/api/newborn/index'

import dayjs from 'dayjs'
import Contents from './components/contents.vue'
import StatusList from './components/status-list.vue'
import { setEnableBtnTimer } from './business'
export default {
  components: {
    Contents,
    StatusList
  },
  data() {
    return {
      settgins: {},
      stepList: [
        {
          name: '申请探视'
        },
        {
          name: '医生确认'
        },
        {
          name: '准备探视'
        },
        {
          name: '完成探视'
        }
      ], // 步骤条
      selectTime: null, // 预约时间
      details: null, // 探视详情数据
      disable: false, // 修改的禁用
      id: null, // 探视记录的id
      statusVisible: false, // 状态跟踪的显示
      familyName: null, // 家属姓名
      rule: null // 规则
    }
  },
  computed: {
    stepCurrent() {
      if (this.details) {
        if (this.details.visitState === 'TO_BE_CONFIRM') {
          return 0
        }
        if (this.details.visitState === 'CONFIRM_DOING') {
          return 1
        }
        if (['TO_BE_START', 'DOING'].includes(this.details.visitState)) {
          return 2
        }
        if (this.details.visitState === 'END') {
          return 3
        }
        if (this.details.visitState === 'CANCEL') {
          return 3
        }
      }
      return 0
    }
  },
  watch: {
    details() {
      const now = Date.now()
      const startTime = new Date(this.details.visitStartTime).getTime()
      const restTimestamp = startTime - now
      if (restTimestamp >= 0) {
        setTimeout(_ => {
          if (this.id) this.fhGetVisitList(this.id)
        }, restTimestamp)
      }
    }
  },
  onLoad(options) {
    console.log(options, '新生儿申请oload')
    if (options.scene) {
      if (options.scene.includes('newborn')) {
      // 新生儿短链进入
        console.log('🤣🤣🤣🤣🤣🤣新生儿申请oload')
        console.log(options, '🤣🤣🤣🤣传进来的')
        wx.setStorageSync('hospitalFlag', true)
        const { hid, id } = this.sceneDecode(options.scene)
        console.log(hid, '/hid')
        console.log(id, '/id')
        this.id = id
        this.getnewbornSettings()
      }
    }

    if (options.id) this.id = options.id
    if (options.familyName) this.familyName = options.familyName
    this.getRules()
  },
  onShow() {
    if (this.id) {
      Promise.all([
        this.fhGetVisitList(this.id),
        this.getnewbornSettings()
      ]).then(() => {
        setEnableBtnTimer(this.details, this.settgins, () => {
          console.info('run  fhGetVisitList')
          this.fhGetVisitList(this.id)
        })
      })
    }
    uni.$on('selectTime', res => {
      console.log(res)
      const { selectTime } = res
      this.selectTime = selectTime
      // 清除监听
      uni.$off('selectTime')
    })
  },
  methods: {
    /**
     * 家属预约新生儿探视（创建新生儿探视）
     *
     */
    async fhCreateVisit(form) {
      try {
        const hospitalInfo = uni.getStorageSync('hospital-info')
        const hospitalId = hospitalInfo.hospitalId
        const memberId = uni.getStorageSync('memberId')
        const { results, message } = await fhCreateVisit(form, hospitalId, memberId)
        // 患者今日的预约次数超过医院设置的次数,则抛出提示,并打断代码后续操作
        if (message === '超过今日可预约次数') {
          uni.showModal({
            title: '提示',
            content: '您今日的申请次数已经使用完毕,请明日再预约'
          })
          return
        }
        // 患者本周的预约次数超过医院设置的次数,则抛出提示,并打断代码后续操作
        if (message === '超过本周可预约次数') {
          uni.showModal({
            title: '提示',
            content: '超过本周可预约次数'
          })
          return
        }
        this.fhGetVisitList(results.id)
        console.log(results, 'this.details')
      } catch (e) {
        return Promise.reject(e)
      }
    },
    /**
     * 获取新生儿探视详情
     * id：探视id
     */
    async fhGetVisitList(id) {
      uni.showLoading({ title: '正在加载中...' })
      try {
        const { results } = await fhGetVisitDetails(id)
        this.details = results
        this.selectTime = this.details.visitTime
        this.details.visitDate = `${dayjs(this.date).format('MM月DD日')} 周${['日', '一', '二', '三', '四', '五', '六'][
          dayjs(this.date).day()]}`
        console.log(this.details, 'this.details')
      } catch (e) {
        return Promise.reject(e)
      }
      uni.hideLoading()
    },
    // 获取医院新生儿探视的配置
    async getnewbornSettings() {
      try {
        const hospitalInfo = wx.getStorageSync('hospital-info')
        console.log(hospitalInfo, 'hospitalInfo123')
        const { results } = await fhGetnewbornSettings(hospitalInfo.hospitalId)
        getApp().globalData.newbornSetting = results
        this.settgins = results
      } catch (e) {
        console.log('debug axios', e)
      }
    },
    /**
     * 患者端获取探视规则
     *
     */
    async getRules() {
      try {
        const hospitalInfo = uni.getStorageSync('hospital-info')
        const hospitalId = hospitalInfo.hospitalId
        const { results } = await fhGetRules(hospitalId)
        this.rule = results.rules
      } catch (e) {
        return Promise.reject(e)
      }
    },
    /**
     * 取消新生儿探视的预约
     * id：探视id
     */
    async putModifyVisit(id) {
      uni.showLoading({ title: '正在加载中...' })
      try {
        await fhPutModifyVisit({ status: 'CANCEL', memberType: 'FAMILY_MEMBER' }, id)
        this.fhGetVisitList(id)
      } catch (e) {
        return Promise.reject(e)
      }
      uni.hideLoading()
    },
    /**
     * 申请新生儿探视
     */
    submitFrom(form) {
      form.familyName = this.familyName
      form.familyPhoneNumber = uni.getStorageSync('auth-phone')
      form.memberId = uni.getStorageSync('memberId')
      this.fhCreateVisit(form)
    },
    /**
     * 取消预约
     */
    cancelVisit(id) {
      this.putModifyVisit(id)
    },
    // 解析URL链接或二维码中的参数
    sceneDecode(str) {
      const result = {}
      const tempObj = str.split('_')
      tempObj.forEach(i => {
        const temp = i.split('-')
        if (temp?.[0]) result[temp[0]] = temp[1]
      })
      return result
    }
  },
  onUnload() {
  }
}
</script>
<style lang="scss" scoped>
.detail {
  .details-step {
    padding: 16rpx 0;
    background-color: #ffffff;
  }
  .line {
    width: 100%;
    height: 10rpx;
  }
  .msg {
  padding: 24rpx 17rpx;
  .block {
    width: 5rpx;
    height: 36rpx;
    margin-right: 6rpx;
    background: $u-type-primary;
    border-radius: 3rpx;
    margin-left: 5rpx;
  }
}
.title {
    color: #666;
    font-size: 30rpx;
    font-weight: bold;
  }
}
</style>
