<template>
  <view class="detail">
    <view class="line" />
    <view class="u-flex u-row-between">
      <view class="msg u-flex g-bor-bottom">
        <view class="block" />
        <view class="title"> 预约信息 </view>
      </view>
      <view style="margin-right: 20px;color: #999999; font-size: 30rpx;" @click="showRule = true">
        探视规则 <u-icon
          style="margin-left: 5px;"
          name="info-circle"
        /></view>
    </view>
    <view class="basic-wrappper">
      <u-form ref="form" :model="form" :label-width="150" label-align="left">
        <u-form-item label="医院名称" required>
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="form.hospitalName"
              disabled="true"
              style="width: 230px"
              input-align="right"
            />
          </view>
        </u-form-item>

        <u-form-item label="住院号" required prop="admissionNum">
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="form.admissionNum"
              :disabled="details"
              type="number"
              style="width: 250px"
              input-align="right"
              placeholder="请输入新生儿的住院号"
            />
          </view>
        </u-form-item>

        <u-form-item label="新生儿性别" required prop="sex">
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="sex"
              disabled="true"
              input-align="right"
              placeholder="请选择新生儿性别"
              @click="selectSex"
            />
            <u-icon name="arrow-right" color="#E1E1E1" @click="selectSex" />
          </view>
        </u-form-item>

        <u-form-item label="父亲姓名" required prop="fatherName">
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="form.fatherName"
              :disabled="details"
              style="width: 250px"
              input-align="right"
              placeholder="请输入父亲姓名"
            />
          </view>
        </u-form-item>

        <u-form-item label="母亲姓名" required prop="motherName">
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="form.motherName"
              :disabled="details"
              style="width: 250px"
              input-align="right"
              placeholder="请输入母亲姓名"
            />
          </view>
        </u-form-item>

        <u-form-item label="预约日期" required prop="visitDate">
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="form.visitDate"
              disabled="true"
              input-align="right"
              placeholder="请选择"
              @click="dateShow"
            />
            <u-icon name="arrow-right" color="#E1E1E1" @click="dateShow" />
          </view>
        </u-form-item>

        <u-form-item label="预约时间" required prop="time">
          <view class="u-flex u-row-right u-col-center">
            <view v-if="appointTime" @click="jump">
              <view>
                {{ appointTime }}
              </view>
            </view>
            <u-input
              v-else
              v-model="form.time"
              disabled="true"
              input-align="right"
              placeholder="请选择"
              @click="jump"
            />
            <u-icon name="arrow-right" color="#E1E1E1" />
          </view>
        </u-form-item>

        <u-form-item label="预约人手机号" label-width="180" required>
          <view class="u-flex u-row-right u-col-center">
            <u-input
              v-model="phone"
              disabled="true"
              style="width: 250px"
              input-align="right"
            />
          </view>
        </u-form-item>

        <u-form-item v-if="isDetails" label="探视状态">
          <view class="state-box" @click="onOpenStatus">
            <view class="u-flex u-row-right u-col-center">
              <view class="remote-text" :style="{color: details.visitState === 'CANCEL'? '#F32D2D':'#69A9F8'}">{{ stateCurrent }}</view>
              <u-icon name="arrow-right" color="#69A9F8" />
            </view>
            <view v-if="details.visitState === 'CONFIRM_DOING'" class="state-font">
              申请已提交，请等待医院确认
            </view>
            <view v-if="details.visitState === 'CONFIRM_DOING'" class="state-font">
              务必准时参加新生儿探视
            </view>
          </view>
        </u-form-item>
        <view v-if="details.visitState === 'CANCEL'&& form.reason " class="remarks">
          <view class="msg-remarks">取消原因</view>
          <view>
            <textarea
              data-key="remark"
              :value="form.reason"
              class="text-remarks"
              disabled="true"
            />
          </view>
        </view>
        <view class="basic-footer">
          <view v-if="details.visitState === 'TO_BE_CONFIRM'|| details.visitState === 'CONFIRM_DOING' " class="txt-bottom" style="color: #F32D2D;">申请已提交，请等待医院确认</view>
          <view v-if="showEnterRoom&&!isCanEnterRoom" class="txt-bottom" style="color: #F13B3B;">请在{{ changeVisitStartTime }}进入新生儿探</view>
          <view class="safe-bottom">
            <u-button
              v-if="details === null"
              type="primary"
              @click="submit"
            >提交申请</u-button>
            <u-button
              v-if="isCanEnterRoom"
              type="primary"
              :custom-style="{
                backgroundColor: !isCanEnterRoom ? '#C7C7C7 !important' : ''
              }"
              @click="enterRoom"
            >
              进入新生儿探视
            </u-button>
            <u-button v-if="details.visitState === 'TO_BE_CONFIRM'|| details.visitState === 'CONFIRM_DOING' " type="error" @click="handleCancel">取消预约</u-button>
            <view v-if="details.visitState === 'END'" class="u-flex u-row-center">
              <view class="end-info">- 探视已完结 -</view>
            </view>
          </view>
        </view>
      </u-form>
    </view>

    <!-- 选择新生儿性别  -->
    <u-select v-model="sexShow" style=" font-size: 18px" :list="sexList" @confirm="comfirmSex" />

    <!-- 取消预约 -->
    <u-modal v-model="cancel" :content="cancelTxt" :mask-close-able="true" show-cancel-button @confirm="confirmCancel" />

    <!-- 预约日期 -->
    <u-calendar v-model="showDate" :min-date="minDate" max-date="2100-01-01" mode="date" @change="changeDate" />

    <!-- 探视规则 -->
    <u-popup
      v-model="showRule"
      mode="center"
      closeable
      width="600"
      height="800"
      border-radius="15"
    >
      <view class="rule-box">
        <view class="rule-title">新生儿科探视制度</view>
        <u-parse class="rule-content" :html="rule" />
      </view>
    </u-popup>
  </view>
