/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-06-09 23:18:37
 * @LastEditors: HJ
 * @LastEditTime: 2021-07-27 13:42:59
 */
import { status, nurseOrderStatusMap } from '../../utils/enumMap'
import { fhPayNurseOrders, fhCancelNurseOrders } from '../../api/hospital/index'
import { fhReminderOrder } from '../../api/order/index'
import { Tips } from '../../utils/util'
const baseUrl = require('../../api/index.js').config
const order = require('../../api/order')
const { Loading, hLoading } = getApp()
const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true
  },
  behaviors: [],
  properties: {
    value: {
      type: Object,
      value: {}
    },
    orderType: {
      type: String,
      value: null,
      observer(type) {
        this.setData({
          orderStatus: type === 'patient' ? status : nurseOrderStatusMap
        })
      }
    },
    listInfo: {
      type: String,
      value: 'all'
    }
  },
  observers: {
    'value,orderStatus'(value, orderStatus) {
      if (value && orderStatus) {
        const { payTime } = value
        if (payTime) this.computedReminder(value)
        const orderStatusText = this.compoutedStatusText(value)
        this.setData({
          orderStatusText
        })
      }
    }
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    // 订单状态
    orderStatus: null,
    // 订单状态文案
    orderStatusText: '',
    funs: [],
    // 是否显示催单按钮
    isShowReminderBtn: false
  },
  // 组件方法
  methods: {
    init() {},
    // 打电话
    ringUp({ currentTarget: { dataset } }) {
      wx.makePhoneCall({
        phoneNumber: dataset.phone
      })
    },
    // //去支付
    goPaid({ currentTarget: { dataset } }) {
      const { id } = dataset
      Loading()
      this.setData(
        {
          orderid: id
        },
        () => {
          this.data.orderType === 'patient'
            ? this.payWechat(id)
            : this.payNurseOrders()
        }
      )
    },
    // 微信支付
    payWechat(id) {
      var that = this
      var memberId = wx.getStorageSync('memberId')
      order.takePayment(
        baseUrl.waimaiUrl + `/client/${memberId}/order/${id}/pay`,
        {},
        {
          payType: 1
        },
        '加载中',
        function(res) {
          hLoading()
          var result = res.results
          that.evokeWechatPay(result)
        },
        function(err) {
          hLoading()
          wx.showToast({
            title: '支付失败'
          })
          that.setData({
            payflag: false
          })
        }
      )
    },
    // 去反馈
    toEval({ currentTarget: { dataset } }) {
      const { item } = dataset
      try {
        wx.setStorageSync('j_feedback', item)
        wx.navigateTo({
          url: '/package/good/feedback/feedback'
        })
      } catch (e) {
        wx.showToast({
          title: '数据异常，请重试',
          icon: 'none'
        })
      }
    },
    // 跳转商家门店
    jumpSaleroom({ currentTarget: { dataset } }) {
      if (this.data.orderType !== 'patient') {
        this.nav({ currentTarget: { dataset } })
        return
      }
      const { storeid } = dataset
      wx.setStorageSync('storeid', storeid)
      wx.navigateTo({
        url: '/store/pages/lunch/index'
      })
    },
    // 跳转到详情
    nav({ currentTarget: { dataset } }) {
      const { orderId } = dataset
      wx.$routerTo({
        url: '/pages/order/detail/index',
        query: {
          orderId,
          type: this.data.orderType,
          from: this.data.listInfo
        }
      })
    },
    // 支付护工订单
    async payNurseOrders() {
      try {
        const { results } = await fhPayNurseOrders(this.data.orderid, {
          payType: 1
        })
        this.evokeWechatPay(results)
      } catch (e) {
        console.log('debug axios', e)
        hLoading()
      }
    },
    // 取消护工订单
    async fhCancelNurseOrders() {
      try {
        await fhCancelNurseOrders(this.data.orderid)
        Tips('取消订单成功')
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/order/list/index'
          })
        }, 1000 * 1.2)
      } catch (e) {
        console.log('debug axios', e)
      }
    },
    // 唤起微信支付
    evokeWechatPay(info) {
      hLoading()
      const { prepayId } = info
      wx.requestPayment({
        ...info,
        package: prepayId,
        success: res => {
          wx.showToast({
            title: '支付成功',
            duration: 1000,
            mask: true,
            success: () => {
              setTimeout(() => {
                wx.$routerTo({
                  url: '/package/good/successpage/successpage',
                  type: 'reLaunch',
                  query: {
                    type: this.data.orderType,
                    orderid: this.data.value.orderId,
                    price: this.data.value.totalPrice
                  }
                })
              }, 1000) //延迟时间
            }
          })
        },
        fail: res => {
          hLoading()
          this.setData({
            payflag: false
          })
          wx.showToast({
            title: '取消支付',
            icon: 'error',
            duration: 800,
            success: function() {}
          })
        }
      })
    },
    // 计算当前订单实际状态
    compoutedStatusText(info) {
      const { orderStatus, refundStatus } = info
      const key = (refundStatus !== 603 && refundStatus) || orderStatus
      return this.data.orderStatus[key]
    },
    // 催单
    async takeReminder({ currentTarget: { dataset } }) {
      const { id } = dataset
      await fhReminderOrder(id)
      Tips('催单成功')
    },
    // 计算是否展示催单按钮
    computedReminder(value) {
      if (this.data.orderType === 'patient') {
        const { payTime, orderStatus } = value
        const payTimeStamp = new Date(payTime).valueOf()
        const nowTimeStamp = new Date().valueOf()
        const showFlag = [4, 3, 5, 102, 201, 202, 301].includes(orderStatus)
        if (nowTimeStamp - payTimeStamp > 30 * 60000 && showFlag) {
          this.setData({
            isShowReminderBtn: true
          })
        }
      }
    }
  },
  // 组件生命周期
  lifetimes: {
    created() {},
    attached() {
      this.init()
    },
    ready() {},
    moved() {},
    detached() {}
  },
  definitionFilter() {},
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data

      // show事件发生前，页面不是处于隐藏状态时
      if (!isPageHidden) {
        return
      }

      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true
      })

      // 清除定时器等操作
    },
    // 页面尺寸变化时
    resize() {}
  }
}

Component(componentOptions)
