// pages/my/my.ts
const app = getApp<IAppOption>()
import { bindPhoneList, phoneChose } from "../../apis/consumer";
import { info, cleanPhoneDate, labelStatistics, getCleanReturn } from "../../apis/phone";
import { list } from "../../apis/phone";
import { sysConfig } from "../../apis/config";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    dialogRecords: false,
    dialogAddReport: false,
    dialogInvite: false,
    dialogShare: false,
    dialogSwitchAccount: false,
    dialogCommentRecord: false,
    dialogTagRecord: false,
    commentRecordList: [],
    visible: false,
    dialogClear: false,
    dialogGoPay: false,
    form_phone: '',
    form_name: ''
  },
  handleTagRecord() {
    const { checkCondition } = this.data
    const size = this.data.userInfo.evaluatedTimes
    if (size < checkCondition) {
      this.setData({
        dialogRecords: true
      })
    } else {
      this.setData({
        dialogTagRecord: true
      })
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      })
      this.getTagRecord()
    }
  },
  dialogTagRecordClose() {
    this.setData({
      dialogTagRecord: false
    })
  },
  getTagRecord() {
    labelStatistics(this.data.userInfo.phone).then(res => {
      // console.log(res);
      let total = 0;
      res.d.map(item => {
        total = total + Number(item.contentCount)
      })
      this.setData({
        tagRecordList: res.d,
        tagRecordTotal: total
      })
    })
  },
  closeDialogShare() {
    this.setData({
      dialogShare: false
    })
  },
  showDialogShare() {
    this.setData({
      dialogShare: true,
      dialogRecords: false,
    })
  },
  getSysConfig() {
    sysConfig().then((res: any) => {
      this.setData({
        checkCondition: res.d.checkCondition,
        money: res.d.refreshAmount / 100
      })
    })
  },
  handleShare() {
    // wx.showShareImageMenu({  //分享给朋友
    //   // path,
    //   url: '/assets/images/my/icon_question.png',
    //   success: (res) => {
    //     console.log("分享成功：", res);
    //   },
    //   fail: (err) => {
    //     console.log("分享失败：", err);
    //     wx.showToast({
    //       title: "分享失败",
    //       duration: 2000
    //     })
    //   },
    // })
  },
  getBindPhoneList(phone: String) {
    bindPhoneList().then((res: any) => {
      // console.log('##', phone);

      // console.log(res.d.find((item: any) => item.phone === phone));

      this.setData({
        accountList: res.d,
        userInfo: res.d.find((item: any) => item.phone === phone)
      })
      this.getInfo()
    })
  },
  closeDialogSwichAccount() {
    this.setData({
      dialogSwitchAccount: false
    })
  },
  getInfo() {
    info({ phone: this.data.userInfo.phone, type: 0 }).then((res: any) => {
      this.setData({
        consumer: res.d
      })
    })
  },
  handleRecords() {
    const { checkCondition } = this.data
    const size = this.data.userInfo.evaluatedTimes
    if (size === 0) {
      this.setData({
        dialogShare: true
      })
    } else if (size < checkCondition) {
      this.setData({
        dialogRecords: true
      })
    } else {
      this.setData({
        dialogCommentRecord: true
      })
      wx.setPageStyle({
        style: {
          overflow: 'hidden'
        }
      })
      this.getCommentRecords()
    }
  },
  dialogRecordsClose() {
    this.setData({
      dialogRecords: false
    })
  },
  dialogAddReportShow() {
    this.setData({
      dialogAddReport: true
    })
  },
  dialogAddReportClose() {
    this.setData({
      dialogAddReport: false
    })
  },
  handleClear() {
    // this.selectComponent('#shadow2').show()
    this.setData({
      dialogClear: true,
      form_name: '',
      form_phone: this.data.userInfo.phone
    })
  },
  goPay() {
    // wx.navigateTo({
    //   url: `/pages/pay/pay?phone=${this.data.userInfo.phone}`
    // })
    let userInfo = wx.getStorageSync('userInfo');
    return new Promise((resolve, reject) => {
      cleanPhoneDate(this.data.form_phone, this.data.form_name).then((res: any) => {
        wx.requestPayment({
          ...res.d,
          success: (res: any) => {
            resolve(res)
            bindPhoneList().then((resp: any) => {
              wx.showToast({
                icon: 'none',
                title: '支付完成'
              })
              wx.setStorageSync('userInfo', resp.d.find((consumer: any) => consumer.id === userInfo.id))
            })
            // userInfo.evaluatedTimes = 0
            // wx.setStorageSync('userInfo', userInfo)
            // wx.navigateBack({
            //   delta: 1
            // })
            // this.getInfo()
            this.setData({
              dialogClear: false,
              dialogGoPay: false
            })
            getCleanReturn().then(response => {
              console.log(response);
              wx.navigateTo({
                url: `/pages/pay/pay?result=${response.d === 'true'}`
              })
              // }
            })
          },
          fail: (err: any) => {
            wx.showToast({
              icon: 'none',
              title: '支付失败, 请稍后再试!'
            })
            reject(err)
          }
        })
      })
    })
  },
  dialogInviteShow() {
    console.log('dialogInviteShow');

    this.setData({
      dialogInvite: true
    })
  },
  closeInvite() {
    console.log('closeInvite');
    this.setData({
      dialogInvite: false
    })
  },
  showDialogSwitchAccount() {
    this.setData({
      dialogSwitchAccount: true
    })
  },
  goReports(e: WechatMiniprogram.BaseEvent) {
    console.log('goReports', e);

    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/report/report?phone=${this.data.userInfo.phone}&id=${id}`,
    })
    this.setData({
      dialogAddReport: false
    })
  },
  accountChange(e: WechatMiniprogram.BaseEvent) {
    const { accountList } = this.data
    let accList = accountList.find((item: any) => item.id === e.currentTarget.dataset.id)
    this.setData({
      userInfo: accList,
      dialogSwitchAccount: false
    })
    wx.setStorageSync("userInfo", accList)
    phoneChose({ phone: accList.phone })
    this.getInfo()
  },
  goBind() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },
  share() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  showTagList() {
    this.setData({
      dialogCommentRecord: true
    })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
    this.getCommentRecords()
  },
  dialogCommentRecordClose() {
    this.setData({
      dialogCommentRecord: false
    })
    wx.setPageStyle({
      style: {
        overflow: 'auto'
      }
    })
  },
  getCommentRecords() {
    let payload = {
      current: 1,
      size: 99999,
      phone: this.data.userInfo.phone
    }
    list(payload).then(res => {
      console.log(res);
      this.setData({
        commentRecordList: res.d.records
      })
    })
  },
  show() {
    if (!this.data.realName) {
      this.setData({
        visible: true
      })
    }
  },
  close() {
    this.setData({
      visible: false
    })
  },
  goChrivc() {
    wx.navigateToMiniProgram({
      appId: 'wx1da91ccb94c17c99',
      path: 'pages/information/information',
      success(res) {
        // 打开成功
      }
    })
  },
  handleConfirmPay() {
    const { form_name, form_phone } = this.data
    if (!form_name) {
      wx.showToast({
        icon: 'none',
        title: '请输入您的真实姓名'
      })
      return
    }

    if (!form_phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入您的手机号码'
      })
      return
    }

    if (!/^1[3|4|5|7|8][0-9]{9}$/.test(form_phone)) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误!'
      })
      return
    }

    this.setData({
      dialogGoPay: true,
    })
  },
  handleCloseClear() {
    this.setData({
      dialogClear: false
    })
  },
  closeDialogGoPay() {
    this.setData({
      dialogGoPay: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.setData({
      now: Math.floor(new Date().getTime() / 1000)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      accountList: wx.getStorageSync('accountList')
    })
    this.getInfo()
    this.getSysConfig()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  sharePage() {
    // wx.showShareImageMenu({  //分享给朋友
    //   path:'/assets/images/my/sharePic.png',
    //   success: (res) => {
    //     console.log("分享成功：", res);
    //   },
    //   fail: (err) => {
    //     console.log("分享失败：", err);
    //     wx.showToast({
    //       title: "分享失败",
    //       duration: 2000
    //     })
    //   },
    // })
    // wx.showActionSheet({
    //   itemList: ['A', 'B', 'C'],
    //   success (res) {
    //     console.log(res.tapIndex)
    //   },
    //   fail (res) {
    //     console.log(res.errMsg)
    //   }
    // })
    // wx.onAppRoute((res) => {
    //   // console.log('route', res)
    //   let pages = getCurrentPages()
    //   let view = pages[pages.length - 1]
    //   if(view) {
    //     wx.showShareMenu({
    //       menus: ['shareAppMessage', 'shareTimeline'],
    //       success(res) {},
    //       fail(e) {}
    //     })
    //   }
    // })
    // console.log(2);
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
      success(res) {
        console.log(res);
      },
      fail(e) {
        console.log(e);
      }
    })
  },
  goShareTimeLine() {
    wx.navigateTo({
      url: "/pages/shareTimeLine/shareTimeLine?active=false"
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '邀请您到【众评】上对我做出印象评价',
          path: `/pages/searchResult/searchResult?phone=${this.data.userInfo.phone}`,
        })
      })
    })
    return {
      title: '邀请您到【众评】上对我做出印象评价',
      path: '/pages/login/login',
      promise
    }
  },
  // onShareTimeline() {
  //   const promise = new Promise(resolve => {
  //     setTimeout(() => {
  //       resolve({
  //         title: '你的印象评价是什么？',
  //         path: `/pages/shareTimeLine/shareTimeLine`,
  //       })
  //     })
  //   })
  //   return {
  //     title: '你的印象评价是什么？',
  //     path: '/pages/login/login',
  //     promise
  //   }
  // }
})
