import store from '../../store'
import create from '../../utils/create'
import fetch from '../../utils/http'
import { get as getApi } from '../../config/api'

const app = getApp()

create(store, {
  onShow() {
    wx.setNavigationBarTitle({
      title: '预约记录'
    })
  },
  onLoad () {
    const userInfo = app.globalData.UserInfo

    fetch({
      ...getApi('user.appointment', { openid: userInfo.openid }),
      query: { pageNum: 1, pageSize: 10 },
    }).then(({ data }) => {
      const list = data.records || []

      this.setData({ list })
    }).catch((err) => {
      wx.showToast({
        title: '获取列表失败',
        icon: 'error',
      })
    })
  },
  data: {
    list: [],
    DeleteIndex: null,
  },
  ShowDeleteItem(e) { // 长按显示删除
    this.setData({
      DeleteIndex: e.target.dataset.index
    })
  },
  ResetDeleteIndex() { // 重置删除状态
    this.setData({
      DeleteIndex: null
    })
  },
  DeleteItem() { // 确认删除逻辑
    const delId = this.data.DeleteIndex
    this.ResetDeleteIndex()

    const _self = this

    wx.showModal({
      title: '确认',
      content: '确认要删除当前记录?',
      success(res) {
        if (res.confirm) {
          
          fetch({
            ...getApi('user.delAppointment', { id: delId }),
          }).then(() => {
            const list = _self.data.list.filter(x => x.appointmentId !== delId)

            _self.setData({ list })
          }).catch((err) => {
            wx.showToast({
              title: '删除失败',
              icon: 'error',
            })
          })


        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})