// app.js
// 将属性加入相应类型对象中
import './utils/prototype/prototypeArray';
import './utils/prototype/prototypeObject';
import './utils/prototype/prototypeNumber';
import './utils/prototype/prototypeString';
import './utils/prototype/prototypeDatetime';
import './mixins/mixins.js';

// api/pages中的路由服务文件
const common = require('./api/pages/common/common.js');
const setting = require('./api/pages/other/setting.js');
const oauth = require('./api/pages/other/oauth.js');
const company = require('./api/pages/other/company.js');
const wechatPay = require('./api/pages/other/wechatPay.js');
const user = require('./api/pages/core/user.js');
const staff = require('./api/pages/mst/staff.js');
const staffRight = require('./api/pages/mst/staffRight.js');
const staffPurview = require('./api/pages/mst/staffPurview.js');
const settingValue = require('./api/pages/mst/settingValue.js');
const customer = require('./api/pages/core/customer.js');
const role = require('./api/pages/mst/role.js');
const roleFun = require('./api/pages/mst/roleFun.js');
const org = require('./api/pages/mst/org.js');
const roleSensitive = require('./api/pages/mst/roleSensitive.js');
const goodsBrand = require('./api/pages/mst/goodsBrand.js');
const goodsCategory = require('./api/pages/mst/goodsCategory.js');
const goodsSeries = require('./api/pages/mst/goodsSeries.js');
const unit = require('./api/pages/mst/unit.js');
const supplier = require('./api/pages/mst/supplier.js');
const warehouse = require('./api/pages/mst/warehouse.js');
const saleChannel = require('./api/pages/mst/saleChannel.js');
const goodsSku = require('./api/pages/mst/goodsSku.js');
const basicData = require('./api/pages/mst/basicData.js');
const customerMst = require('./api/pages/mst/customer.js');
const purchase = require('./api/pages/pur/purchase.js');


const account = require('./api/pages/mac/account.js');
const receiptPayment = require('./api/pages/mac/receiptPayment.js');
const payment = require('./api/pages/mac/payment.js');
const inbound = require('./api/pages/ivt/inbound.js');
const inboundOther = require('./api/pages/ivt/inboundOther.js');
const inboundProcessing = require('./api/pages/ivt/inboundProcessing.js');
// const inboundSaleReturn = require('./api/pages/ivt/inboundSaleReturn.js');
const inboundPurchaseReturn = require('./api/pages/ivt/inboundPurchaseReturn.js');
const outbound = require('./api/pages/ivt/outbound.js');
const outboundOther = require('./api/pages/ivt/outboundOther.js');
const outboundProcessing = require('./api/pages/ivt/outboundProcessing.js');
// const outboundPurchaseReturn = require('./api/pages/ivt/outboundPurchaseReturn.js');
const outboundSaleReturn = require('./api/pages/ivt/outboundSaleReturn.js');
const inventory = require('./api/pages/ivt/inventory.js');
const moneyAccount = require('./api/pages/mst/moneyAccount.js');
const intoReturn = require('./api/pages/ivt/intoReturn.js');
const intoReturnItem = require('./api/pages/ivt/intoReturnItem.js');
const cusFollow = require('./api/pages/mst/cusFollow.js');
const transfer = require('./api/pages/mac/transfer.js');
const order = require('./api/pages/sale/order.js');
const saleOutBound = require('./api/pages/ivt/saleOutBound.js');
const inboundReturn = require('./api/pages/ivt/inboundReturn.js');
const cusReceiptPayment = require('./api/pages/mac/cusReceiptPayment.js');
const menuFrequency = require('./api/pages/mst/menuFrequency.js');
const userMenuFrequency = require('./api/pages/mst/userMenuFrequency.js');
const comMenu = require('./api/pages/mst/comMenu.js');
const saleOutBoundReturn = require('./api/pages/ivt/saleOutBoundReturn.js');
const advertisement = require('./api/pages/mst/advertisement.js');
const check = require('./api/pages/ivt/check.js');
const freeze = require('./api/pages/ivt/freeze.js');
const otherReceivable = require('./api/pages/mac/otherReceivable.js');
const otherPayable = require('./api/pages/mac/otherPayable.js');
const inventoryAdjustment = require('./api/pages/ivt/inventoryAdjustment.js');

// api服务路由文件
var apiList = [common, oauth,setting, company, wechatPay,user, staff, staffRight, staffPurview, settingValue, customer, role, roleFun, org, roleSensitive, goodsBrand, goodsCategory, goodsSeries, unit, supplier, warehouse, saleChannel, goodsSku, basicData,customerMst,purchase,account,payment,
  receiptPayment,inbound,inboundOther,inboundProcessing,inboundPurchaseReturn,outbound,outboundOther,outboundProcessing,outboundSaleReturn,inventory,moneyAccount,intoReturn,intoReturnItem,cusFollow,order,transfer,saleOutBound,inboundReturn,cusReceiptPayment,menuFrequency,userMenuFrequency,comMenu,saleOutBoundReturn,advertisement,check,freeze,otherReceivable,otherPayable,inventoryAdjustment]

