<!--
 * @Descripttion: 首页
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-08-11 15:07:09
 * @LastEditors: zhangzhuobin 1093998108@qq.com
 * @LastEditTime: 2022-05-31 18:33:55
-->
<template>
  <view>
    <u-modal
      :value="show"
      title="认证提醒"
      cancel-text="暂不使用"
      cancel-color="#666666"
      show-cancel-button
      width="540"
      border-radius="12"
      :title-style="{ 'font-size': '36rpx' }"
      :cancel-style="{ 'font-size': '30rpx' }"
      @cancel="onCancel"
    >
      <view class="content">
        <view class="info">
          为了保证用户合法使用与系统安全运行，根据国家网络信息安全相关要求，请您完成实名认证。
        </view>
        <view class="checkbox" @click="viewAgreement">
          <u-checkbox :value="checked" shape="circle">
            <view class="text">《服务协议》和《隐私政策》</view>
          </u-checkbox>
        </view>
      </view>
      <template #confirm-button>
        <view
          class="confirm"
          :class="{ disabled: !checked }"
          @click="confirm"
        >确定</view>
      </template>
    </u-modal>
    <view
      v-if="message.show"
      :value="message.show"
      :show-title="false"
      :show-cancel-button="false"
      width="540"
      border-radius="12"
      :title-style="{ 'font-size': '36rpx' }"
      :cancel-style="{ 'font-size': '30rpx' }"
      @cancel="onCancel"
    />
    <view v-if="message.show" class="content">
      <view
        class="title"
      >您需要阅读并确认以下2份协议（{{ message.step }}/2）</view>
      <view class="info">
        <view class="name">{{ message.title }}</view>
        <rich-text :nodes="message.info" />
      </view>
    </view>
    <view
      v-if="message.show"
      class="confirmBtn confirm u-flex u-row-center"
      :style="{
        color: message.btnClick ? '#69a9f8' : '#c7c7c7',
        background: message.btnClick ? '#e6f7ff' : '#fff'
      }"
      @click="confirmAgreenment"
    >
      我已阅读并确认<view
        v-if="!countDownEnd"
      >（<u-count-down
        :timestamp="5"
        :show-days="false"
        :show-hours="false"
        :show-minutes="false"
        :color="message.btnClick ? '#69a9f8' : '#c7c7c7'"
        @end="message.btnClick = true"
        @change="changecountDownTime"
      />）</view>
    </view>
  </view>
</template>

