const { Tips, watch, Loading, hLoading } = getApp()
const app = getApp()
import {
  fhSaveFamilyMembers,
  fhGetFamilyMembersDetail,
  fhEditFamilyMembers,
  fhDeleteFamilyMembers
} from '../../../api/remote/index'
import { fhSendMsm } from '../../../api/notice/notice'

const pageOptions = {
  // 页面数据
  data: {
    options: null,
    editFlag: false,
    isFirstOnShow: true, // 是否为首次执行onShow
    form: {
      sex: 0,
      bedNumber: app.globalData.hospitalInfo.bedNumber,
      sickroomId: app.globalData.hospitalInfo.sickroomId,
      hospitalId: app.globalData.hospitalInfo.hospitalId,
      defaultStatus:false,
    },
    certificateTypeIndex: 0,
    certificateTypeEnmu: {
      0: 'ID_Card',
      1: 'Passport',
      2: 'HongKong_Macau_Pass',
      3: 'Taiwan_Pass'
    },
    certificateType: [
      '中国居民身份证',
      '护照',
      '港澳居民来往内地通行证',
      '台湾居民来往内地通行证'
    ],
    relationIndex: -1,
    // relation: ['父子', '母子', '亲戚', '其他'],
    relation: ['家庭成员', '亲戚', '朋友', '其他'],
    countDownTime: 60 * 1000,
    familyMemberId: '',
    loading: true,
    countDownFlag: false,
    change: null //编辑
  },
  onInputChange({ currentTarget: { dataset }, detail }) {
    const { key, formKey = 'form' } = dataset
    let { value } = detail
    if (key === 'sex') value = +value
    this.setData({
      [`${formKey}.${key}`]: typeof detail === 'string' ? detail : value
    })
  },
  onChangeCertificateType({ currentTarget: { dataset }, detail }) {
    this.setData({
      certificateTypeIndex: detail.value
    })
  },
  onChangeRelation({ currentTarget: { dataset }, detail }) {
    this.setData({
      relationIndex: detail.value
    })
  },

  onChangeSelect({ currentTarget: { dataset },detail }) {
    const { formKey = 'form' } = dataset
    this.setData({
      [`${formKey}.defaultStatus`]: !this.data.form.defaultStatus
    });
  },

  //患者添加家属
  async fhSaveFamilyMembers() {
    const {
      form,
      certificateTypeIndex,
      certificateTypeEnmu,
      relationIndex,
      relation
    } = this.data
    const memberId = app.globalData.baseInfo.memberId
    form.certificateType = certificateTypeEnmu[certificateTypeIndex]
    form.relation = relation[relationIndex]
    const familyMemberId = this.options.id
    try {
      const { results } = this.options.id
        ? await fhEditFamilyMembers(form, memberId, familyMemberId)
        : await fhSaveFamilyMembers(form, memberId)
      // const { results } = await fhSaveFamilyMembers(form, memberId);
      Tips('保存成功')
      // wx.$setGlobalData("familyMemberInfo", results);
      wx.navigateBack()
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 获取患者家属详情
  async fhGetFamilyMembersDetail() {
    const form = []
    const memberId = app.globalData.baseInfo.memberId
    const familyMemberId = this.options.id
    try {
      const { results } = await fhGetFamilyMembersDetail(
        form,
        memberId,
        familyMemberId
      )

      this.setData({
        certificateTypeIndex: Object.values(
          this.data.certificateTypeEnmu
        ).findIndex(r => r === results.certificateType),
        relationIndex: this.data.relation.findIndex(
          r => r === results.relation
        ),
        form: results
      })
      wx.$setGlobalData('familyMemberInfo', results)
      if (results !== null) {
        this.setData({
          editFlag: true
        })
      }
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 获取手机验证码
  async getMsmCode() {
    const { form, countDownFlag } = this.data
    const { phone } = form
    // const { phone: changePhone } = changePhoneForm;
    // if (phone === changePhone) {
    //   Tips("手机号未修改");
    //   return;
    // }
    if (countDownFlag) return

    if (!phone) {
      Tips('请输入手机号')
      return
    }
    Loading('获取手机验证码中...')
    try {
      await fhSendMsm({ phone })
      Tips('获取验证码成功，请留意手机短信')

      this.setData(
        {
          countDownFlag: true
        },
        () => {
          this.start()
        }
      )
    } catch (e) {
      console.log('debug axios', e)
    }
    hLoading()
  },
  // 初始化表单
  initInfo(info = {}) {
    if (info && info.memberId) {
      this.tempHadInfo = true
    }
    this.setData({
      form: { ...info },
      loading: false
    })
    console.log(info, '....11111')
  },
  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
    })
  },
  fhDeleteFamilyMember() {
    wx.showModal({
      title: '提示',
      content: '确定删除该家属？',
      success: ({ confirm }) => {
        if (confirm) {
          fhDeleteFamilyMembers(
            app.globalData.baseInfo.memberId,
            this.options.id
          ).then(() => {
            wx.showToast({ icon: 'none', title: '操作成功～' })
            wx.navigateBack()
          })
        }
      }
    })
  },
  // 页面载入时
  onLoad(e) {
    this.options = e
    this.setData({
      options: e
    })
    this.init(e)
    if (this.options.id) {
      this.fhGetFamilyMembersDetail()
    }
    // this.setData({
    //   id: e.id,
    //   memberType: e.memberType,
    //   memberId: e.memberId,
    // });
  },
  // 页面初始化
  init(e) {},
  // 页面准备好时
  onReady() {
    watch(' app.globalData.familyMemberInfo', this.initInfo.bind(this))
  },
  // 页面显示时
  onShow() {
    const { isFirstOnShow } = this.data

    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false
      })
      return
    }
  },
  // 页面隐藏时
  onHide() {},
  // 页面卸载时
  onUnload() {
    wx.$setGlobalData('familyMemberInfo', null)
    wx.$setGlobalData('familyMemberId', 0)
  },
  // 下拉页面时
  onPullDownRefresh() {},
  // 到达页面底部时
  onReachBottom() {},
  // 页面滚动时
  onPageScroll() {},
  // 分享时，注：onShareAppMessage不能为async异步函数，会导致不能及时取得返回值，使得分享设置无效
  onShareAppMessage() {
    /* const title = ''
    const path = ''
    const imageUrl = ``

    return {
      title,
      path,
      imageUrl,
    } */
  }
}

Page(pageOptions)
