const {
  globalData: {
    util: {
      regeneratorRuntime,
      api: {
        guide,
        addCollect,
        delCollect,
        server,
        reservationServiceList,
        reservationSave,
        reservationDateStatus,
        sendVerifCode,
        verifSmsCode
      },
      navigate,
      navigate_native,
      navigate_auth_native,
      navigateBack,
      showTip,
      request: {
        get,
        get_auth,
        post_auth
      },
      extend: {
        dateLaters
      },
      getUserInfo,
      inputChange,
      pickerChange,
      appKey,
      md5,
      goSuccess,
      init,
      verify: {
        isPhone,
        form_verify
      }
    }
  }
} = getApp(),
  t = {
    name: '请选择',
    list: [
      {
        name: '请选择',
      }
    ]
  },
  t_arr = ['请选择'],
  realNameTip = true,
  date_list = [t_arr, ...dateLaters(7).filter(([, x]) => !/[六|日]/.test(x))];
let lock;

Page({
  data: {
    date_list_range: date_list.map(x => x.join('  ')),
    dep_list: [t],
    verify: {
      applicantIdCard: "请输入证件号码",
      applicantIdType: "请输入证件类型",
      applicantName: "请输入预约姓名",
      applicantPhone: x => x ? !isPhone(x) && '您输入的电话格式不正确' : '请输入预约电话',
      checked: (x, { mask }) => mask && !x && '请先阅读预约须知',
      code: x => x.length != 4 && '请输入六位短信验证码',
      deptUnid: "请选择预约窗口",
      reservationDate: "请选择预约日期",
      reservationInterval: "请选择预约时段",
      serviceUnid: "请选择预约事项"
    }
  },
  onLoad({ unid }) {
    unid && this.setData({ flag: !!this.setHandleInfo(unid) })
    init(this).p_code = get(server, { code: 'CARDTYPE' }, { loading: true, loadingMsg: '加载证件列表...' }).then(code_list => {
      if (code_list._err) return []
      code_list = code_list.map(({ dictValueCode: id, dictValueName: name }) => ({ id, name }))
      this.setData({ code_list })
      return code_list
    })
  },
  async onShow() {
    lock = false
    const { num: applicantIdCard, code_type: applicantIdType, name: applicantName, phone: applicantPhone, _err } = await getUserInfo({ realNameTip, loading: true })
    if (_err) return _err.status && showTip('用户信息加载失败')
    this.setData({
      mask: false,
      checked: false,
      applicantIdCard,
      applicantName,
      applicantPhone,
      applicantIdType,
      code_index: applicantIdType ? Math.max((await this.p_code).map(({ id }) => id).indexOf(applicantIdType), 0) : 0
    })
    if (this.data.flag) return
    const dep_list = await get_auth(reservationServiceList, null, { loginTip: false });
    if (dep_list._err) return dep_list._err.status && showTip('部门列表加载失败')
    this.setData({ dep_list: [t, ...dep_list.map(({ deptName: name, deptUnid: id, serviceList: list }) => ({ id, name, list: [t, ...list.map(({ UNID: id, serviceName: name }) => ({ id, name }))] }))] })
    this._pickerChange('dep_index')
  },
  async send_verify_code() {
    let context = this, { data: { applicantPhone: phone, send_time } } = context;
    if (send_time) return
    if (!isPhone(phone))
      return showTip('您输入的电话格式不正确')
    let timeStamp = new Date().getTime() + '', sign = md5(md5(appKey).toUpperCase() + md5(timeStamp).toUpperCase()).toUpperCase()
    let { _err } = await get_auth(sendVerifCode, { phone, timeStamp, sign }, { loading: true, loadingMsg: '正在发送验证码...', })
    if (_err) return _err.status && showTip('验证码发送失败')
    showTip('发送成功')
    context._setData({ send_time: 60 });
    (function timer() {
      let { data: { send_time } } = context
      if (!send_time--) return
      context._setData({ send_time })
      setTimeout(timer, 1000)
    })()
  },
  async setHandleInfo(unid = '') {
    const { isCollect, preService: { serviceName = '', amStartTime = '', amEndTime = '', pmStartTime = '', pmEndTime = '', deptName = '', deptUnid = '' } = {}, _err } = unid ? await get_auth(guide, { unid, type: 2, }, { loading: true, loadingMsg: '事项信息获取中...' }) : { _err: { status: false } }
    this.setData({
      deptUnid,
      deptName,
      isCollect: isCollect == '1',
      serviceName,
      serviceUnid: unid,
      amTime: amStartTime && amEndTime ? `${amStartTime}-${amEndTime}` : '',
      pmTime: pmStartTime && pmEndTime ? `${pmStartTime}-${pmEndTime}` : ''
    })
    if (_err) return _err.status && showTip('获取信息失败')
    this._pickerChange('reservation_date_index', 1)
  },
  reserva_change({ currentTarget: { dataset: { val: reservationInterval } } }) {
    let { serviceUnid, [`${reservationInterval.toLowerCase()}Status`]: status } = this.data
    serviceUnid && status && this.setData({ reservationInterval })
  },
  async _pickerChange(_index, value = 0) {
    this.setData({ [_index]: value })
    let { dep_list, dep_index, serviceUnid, deptUnid, reservation_date_index, code_list } = this.data;
    switch (_index) {
      case 'dep_index':
        return this._pickerChange('matter_index')
      case 'matter_index':
        await this.setHandleInfo(dep_list[dep_index].list[value].id)
        return this._pickerChange('reservation_date_index', value && (reservation_date_index || 1))
      case 'reservation_date_index':
        let reservationDate = value ? date_list[value][0] : '', { amStatus = false, pmStatus = false } = value && await get_auth(reservationDateStatus, { reservationDate, deptUnid, serviceUnid }, { loading: true, loadingMsg: '预约信息获取中...' })
        return this.setData({ reservationDate, amStatus, pmStatus, reservationInterval: '' })
      case 'code_index':
        return this.setData({
          applicantIdType: code_list[value].id
        })
    }
  },
  async verify_code() {
    const msg = this.form_verify()
    if (msg) return showTip(msg)
    const { data } = this, { applicantPhone: phone, code } = data,
      { _err } = await get_auth(verifSmsCode, { phone, code }, { loading: true, loadingMsg: '信息验证中。。。', realNameTip })
    if (_err) return _err.status && showTip('短信验证码错误')
    this.setData({ mask: true, checked: false })
  },
  async formSubmit({ detail: { value } }) {
    const msg = this.form_verify(value)
    if (msg) return showTip(msg)
    let { id, _err } = await post_auth(reservationSave, value, { loading: true, loadingMsg: '信息提交中。。。', realNameTip })
    if (_err) return _err.status && showTip(`提交失败 ${_err.errmsg}`)
    goSuccess('reservation', id)
  },
  cancel() {
    this.setData({
      mask: false,
      checked: false
    })
  },
  async keep() {
    let
      {
        isCollect,
        serviceUnid,
        serviceName
      } = this.data
    if (!serviceUnid || lock) return
    lock = !this.setData({
      isCollect: !isCollect
    })
    let [req, url] = isCollect ? [get_auth, delCollect] : [post_auth, addCollect],
      { _err } = await req(url, {
        type: 2,
        serviceUnid,
        serviceName,
      })
    if (_err) {
      _err.status && showTip(`${isCollect ? "取消" : ""}收藏失败`)
      this.setData({
        isCollect: isCollect
      })
    }
    lock = false
  },
  checkboxChange({ detail: { value: [checked] } }) {
    this.setData({
      checked
    })
  },
  inputChange,
  pickerChange,
  navigateBack
})