import { loginStatusPage, post } from '@/utils/https';
import {
  getAuthInfo,
  priceRetentionDigits,
  sleep,
  toastSuccess,
  toNumber,
  toObject,
} from '@/utils/util';
import dayjs from 'dayjs';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    params: {} as any,
    record: {} as any,
    datetimeVisible: false,
  },
  showPicker() {
    this.setData({ datetimeVisible: true });
  },
  hidePicker() {
    this.setData({ datetimeVisible: false });
  },
  onConfirm(e: any) {
    this.data.params.bill_date = e.detail.value;
    this.setData({
      datetimeVisible: false,
      params: this.data.params,
    });
  },
  handleLogin(e: any) {
    this.setData({ isLogin: e.detail });
    if (e.detail) {
      this.init();
    }
  },
  init() {
    const eventChannel: any = this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel?.on('saleOrderPay', (res: any) => {
        const data = toObject(res.data);
        const { un_payed_amount, order_no } = data;
        // console.log(data);
        wx.setNavigationBarTitle({ title: `${order_no} 收付款` });
        this.data.params.order_no = order_no;
        this.data.params.bill_date = dayjs().format('YYYY-MM-DD HH:mm:ss');

        this.data.params.amount = priceRetentionDigits(toNumber(un_payed_amount));
        this.data.params.operator = toNumber(wx.getStorageSync('user_id')) || undefined;
        this.setData({
          params: this.data.params,
          record: data,
        });
      });
    }

    this.setData({ authInfo: getAuthInfo() });
  },
  accountOk(e: any) {
    this.data.params.last_account_id = e.detail?.account_id;
    this.setData({
      params: this.data.params,
    });
    // console.log(e);
  },
  accountDefault(e: any) {
    this.data.params.last_account_id = e.detail?.account_id;
    this.setData({
      params: this.data.params,
    });
    // console.log(e);
  },
  onPriceInput(e: any) {
    this.data.params.amount = e.detail.value;
  },
  onCommentInput(e: any) {
    this.data.params.comments = e.detail.value;
  },
  onPay() {
    const { record, params } = this.data;
    const data = {
      order_no: record.order_no,
      bill_date: params.bill_date,
      amount: params.amount,
      operator: params.operator,
      last_account_id: params.last_account_id,
      comments: params.comments || '',
    };
    post('Orders/orderPay', data).then(() => {
      toastSuccess('保存成功');
      sleep(() => {
        wx.navigateBack();
      }, 1000);
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(_options) {
    loginStatusPage(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {},
});
