// pages/invoicing/index.js
import { getInvoiceInfo, makeInvoice } from "../../service/invoice"
import { alertInfo, alertSuccess, loadingFunc } from "../../utils/index";
import request from '../../utils/request'
const { OK } = request

Page({

  /**
   * 页面的初始数据
   */
  data: {
    money: 0,
    tenement: "",
    tenementName: "",
    ids: [],
    count: 0,
    show: false,
    remark: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { money = 0, tenement, ids = '', count = 0, tenementName } = options;
    this.setData({ money, tenement, ids: ids.split(","), count, tenementName })
    this.getDetail();
  },
  async getDetail() {
    const { code, message, data } = await getInvoiceInfo()
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    if (!data?.id) {
      const user = wx.getStorageSync('user')
      if (user.isAdmin) {
        wx.showModal({
          title: '提示',
          content: '当前公司没有开票信息，请先前往开票信息页面编辑开票信息',
          confirmText: '前往编辑',
          cancelText: '取消',
          complete: (res) => {
            if (res.cancel) {
              wx.navigateBack()
            }
        
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/invoiceList/index?tab=2',
              })
            }
          }
        })
        return
      } else {
        wx.showModal({
          title: '提示',
          content: '当前公司没有开票信息，请联系管理员编辑完开票信息之后再开票',
          showCancel: false,
          confirmText: '返回',
          complete: (res) => {
            if (res.cancel) {
              wx.navigateBack()
            }
        
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
        return
      }
    }
    this.setData({ detail: {...data, }, remark: data.remark })
  },
  changeRemark(e) {
    this.setData({ remark: e.detail })
  },
  async onSubmit() {
    loadingFunc(async() => {
      const {ids = [], remark } = this.data;
      const tenement = wx.getStorageSync('tenement')
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/invoiceList/index?tab=1',
        })
      }, 500)
      const { code, message, data } = await makeInvoice({ ids, tenement: tenement.id, remark })
      if (code !== OK) {
        alertInfo(message)
        return;
      }
      alertSuccess("操作成功")
    })
  },
  changeShow() {
    this.setData({ show: true })
  },
})