/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-06-16 10:26:06
 * @LastEditors: lvdexin
 * @LastEditTime: 2022-08-02 11:54:52
 */
import { automaticPhone } from '../../utils/auth'
import { fhSavePatientInfo, fhEditPatientInfo } from '../../api/hospital/index'
import { fhSendMsm } from '../../api/notice/notice'
import { clone } from '../../utils/deep-copy'
const { Tips, watch, Loading, hLoading } = getApp()
let confirmFlag = null
let confirmResolve = null
const pageOptions = {
  // 页面数据
  data: {
    options: null,
    certificateList: [
      '中国居民身份证',
      '护照',
      '港澳居民来往内地通行证',
      '台湾居民来往内地通行证'
    ],
    certificateType: {
      0: 'ID_Card',
      1: 'Passport',
      2: 'HongKong_Macau_Pass',
      3: 'Taiwan_Pass'
    },
    authedImg: '../../images/authedFlag.png',
    certificateIndex: 0,
    isFirstOnShow: true, // 是否为首次执行onShow
    form: {},
    // editPhoneState: false, // 判断是否修改手机号显示验证码
    bloodArray: ['A', 'B', 'O', '其它'],
    loading: true,
    countDownTime: 60 * 1000,
    countDownFlag: false,
    // 修改手机号的弹窗
    changePhoneDialogShow: false,
    // 修改手机号的判断
    phoneFlag: false,
    // 法大大验证
    authedFlag: false,
    // 修改手机号弹窗的表单
    changePhoneForm: {},
    checkProtrol: false,
    isRecord: null, // 判断是否新生儿或者远程探视进入
    type:null, // 判断是否新生儿或者远程探视进入
    // 异步关闭弹窗
    beforeClose: action =>
      new Promise(resolve => {
        if (action === 'confirm') {
          if (confirmFlag) resolve(true)
          else confirmResolve = resolve
        } else {
          resolve(true)
        }
      })
  },
  // 页面载入时
  onLoad(e) {
    this.setData({ options: e })
    console.log('我是e', e)
    // isRecord == 1 判断是否没有填写过健康档案
    if(e.isRecord == 1) this.setData({phoneFlag: true, isRecord:e.isRecord})
    if(e.type) this.setData({type: e.type })
    this.init(e)
    // 根据用户入口不同,动态修改页面标题
    wx.setNavigationBarTitle({
      title: this.options.titleType === '1' ? '个人信息' : '健康档案'
    })
  },
  // 页面初始化
  init(e) {
    const { nextPath } = e
    this.tempNextPath = nextPath
  },
  // 页面准备好时
  onReady() {
    watch('patientInfo', this.initInfo.bind(this))
    console.log('我是form', this.data.form)
    const authedInformation = wx.getStorageSync('authedInformation') || ''
    if (authedInformation) {
      this.setData({
        authedInformation: authedInformation,
        ['form.name']: authedInformation.name,
      })
      if (this.data.certificateIndex === 0) {
        this.setData({
          ['form.identityCardNumber']: authedInformation.identityCardNumber
        })
      }
    }
    this.saveSwitchData()
  },
  // 页面显示时
  onShow() {
    const { isFirstOnShow } = this.data
    // 获取患者是否认证状态
    const isAuthedFlag = wx.getStorageSync('authedFlag')
    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false,
        authedFlag: isAuthedFlag
      })
      return
    }
  },
  // 自定义事件
  // 初始化表单
  initInfo(info = {}) {
    const phoneNum = wx.getStorageSync('auth-phone') || ''
    if (info && info.id) {
      this.tempHadInfo = true
    }
    this.setData({
      certificateIndex: Object.values(this.data.certificateType).findIndex(
        item => item === (info.certificateType || 'ID_Card')
      )
    })
    this.setData({
      form: { certificateType: 'ID_Card', ...info, phone: phoneNum, sex: 1 },
      loading: false,
      // 修复在获取手机号之后没有打开接受短信输入框的bug
      phoneFlag: !!phoneNum 
    })
  },
  // 输入
  onInputChange({ currentTarget: { dataset }, detail }) {
    const { key, formKey = 'form' } = dataset
    let { value } = detail
    // if (key === 'phone') this.setData({editPhoneState:true})
    if (key === 'sex') value = +value
    this.setData({
      [`${formKey}.${key}`]: typeof detail === 'string' ? detail : value
    })
  },
  // 初始进入页面或保存档案时certificateIndex
  saveSwitchData() {
    // 若初次进入该页面时,certificateIndex不等于0,则存储当前的证件类型下标以及身份证
    if (this.data.certificateIndex !== 0) {
      const switchData = { certificateIndex: this.data.certificateIndex, identityCardNumber: this.data.form.identityCardNumber }
      console.log('我是switchData', switchData)
      this.setData({
        switchData: switchData
      })
    }
  },
  //
  onPickerChange({ currentTarget: { dataset }, detail }) {
    // 若存在authedInformation的情况下执行
    if (this.data.authedInformation) {
      // 由于法大大实名认证返回的证件类型只能是身份证,所以用户进行证件类型切换时,是身份证类型则赋值法大大返回的身份证信息,否则为空
      if (detail.value === '0') {
        this.setData({
          ['form.identityCardNumber']: this.data.authedInformation.identityCardNumber
        })
      } else {
        const switchData = this.data.switchData
        if (switchData && detail.value === String(switchData.certificateIndex)) {
          this.setData({
            ['form.identityCardNumber']: switchData.identityCardNumber
          })
        } else {
          this.setData({
            ['form.identityCardNumber']: ''
          })
        }
      }
    }
    this.setData({
      // 将certificateIndex转换为数值
      certificateIndex: Number(detail.value),
      'form.certificateType': this.data.certificateType[detail.value]
    })
  },
  // 自动填入手机号或修改手机号
  async automaticPhoneFn(e) {
    const { type } = e.currentTarget.dataset
    if (type === 'change') {
      this.setData({
        changePhoneDialogShow: true,
        changePhoneForm: clone(this.data.form)
      })
      confirmFlag = false
      confirmResolve = null
      return
    }

    const { errMsg } = e.detail
    if (errMsg.includes('deny')) return

    const phone = await automaticPhone(e)
    this.setData({
      'form.phone': phone
    })
  },
  // 保存用户信息
  async fhSavePatientInfo() {
    if (this.data.form.identityCardNumber) {
      // 判断身份证格式
      let card = this.data.form.identityCardNumber
      let regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!this.data.form.certificateType) {
        wx.showToast({ icon: 'none', title: '请选择证件类别' })
        return false
      }
      if (!regIdNo.test(card)) {
        if (this.data.certificateIndex === 0) {
          wx.showToast({ icon: 'none', title: '请输入正确的身份证' })
          return false
        }
      }
    }
    if (!this.data.options.showStep && !this.data.checkProtrol) {
      wx.showToast({ icon: 'none', title: '需要先勾选服务协议和隐私政策' })
      return
    }
    try {
      const { form, changePhoneForm } = this.data
      const hospitalInfo = wx.getStorageSync('hospital-info')
      const send = {
        hospitalId: hospitalInfo.hospitalId,
        ...form,
        ...changePhoneForm
      }
      const { results } = this.tempHadInfo
        ? await fhEditPatientInfo(send)
        : await fhSavePatientInfo(send)
      confirmFlag = true
      Tips('保存档案成功')
      this.saveSwitchData()
      // this.setData({editPhoneState:false})
      wx.$setGlobalData('patientInfo', results)
      this.setData(
        {
          form: results,
          changePhoneForm: {},
          phoneFlag: false
        },
        () => {
          if (confirmResolve) confirmResolve(true)
        }
      )
      if (this.data.options.showStep) {
        wx.redirectTo({
          url: '/remote/patient/hospitalInformation/index'
        })
        return
      }
      if (this.data.type === 'newborn') {
        wx.redirectTo({
          url: '/pages/babyVisit/newBorn/index'
        })
        return
      }
      if (this.tempNextPath) {
        setTimeout(() => {
          wx.$routerTo({
            url: decodeURIComponent(this.tempNextPath),
            type: 'reLaunch'
          })
        }, 1000 * 0.8)
      }
    } catch (e) {
      console.log('debug axios', e)
      if (confirmResolve) confirmResolve(false)
    }
  },
  // 获取手机验证码
  async getMsmCode() {
    const { form, changePhoneForm, countDownFlag } = this.data
    const { phone } = form
    const { phone: changePhone } = changePhoneForm
    // 获取未修改前的手机号
    const originalPhone = wx.getStorageSync('auth-phone') || ''
    // 未更换手机号获取验证码时,提示'请输入新的手机号'
    if(this.data.isRecord != 1){
      if (originalPhone === phone) {
        Tips('请输入新的手机号')
        return
      }
      if (phone === changePhone) {
        Tips('手机号未修改')
        return
      }
    }

    if (countDownFlag) return

    if (!phone) {
      Tips('请输入手机号')
      return
    }
    Loading('获取手机验证码中...')
    try {
      await fhSendMsm({ phone: changePhone || phone })
      Tips('获取验证码成功，请留意手机短信')
      this.setData(
        {
          countDownFlag: true
        },
        () => {
          this.start()
        }
      )
    } catch (e) {
      console.log('debug axios', e)
    }
    hLoading()
  },
  /**
   * 更换手机号
   */
  changePhone() {
    this.setData({
      phoneFlag: true
    })
  },
  // 倒计时开始
  start() {
    const countDown = this.selectComponent('#control-count-down')
    countDown.start()
  },
  // 倒计时暂停
  pause() {
    const countDown = this.selectComponent('#control-count-down')
    countDown.pause()
  },
  // 倒计时重置
  reset() {
    const countDown = this.selectComponent('#control-count-down')
    countDown.reset()
  },
  // 倒计时结束
  finished() {
    this.reset()
    this.setData({
      countDownFlag: false
    })
  },
  jumpProtrol({ target: { dataset } }) {
    wx.navigateTo({
      url: `/pages/personal/agreement/agreement?type=${dataset.type}&title=${dataset.title}`
    })
  },
  toggleProtrol() {
    this.setData({
      checkProtrol: !this.data.checkProtrol
    })
  },
  // 弹窗关闭
  dialogClose() {
    confirmFlag = null
    confirmResolve = null
    this.setData({
      changePhoneForm: {}
    })
  }
}

Page(pageOptions)