<script>
const app = getApp()
import uModal from 'uview-ui/components/u-modal/u-modal.vue'
import uCheckbox from 'uview-ui/components/u-checkbox/u-checkbox.vue'
import { sceneDecode } from '@/utils/util'
import { getReadPrivacyCache, setReadPrivacyCache } from '@/utils/cache/privacy'
import {
  fhGetPatientRecord,
  fhGetPatientInfo
} from '../../../../mainWeixinMp/api/remote/index'
import {
  fhAgreement,
  fhReaderFile
} from '../../../../mainWeixinMp/api/merchant/index'
export default {
  components: {
    uModal,
    uCheckbox
  },
  data() {
    return {
      basicForm: null,
      hospitalForm: null,
      show: false,
      checked: false,

      message: {
        show: false,
        btnClick: false,
        step: 0,
        info: '',
        title: ''
      },

      service: '',
      privacy: '',
      countDownEnd: false,
      readFlag: false,

      type: null
    }
  },
  onLoad(options) {
    console.log(options, '我是options')
    this.type = options.type
    if (options.scene) {
      options = {
        ...options,
        ...sceneDecode(options.scene)
      }
    }
    this.options = options
  },
  onShow() {
    setTimeout(() => {
      this.verifyAuth().then(() => this.init())
    }, 1500)
  },
  methods: {
    async init() {
      const isReadPrivacy = getReadPrivacyCache()
      this.featureGetReader()
      try {
        const { results } = await fhAgreement('SERVICE')
        this.service = results.content
      } catch (error) {
        console.log(error)
      }
      try {
        const { results } = await fhAgreement('PRIVACY')
        this.privacy = results.content
      } catch (error) {
        console.log(error)
      }
      try {
        await Promise.all([this.fhGetPatientInfo(), this.fhGetPatientRecord()])
        if (isReadPrivacy) {
          this.jumpPage()
        } else {
          this.show = true
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 是否强制阅读
    async featureGetReader() {
      try {
        const { results } = await fhReaderFile()
        wx.setStorageSync('readerFlag', results)
        this.readFlag = results
      } catch (e) {
        console.error(e, 'error')
      }
    },
    verifyAuth() {
      return new Promise((resolve, reject) => {
        const ifAuth = wx.getStorageSync('anflag')
        if (ifAuth) {
          wx.$routerTo('/pages/authorization/authorization')
          reject('未登录')
        } else {
          resolve()
        }
      })
    },
    async fhGetPatientInfo() {
      const form = []
      const memberId = app.globalData.baseInfo.memberId
      try {
        const { results } = await fhGetPatientInfo(form, memberId)
        this.basicForm = results
        return results
      } catch (e) {
        return Promise.reject(e)
      }
    },
    // 获取患者住院信息
    async fhGetPatientRecord() {
      const form = []
      const memberId = app.globalData.baseInfo.memberId
      const hospitalId = app.globalData.hospitalInfo.hospitalId

      try {
        const { results } = await fhGetPatientRecord(form, memberId, hospitalId)
        this.hospitalForm = results
        return results
      } catch (e) {
        return Promise.reject(e)
      }
    },
    viewAgreement() {
      if (!this.readFlag) {
        this.show = true
        this.checked = true
        return true
      }
      if (!this.checked) {
        this.show = false
        this.message.step = this.message.step + 1
        this.message.title =
          this.message.step === 2 ? '隐私协议' : '用户服务协议'
        this.message.info =
          this.message.step === 2 ? this.privacy : this.service
        this.message.show = true
      }
    },
    confirmAgreenment() {
      if (this.message.btnClick) {
        this.message.show = false
        this.message.btnClick = false
        this.countDownEnd = false

        setTimeout(() => {
          if (this.message.step === 1) {
            this.viewAgreement()
          } else {
            this.checked = true
            this.message.show = false
            this.show = true
          }
        }, 500)
      }
    },
    confirm() {
      if (this.checked) {
        setReadPrivacyCache(true)
        this.jumpPage()
      }
    },
    jumpPage() {
      if (this.type === 'remote') {
        if (this.options.rid) {
          uni.redirectTo({
            url:
              '/remote/family-member/info/index' +
              '?scene=rid-' +
              this.options.rid
          })
          return
        }
        if (!this.basicForm) {
          uni.reLaunch({
            url: '/pages/health-record/index?showStep=1&&isRecord=1'
          })
          return
        }
        if (!this.hospitalForm) {
          uni.reLaunch({
            url: '/remote/patient/hospitalInformation/index'
          })
          return
        }
        uni.reLaunch({
          url: '/remote/patient/home/index'
        })
      } else if (this.type === 'newBorn') {
        if (!this.basicForm) {
          uni.reLaunch({
            url: '/pages/health-record/index?isRecord=1&type=newborn'
          })
          return
        }
        console.log('跳转成功🤣🤣')
        uni.reLaunch({
          url: '/pages/babyVisit/newBorn/index'
        })
      }
    },
    onCancel() {
      if (this.options.type === 'back') {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/home/index'
        })
      }
    },
    changecountDownTime(countDownTime) {
      if (countDownTime === 0) {
        this.countDownEnd = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  margin: 0 28rpx;
  .title {
    padding-top: 20rpx;
    margin-bottom: -20rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #333333;
    text-align: center;
  }
  .info {
    color: #666666;
    margin-top: 35rpx;
    margin-bottom: 30rpx;
    font-size: 26rpx;

    .name {
      margin-bottom: 20rpx;
      font-size: 30rpx;
      text-align: center;
    }

    .desc {
      max-height: 700rpx;
      overflow: scroll;
    }
  }
  .checkbox {
    margin-bottom: 25rpx;
    .text {
      color: #69a9f8;
      font-size: 26rpx;
    }
  }
}
.confirm {
  position: relative;
  color: #69a9f8;
  font-size: 30rpx;
  &.disabled {
    color: #c7c7c7;
  }
  &::after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 1px;
    height: 100%;
    transform: translateX(0.5);
    background-color: #f2f2f2;
  }
}
.confirmBtn {
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  line-height: 100rpx;
}
</style>
