// pages/rechargeDetail/index.js
import { getRechargeDetail } from "../../service/recharge";
import { alertError, alertInfo, loadingFunc, getFileName } from "../../utils/index";
import { getRechargeOperateType, getRechargeOperateWay } from "../../utils/data";
import request from "../../utils/request"
const { OK } = request
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id } = options;
    loadingFunc(async () => {
      await this.init(id)
    })
  },
  async init(id) {
    const { code, message, data } = await getRechargeDetail(id)
    if (code !== OK) {
      alertInfo(message)
      return;
    }
    this.setData({
      detail: { 
        ...data, 
        way: getRechargeOperateWay(data.way), 
        type: getRechargeOperateType(data.type),
        fileList: data?.images ? [{
          url: data.images, name: getFileName(data.images)
        }] : []
      }
    })
  },
  record() {
    const { detail } = this.data;
    if (detail.orderStatus === 1) {
      alertInfo("审核中的充值不能开收据")
      return;
    }
    if (detail.orderStatus === 2) {
      alertInfo("已退回的充值不能开收据")
      return;
    }
    const handleDownload = () => {
      return new Promise((resolve, rej) => {
     
        const result = wx.getAccountInfoSync();
        const { envVersion } = result.miniProgram;
        let api = ""
        switch (envVersion) {
          // 开发版
          case 'develop':
            // api = `http://localhost:9001`;
            // api = `https://zgd.hbhcbn.com/recharge-print-api`;
            api =  `https://zgd.hbhcbn.com/recharge-print-api-test`;
            break;
          // 体验版
          case 'trial':
            api =  `https://zgd.hbhcbn.com/recharge-print-api-test`;
            // api = `https://zgd.hbhcbn.com/recharge-print-api`;
            break;
          // 正式版
          case 'release':
            api = `https://zgd.hbhcbn.com/recharge-print-api`;
            break;
        }
        wx.downloadFile({
          url: `${api}/${detail.id}`,
          success: (res) => {
            if (res.statusCode === 200) {
              if (!res.tempFilePath) {
                alertInfo("获取文件失败")
                rej()
                return;
              }
              if (res.tempFilePath.endsWith(".json")) {
                alertInfo("下载文件失败")
                return;
              }
              // const fs = wx.getFileSystemManager()
              // const newPath = `${wx.env.USER_DATA_PATH}/收据-${detail.time.slice(0, 10)}.pdf`
              // fs.rename({
              //   oldPath: res.tempFilePath,
              //   newPath: newPath,
              //   success(r) {
                  wx.openDocument({
                    filePath: res.tempFilePath,
                    fileType: [ "pdf"], // 3. 这个必须写合法类型，不然下载不了 ！！！
                    showMenu: true,
                    success: function (res) {
                      resolve()
                    },
                    fail: function (e) {
                      alertError("打开失败")
                      console.log('打开失败错误为', e)
                      rej()
                    }
                //   });
                // },
                // fail(res) {
                //   console.error(res)
                //   alertInfo("下载失败")
                //   rej()
                // }
              })
              
              
            }
          }
        })
      })
    }
    loadingFunc(async () => {
      await handleDownload();
    })
  },
  back() {
    wx.navigateBack();
  },
})