</template>

<script>
import dayjs from 'dayjs'
export default {
  props: {
    selectTime: {
      type: String,
      default: null
    },
    disable: {
      type: Boolean,
      default: false
    },
    details: {
      type: Object,
      default: null
    },
    rule: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 预约时间
      appointTime: null,
      stepList: [
        {
          name: '申请探视'
        },
        {
          name: '医生确认'
        },
        {
          name: '准备探视'
        },
        {
          name: '完成探视'
        }
      ], // 步骤条
      form: {
        hospitalName: uni.getStorageSync('exactaddress'),
        fatherName: '',
        motherName: '',
        visitDate: '',
        time: null,
        sex: '',
        admissionNum: ''
      }, // 表单数据
      showDate: false, // 日期显示
      showRule: false, // 规则显示
      date: '', // 赋值的date
      minDate: dayjs().format('YYYY-MM-DD'),
      isNotCanEnterRoom: true,
      cancel: false,
      cancelTxt: '确认取消本次预约？',
      sexShow: false,
      sexList: [{
        value: 0,
        label: '男孩'
      },
      {
        value: 1,
        label: '女孩'
      }],
      sex: null, // 展示用
      phone: uni.getStorageSync('auth-phone')
    }
  },
  computed: {
    stateCurrent() {
      if (this.details) {
        if (this.details.visitState === 'TO_BE_CONFIRM') {
          return '待护士确认'
        } else if (this.details.visitState === 'CONFIRM_DOING') {
          return '确认中'
        } else if (this.details.visitState === 'TO_BE_START') {
          return '待开始'
        } else if (this.details.visitState === 'DOING') {
          return '进行中'
        } else if (this.details.visitState === 'END') {
          return '探视结束'
        } else if (this.details.visitState === 'CANCEL') {
          return '已取消'
        }
      }
      return null
    },

    isDetails() {
      if (this.details) {
        return true
      } else {
        return false
      }
    },
    showEnterRoom() {
      if (this.details) {
        return ['DOING', 'TO_BE_START'].includes(this.details.visitState)
      }
      return false
    },
    showFooter() {
      if (this.options && this.options.id) {
        return ['CONFIRM_DOING', 'TO_BE_START', 'DOING'].includes(
          this.details && this.details.visitState
        )
      } else {
        return true
      }
    },
    // 是否可以进房间的按钮
    isCanEnterRoom() {
      console.log(this.form)
      if (this.details) {
        const newbornSettings = getApp().globalData.newbornSetting
        const toBeStartTimes =
          dayjs(this.details.visitStartTime).valueOf() - dayjs().valueOf()
        return (
          this.details.visitState === 'DOING' ||
          (this.details.visitState === 'TO_BE_START' &&
            newbornSettings.aheadEnterSwitch &&
            toBeStartTimes < dayjs(newbornSettings.aheadEnterTime).valueOf() * 60 * 1000)
        )
      }
      return false
    },
    changeVisitStartTime() {
      if (this.details) {
        if ((this.details.visitStartTime)) {
          return `${dayjs(this.details.visitStartTime).format('MM')}月${dayjs(this.details.visitStartTime).format('DD')}日  ${dayjs(this.details.visitStartTime).format('HH:mm')}`
        } else {
          return ''
        }
      } else {
        return ''
      }
    }
  },
  watch: {
    selectTime(newVal) {
      this.appointTime = newVal
    },

    details: {
      handler() {
        this.form = this.details
        this.phone = this.details.familyPhoneNumber
        this.sexList.forEach(item => {
          if (item.value === this.details.sex) this.sex = item.label
        })
      }
    }
  },
  methods: {
    changeDate(e) {
      this.date = e.result
      this.form.visitDate = `${dayjs(this.date).format('MM月DD日')} 周${['日', '一', '二', '三', '四', '五', '六'][
        dayjs(this.date).day()]}`

      if (e.result) {
        this.appointTime = null
      }
    },

    jump() {
      if (!this.isDetails) {
        (this.form.visitDate ?? '') !== '' ? uni.navigateTo({ url: `/pages/babyVisit/appointTime/index?visitDate=${this.date}` }) : uni.showToast({ title: '请先选择预约日期', icon: 'none' })
      }
    },

    // 提交表单
    submit() {
      const form = this.form
      form.time = this.appointTime
      form.appointmentDate = this.date
      if (this.formValidate(form)) {
        this.$emit('submitFrom', form)
      }
    },
    // 取消预约
    handleCancel() {
      this.cancel = true
    },
    // 确认取消预约
    confirmCancel() {
      this.$emit('cancelVisit', this.form.id)
    },
    // 显示日期
    dateShow() {
      this.details ? this.showDate = false : this.showDate = true
    },
    /**
     *  进入房间
     *
     */
    enterRoom() {
      // 授权登录
      if (uni.getStorageSync('anflag')) {
        uni.navigateTo({ url: '/pages/authorization/authorization' })
        return
      }
      // 提前进入房间的判断
      if (!this.isCanEnterRoom) {
        uni.showToast({ title: '探视未开始', icon: 'none' })
        return
      }

      this.checkDeviceAuthorize()
        .then(result => {
          const id = this.details.id
          const memberType = 'family'
          uni.navigateTo({
            url: `/remote/entrance/index?id=${id}&memberType=${memberType}&template=newborn`
          })
        })
        .catch(error => {
          console.log('没有授权', error)
        })
    },
    /**
     * 授权摄像头&&麦克风
     */
    checkDeviceAuthorize: function() {
      this.hasOpenDeviceAuthorizeModal = false
      return new Promise((resolve, reject) => {
        if (!uni.getSetting || !uni.getSetting()) {
        // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
          resolve()
        }
        uni.getSetting().then(result => {
          this.authorizeMic = result[1].authSetting['scope.record']
          if (
            result[1].authSetting['scope.record']
          ) {
          // 授权成功
            resolve()
          } else {
          // 没有授权，弹出授权窗口
          // 注意： uni.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
            this.openConfirm()
            console.log('getSetting 没有授权，弹出授权窗口', result)
            uni.authorize({
              scope: 'scope.record'
            })
              .then(res => {
                console.log('authorize mic', res)
                this.authorizeMic = true
              })
              .catch(error => {
                console.log('authorize mic error', error)
                this.authorizeMic = false
              })
          }
        })
      })
    },
    /**
     * 麦克风弹框提示
     */
    openConfirm: function() {
      if (this.hasOpenDeviceAuthorizeModal) {
        return
      }
      this.hasOpenDeviceAuthorizeModal = true
      return uni.showModal({
        content: '您没有打开麦克风的权限，是否去设置打开？',
        confirmText: '确认',
        cancelText: '取消',
        success: res => {
          this.hasOpenDeviceAuthorizeModal = false
          console.log(res)
          // 点击“确认”时打开设置页面
          if (res.confirm) {
            console.log('用户点击确认')
            uni.openSetting({
              success: res => {}
            })
          } else {
            console.log('用户点击取消')
          }
        }
      })
    },
    /**
     * 查看探视状态跟踪
     *
     */
    onOpenStatus() {
      this.$emit('on-open-status')
    },
    /**
     * 显示新生儿性别
     *
     */
    selectSex() {
      this.details ? this.sexShow = false : this.sexShow = true
    },
    /**
     * 确认新生儿性别
     *
     */
    comfirmSex(e) {
      this.sex = e[0].label
      this.form.sex = e[0].value
    },
    /**
     *  表单校验
     *
     */
    formValidate(form) {
      if (form.admissionNum === '') {
        uni.showToast({
          title: '请输入新生儿的住院号',
          icon: 'none'
        })
      } else if (form.sex === '') {
        uni.showToast({
          title: '请选择新生儿性别',
          icon: 'none'
        })
        return false
      } else if (form.fatherName === '') {
        uni.showToast({
          title: '请填写父亲姓名',
          icon: 'none'
        })
        return false
      } else if (form.motherName === '') {
        uni.showToast({
          title: '请填写母亲姓名',
          icon: 'none'
        })
        return false
      } else if (form.babyName === '') {
        uni.showToast({
          title: '请填写患者姓名',
          icon: 'none'
        })
        return false
      } else if (form.visitDate === '') {
        uni.showToast({
          title: '请选择预约日期',
          icon: 'none'
        })
        return false
      } else if (form.time === '') {
        uni.showToast({
          title: '请选择预约时间',
          icon: 'none'
        })
        return false
      }
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
.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;
}
.basic-wrappper {
  padding: 0 40rpx;
  padding-bottom: 300rpx;
  .basic-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 30rpx;
    background-color: #ffffff;
    z-index: 100;
    .end-info {
    color: $color-text-weak;
    font-size: 32rpx;
  }
  }
}
.rule-box {
  padding: 35px 0;
}
.rule-title {
  text-align: center;
  margin-left:18px;
  width: 289px;
  height: 29px;
  font-size: 16px;
  color: #323233;
  font-weight: bold;
}
.rule-content {
  text-indent: 2em;
  color: #666666;
  font-size: 13px;
  margin: 10px 15px;
}
.remote-text{
  color: #69A9F8;
  font-size: 14px;
}

.state-box{
  display: flex;
  flex-direction: column;
.state-font{
  color: #F13B3B;
  font-size: 14px;
  display: flex;
  flex-direction: row-reverse;
}
}
.remarks {
  height: 150px;
  display: flex;
  flex-direction: column;
}
.msg-remarks {
  font-size: 15px;
  color: #303133
}
 .text-remarks {
  height: 100px;
  width: 335px;
  background: #ffffff;
  border: 2px solid #f2f2f2;
  margin-top: 10px;
  font-size: 14px;
}
.txt-bottom{
  line-height: 30px;
  font-size: 14px;
  text-align: center;
}
</style>