const util = require('./utils/util.js')
const baseMethod = require('./api/pages/baseMethod.js')
const baseRoute = require('./api/pages/baseRoute.js')
//初始化国际化语言设置
const LangUtils = require('./utils/LangUtils')
//app.js
const api = require('/utils/api.js');


// // 引入文件系统管理器模块
// const fs = wx.getFileSystemManager();
// // 要读取的文件夹路径
// const folderPath = '/api/pages'; // 将此处的'/path/to/folder'替换为实际的文件夹路径
// // 定义递归函数，用于读取指定目录下所有的.js文件
// function readJsFiles_old(dirPath) {
//   let returnFiles = []
//   console.log('files1',dirPath,fs);
//   // 读取当前目录下的文件列表
//   const files = fs.readdirSync(dirPath);
//   console.log('files2',files);
//   for (let i = 0; i < files.length; i++) {
//     const file = files[i];
//     // 构建完整路径
//     let fullpath = dirPath + '/' + file;

//     // 如果是js文件就返回
//     if (file.endsWith('.js')) {
//       // fullpath = '@' + fullpath
//       console.log('f1', fullpath);
//       let item = require(fullpath);
//       console.log('f2', item);
//       if (file != 'baseMethod.js' && file != 'baseRoute.js') {
//         item.name = file.replace('.js', '');
//         returnFiles.push(item);
//       }
//     } else if (fs.statSync(fullpath).isDirectory()) {
//       console.log('b3', fullpath);
//       // 如果是文件夹则递归调用自身处理子级文件夹
//       let returns = readJsFiles(fullpath);
//       returns.forEach(it => {
//         returnFiles.push(it);
//       })
//     }
//   }
//   return returnFiles;
// }

//自动更新对象
const updateManager = wx.getUpdateManager()

App({
  onLaunch() {
    console.log("onLaunch");
    // LangUtils.setTabBarLang();

    //自动定时检测是否有新版本
    this.checkHasUpdate();
  },


  /**
   *  检测是否有新版本
   */
  checkHasUpdate: function () {
    var _this = this;
    updateManager.onCheckForUpdate(function (res) {
      setTimeout(function () {
        // 请求完新版本信息的回调  
        if (res.hasUpdate && !_this.globalData.downLoadApp) {
          //有新版本，并且没下载过，才下载。不然会重复提示
          _this.downLoadApp();
        }
        _this.checkHasUpdate()
      }, 60000)
    })
  },


  /**
   * 下载新版本
   */
  downLoadApp() {
    var _this = this;
    _this.globalData.downLoadApp = true //下载标识改变，
    // 1.下载成功
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '检测到应用有新版本，是否现在加载最新版本？',
        cancelText: '稍后',
        success(res) {
          if (res.confirm) {
            // 2.新的版本已经下载好，用户确定后调用 applyUpdate 应用新版本并重启
            _this.updateApp();
          } else {
            wx.showModal({
              title: '提示',
              content: '点击下方导航“我的” - 点击版本号后面“箭头”按钮，即可进行手动加载最新版本',
              showCancel: false
            })
          }
        }
      })
    })

    // 下载失败
    updateManager.onUpdateFailed(function () {
      wx.showModal({
        title: '自动下载最新应用包失败',
        content: '请检查您的网络环境是否正常，或尝试结束微信进程后重新进入小程序。',
        showCancel: false
      })
    })
  },

  /**
   * 更新并重启应用
   */
  updateApp() {
    updateManager.applyUpdate()
  },


  globalData: {
    downLoadApp: false,
    userInfo: null,
    openid: null,
    unionid: null,
    sessionkey: null,
  },
})
try {
  // 调用readdirSync()方法读取文件夹内容
  // let files = readJsFiles(folderPath);
  let app = getApp();
  let routeUrl = {};
  let name = null;
  apiList.forEach(m => {
    // console.log('values',m,Object.values(m),Object.keys(m)[0],m['routeUrl']);
    app.globalData[Object.keys(m)[0]] = Object.assign(Object.values(m)[0], baseMethod.baseService)
    // // 如果没有路由，就建一个路由
    // if (!m['routeUrl']) {
    //   // m['routeUrl'] = {}
    //   // m['routeUrl'][m.name] = {}
    //   // // 加入共通路由
    //   // m['routeUrl'][m.name] = Object.assign(m['routeUrl'][m.name], baseRoute.routeUrl)
    // } else {
    //   util.objectMergeByMainJs(m['routeUrl'][m.name], baseRoute.routeUrl)
    // }
    // 必须有一个路由
    if (m['routeUrl']) {
      name = Object.keys(m['routeUrl'])[0];
      util.objectMergeByMainJs(m['routeUrl'][name], baseRoute.routeUrl)
    }
    if (name && name != 'common') { 
      routeUrl[name] = m['routeUrl'][name];
      // console.log('routeUrl',m,routeUrl,name,m['routeUrl'][name]);
    }
  })
  app.globalData['routeUrl'] = routeUrl;
  // 输出结果
  console.log('文件列表：', apiList, baseMethod, routeUrl);
  // 国际化的初始化
  LangUtils.initLang();
  let langSrc = LangUtils.getLangSrc()
  console.log('langSrc', langSrc);
  app.globalData['lang'] = { ...langSrc.items };
} catch (error) {
  console.error('读取文件夹失败：', error);
}

