/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-06-15 17:20:23
 * @LastEditors: zhangzhuobin 1093998108@qq.com
 * @LastEditTime: 2022-06-10 10:11:58
 */
import {
  fhConfirmOrder,
  fhSubmitOrder,
  fhPayNurseOrders
} from '../../../api/hospital/index'
import { fhGetNurseFeeRule } from '../../../api/store/index'
import { parseTime } from '../../../utils/parseTime'
import { Tips } from '../../../utils/util'
const { Loading, hLoading, getHospitalInfo } = getApp()

const pageOptions = {
  // 页面数据
  data: {
    isFirstOnShow: true, // 是否为首次执行onShow
    // 表单
    form: {},
    // 选中的护工的信息
    nurseInfo: {},
    // 时间配置
    timeOptions: {
      startTime: null,
      endTimeStart: null
    },
    // 护理的天数
    day: 0,
    // 订单总价
    total: 0,
    // 当前的收货地址
    address: null,
    // 加载中
    loading: false,
    // 最小小时数
    minHour: 0,
    // 过滤时间达到时间间隔
    timeFilter(type, options) {
      if (type === 'hour') {
        const currMinu = new Date().getMinutes()
        const currHour = new Date().getHours()
        return options.filter(option => {
          return currMinu > 45 ? option > currHour : option
        })
      }
      if (type === 'minute') {
        const currMinu = new Date().getMinutes()
        return currMinu > 45
          ? [0, 15, 30, 45]
          : options.filter(option => {
            return option % 15 === 0
          })
      }
      return options
    },
    // 是否显示费用规则弹窗
    rulesVisible: false,
    // 费用
    activityDesc: '',

    // 是否显示选中时间弹窗
    visibledTimePicker: false,
    // 时间格式配置
    showTimeConfig: {
      year: true,
      month: true,
      day: true,
      hour: true,
      minute: true,
      second: false
    }
  },
  // 页面载入时
  onLoad(e) {
    this.init(e)
  },
  // 页面初始化
  init(e) {
    this.hospitalIdInfo = getHospitalInfo()
    const hospitalAddress = wx.$getGlobalData('hospitalAddress')

    const tempInfo = wx.getStorageSync('tempPatientInfo') || {}
    const { name } = wx.$getGlobalData('patientInfo') || {}

    const { id, storeId } = e
    this.storeId = storeId
    const startTime = parseTime(new Date().valueOf(), '{y}-{m}-{d}')

    const currMinu = new Date().getMinutes()
    const currHour = new Date().getHours()

    this.setData({
      nurseInfo: e,
      form: {
        ...tempInfo,
        nurseId: id,
        name,
        ...this.hospitalIdInfo
      },
      'timeOptions.startTime': startTime,
      minHour: currMinu > 45 ? currHour + 1 : currHour,
      address: hospitalAddress
    })
    wx.nextTick(() => {
      this.getNurseFeeRule()
      this.storeId && this.confirmOrder()
    })
    wx.removeStorageSync('tempPatientInfo')
  },
  // 页面准备好时
  onReady() {
    this.addressModal = this.selectComponent('#address-modal')
    this.dateTimePicker = this.selectComponent('#date-time-picker')
  },
  // 页面显示时
  onShow() {
    const { isFirstOnShow } = this.data

    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false
      })
      return
    }
  },

  // 用户输入
  wardInput({ currentTarget: { dataset }, detail }) {
    let { value } = detail
    const { key } = dataset

    if (key === 'nurseStartTime') {
      if (value % 900000 !== 0) {
        value = Math.floor(value / 900000) * 900000 + 900000
      }
      value = parseTime(value, '{y}-{m}-{d} {h}:{i}')
    }

    this.setData(
      {
        [`form.${key}`]: value
      },
      () => {
        if (['nurseStartTime', 'nurseTotalDay'].includes(key)) {
          this.computedEndTime()
        }
      }
    )
  },

  // 计算时间
  computedDay() {
    const { form, nurseInfo } = this.data
    const { price } = nurseInfo
    const { nurseStartTime, nurseEndTime } = form
    if (!nurseEndTime || !nurseStartTime) return

    const diff =
      new Date(nurseEndTime.replace(/\.|\-/g, '/')).valueOf() -
      new Date(nurseStartTime.replace(/\.|\-/g, '/')).valueOf()
    const day = Math.ceil(diff / (1000 * 3600 * 24))

    if (day) {
      const total = price * day
      this.setData({
        day,
        total,
        'form.nurseTotalDay': day
      })
    }
  },

  // 计算结束时间
  computedEndTime() {
    const { form, nurseInfo } = this.data
    const { price } = nurseInfo
    const { nurseStartTime, nurseTotalDay } = form
    if (!nurseStartTime || !nurseTotalDay) return

    const endTime = parseTime(
      new Date(nurseStartTime.replace(/\.|\-/g, '/')).valueOf() +
      nurseTotalDay * 24 * 3600 * 1000,
      '{y}-{m}-{d} {h}:{i}'
    )
    const total = price ? price * nurseTotalDay : 0

    this.setData({
      'form.nurseEndTime': endTime,
      total,
      day: nurseTotalDay
    })
  },

  // 预览订单页
  async confirmOrder() {
    this.setData({
      loading: true
    })
    try {
      let { form } = this.data
      const { nurseEndTime, nurseStartTime } = form

      if (nurseEndTime) {
        form = {
          ...form,
          nurseEndTime: nurseEndTime + ':00'
        }
      }

      if (nurseStartTime) {
        form = {
          ...form,
          nurseStartTime: nurseStartTime + ':00'
        }
      }

      const { results } = await fhConfirmOrder(this.storeId, form)
      const { memberAddresses } = results
      const { id } = memberAddresses || {}

      this.computedEndTime()
      this.setData({
        address: memberAddresses,
        'form.addressId': id
      })
    } catch (e) {
      console.log('debug axios', e)
    }
    this.setData({
      loading: false
    })
  },

  // 校验是否可以提交
  validForm() {
    return new Promise((resolve, reject) => {
      const { form } = this.data
      const { nurseStartTime, nurseTotalDay, nurseId } = form
      if (!nurseStartTime) {
        Tips('请先选择护理开始时间')
        reject('请先选择护理开始时间')
      }
      if (!nurseTotalDay) {
        Tips('请先输入护理天数')
        reject('请先输入护理天数')
      }
      if (!nurseId) {
        Tips('请先选择护工')
        reject('请先选择护工')
      }
      resolve()
    })
  },

  // 提交订单
  async submitOrder() {
    Loading()
    try {
      await this.validForm()
      let { form } = this.data
      const { nurseEndTime, nurseStartTime } = form
      const {
        results: { orderId }
      } = await fhSubmitOrder(this.storeId, {
        ...form,
        nurseStartTime: nurseStartTime + ':00',
        nurseEndTime: nurseEndTime + ':00',
        ...this.hospitalIdInfo
      })
      this.payNurseOrders(orderId)
    } catch (e) {
      console.log('debug axios', e)
      hLoading()
    }
  },

  // 支付订单
  async payNurseOrders(orderId) {
    try {
      const { results } = await fhPayNurseOrders(orderId, { payType: 1 })
      this.wechatPay(results, orderId)
    } catch (e) {
      hLoading()
      console.log('debug axios', e)
    }
  },

  // 微信支付
  wechatPay(info, orderId) {
    const { prepayId } = info
    wx.requestPayment({
      ...info,
      package: prepayId,
      success: res => {
        Tips('支付成功')
        wx.$routerTo({
          url: '/package/good/successpage/successpage',
          type: 'reLaunch',
          query: {
            orderid: orderId,
            type: 'nurse'
          }
        })
      },
      fail: res => {
        Tips('取消支付')
        setTimeout(() => {
          wx.$routerTo({
            url: '/order/list/index',
            type: 'reLaunch',
            query: {
              from: 'pay',
              type: 'nurse'
            }
          })
        }, 1000 * 0.8)
      }
    })
  },

  // 展示选择地址
  showAddressModal() {
    this.addressModal.showModal()
  },

  // 选择一个地址
  addressChange({ detail }) {
    const { id } = detail

    this.setData({
      address: detail,
      'form.addressId': id
    })
  },

  // 展示时间选择
  showTimePicker() {
    this.dateTimePicker.showPopup()
    // this.setData({
    //   visibledTimePicker: true
    // })
  },

  // 跳转
  nav({ currentTarget: { dataset } }) {
    try {
      const { path, type } = dataset
      const { form } = this.data
      const { nurseStartTime, nurseTotalDay } = form

      if (type === 'chooseNurse') {
        if (!nurseStartTime) {
          Tips('请先选择护理开始时间')
          return
        }
        if (!nurseTotalDay) {
          Tips('请先输入护理天数')
          return
        }
        wx.setStorageSync('tempPatientInfo', this.data.form)
      }

      // type: "reLaunch",
      wx.$routerTo({
        url: path,
        query: {
          from: 'appointment'
        }
      })
    } catch (e) {
      console.error('跳转错误 error', e)
    }
  },

  // 获取护工费用规则
  async getNurseFeeRule() {
    try {
      if (!this.storeId) return
      const { results } = await fhGetNurseFeeRule(this.storeId)
      this.setData({
        activityDesc: results
      })
    } catch (e) {
      console.log('debug axios', e)
    }
  },

  // 展示费用规则弹窗
  showRuleModal() {
    if (!this.data.activityDesc) {
      wx.showToast({ title: '选择护工后才可查看收费规则', icon: 'none'})
      return
    }
    this.setData({
      rulesVisible: true
    })
  }
}

Page(pageOptions)
