const { BtHelper } = require("../../devices/bt_helper");
import { EnumCmdEvent, CmdEvent } from '../../devices/cmd_key_event';
import EventManager from '../../utils/event_bus'
// pages/OTA/ota.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //
      title: '固件信息',
    },
    device: {},
    otaData: {},
    btHelper: null,
    progress: 0, // 进度条初始值
    otaStatus: 0,
    buttonTips: "固件更新",
    _chunks: [],
    progressPercent: 0,
    progress: 0,
    progressTextLeft: "0%",
    _timer: null,
  },
  setOtaStatus(status) {
    switch (status) {
      case 0:
        this.setData({
          otaStatus: 0,
          buttonTips: "固件更新"
        });
        break;
      case 1:
        this.setData({
          otaStatus: 1,
          buttonTips: "下载升级包"
        });
        break;
      case 2:
        this.setData({
          otaStatus: 2,
          buttonTips: "开始更新"
        });
        break;
      case 3:
        this.setData({
          otaStatus: 3,
          buttonTips: "更新中..."
        });
        break;

      case 4:
        this.setData({
          otaStatus: 4,
          buttonTips: "更新失败，再试一次"
        });
        break;
      default:
        break;
    }

  },
  startOtaTap() {
    let online = this.data.device.state === "online"
    if (!online) {
      wx.showToast({
        title: '设备已经掉线了',
      })
      return;
    }

    let hasNewVersion = this.data.otaData.hasNewVersion ?? false
    if (!hasNewVersion) {
      wx.showToast({
        title: '没有可升级的固件',
      })
      return;
    }

    let _this = this
    wx.showModal({
      title: '有新固件可升级',
      content: _this.data.otaData.content ?? '提升体验，操作更流畅',
      cancelText: '以后再说',
      confirmText: '升级',
      complete: (res) => {
        if (res.cancel) {

        }

        if (res.confirm) {
          _this.startDownloadFile()
          // _this.downloadOtaFile(_this.data.otaData.url ?? "")
        }
      }
    })
    // const btHelper = BtHelper.getInstance();
    // btHelper.ota(this.data.otaData.file_url)

  },
  startDownloadFile() {

    var urlPath = this.data.otaData.url ?? "";

    var list = urlPath.split("/");
    // let cachePath = await PathUtil.getDownloadPath(fileName: list.last ?? 'OTAUpgrade.OTA');
    const fs = wx.getFileSystemManager();

    // 构建本地文件路径
    var localFilePath = list[list.length - 1];
    console.log(list, localFilePath)

    let _this = this;
    let localPath = `${wx.env.USER_DATA_PATH}/` + localFilePath
    // 判断文件是否存在
    fs.access({
      path: localPath,
      success(res) {
        console.log('文件已存在：', res);

        if (res) {
          // 有文件
          _this.readFile(localPath);

        } else {

        }
      }, fail(err) {
        // 文件不存在或其他错误
        console.log(err)
        // 文件不存在，开始下载
        _this.downloadOtaFile(urlPath, localPath)
      }
    }
    );
  },
  downloadOtaFile(urlPath, localPath) {
    let _this = this;
    // const fs = wx.getFileSystemManager();

    wx.downloadFile({
      url: urlPath, // 下载资源的URL
      success: (res) => {
        console.log('文件下载成功2', res);

        if (res.statusCode === 200) {
          // 下载成功，保存文件路径
          const filePath = res.tempFilePath;
          // _this.readFile(filePath);
          _this.readFile(filePath);

          // 将下载的文件移动到本地路径
          // fs.rename({
          //   oldPath: filePath,
          //   newPath: localPath,
          //   success: () => {

          //     // this.setData({
          //     //   localFilePath: localFilePath
          //     // });

          //     // 调用 OTA 更新方法
          //     // const btHelper = BtHelper.getInstance();
          //     // btHelper.ota(localFilePath);

          //     wx.showToast({
          //       title: '文件下载成功',
          //     });
          //     _this.readFile(localPath);
          //   },
          //   fail: (err) => {
          //     wx.showToast({
          //       title: '下载文件失败，检查下手机内存吧',
          //     });
          //     console.error('文件移动失败:', err);
          //   }
          // });
        } else {
          wx.showToast({
            title: '文件下载失败',
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '文件下载失败',
        });
        console.error('下载文件失败:', err);
      }
    });
  },
  readFile(localFilePath) {

    if (!localFilePath) {
      wx.showToast({
        title: '下载文件为空',
      });
      return;
    }
    wx.showLoading({
      title: '开始传输文件',
    })
    this.setOtaStatus(2);
    const fs = wx.getFileSystemManager();

    let _this = this;
    fs.readFile({
      filePath: localFilePath,
      encoding: 'base64', // 可以选择 'utf8' 或 'base64'
      success: (res) => {

        // const btHelper = BtHelper.getInstance();
        //   btHelper.ota(localFilePath);

        console.log('文件内容:', res.data.length);

        _this.startSend(res.data);
      },
      fail: (err) => {
        wx.showToast({
          title: 'OTA文件下载失败',
        });
        console.error('文件读取失败:', err);
      }
    });
  },
  startSend(data) {
    const chunkSize = 20; // 每次发送的数据块大小
    const chunks = [];
    for (let i = 0; i < data.length; i += chunkSize) {
      chunks.push(data.slice(i, i + chunkSize));
    }

    this.data._chunks = chunks;
    this.endOta(1)
    // this.startSendOtaData()
  },

  startSendOtaData() {
    let _this = this
    let length = this.data._chunks.length

    if (length === 0) {
      wx.showToast({
        title: '图片裁剪失败',
        icon: 'none'
      })
      _this.endOta(2)
      return;
    }
    _this.sendOtaData(this.data._chunks, 0)
    // }
  }, sendOtaData(imageBuffer, index) {
    let _this = this

    if (index >= imageBuffer.length) {
      _this.endOta(0)
      return;
    }
    let chunkSize = 20;


    let total = imageBuffer.length
    let next = index + chunkSize;
    const chunk = imageBuffer.slice(index, next);
    BtHelper.getInstance().wallPaperData(chunk, function (res) {
      console.log("发送OTA数据:", next)
      if (res) {
        _this.updateProgress(next, total);

        _this.sendOtaData(imageBuffer)
      } else {
        wx.showModal({
          title: 'OTA升级失败了',
          showCancel: false
        })
      }
    })

  },
  endOta(value) {
    BtHelper.getInstance().otaCmd(value)
  },

  startProgress() {
    this.setData({
      progress: 0,
      showProgress: true
    })
  },
  updateProgress(chunk, total) {
    let progress = chunk / total * 100;
    let _this = this
    if (progress >= 100) {
      _this.setData({
        progress: 0,
        showProgress: false,
        // showCropImg: false
      });
      wx.showToast({
        title: '图片上传成功',
      })
    } else {
      _this.setData({
        progress: progress,
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let param = JSON.parse(options.param)
    console.log("OTA界面：", param)
    let otaData = param.otaData
    let device = param.device
    this.setData({
      otaData: otaData,
      device: device,
      isShowOta: device.clientType === 'MW-S2(BLE)' || device.clientType === 'MW-S2'
    })

    let _this = this;
    EventManager.addNotification(CmdEvent.eventName, function (event) {
      let name = event.cmdEvent;
      console.log("OTA页0：", name, EnumCmdEvent.otaCmd, EnumCmdEvent.otaCmd === name)

      switch (name) {
        case EnumCmdEvent.otaCmd:
          let otaCmd = event.otaCmd;
          let kind = event.heiJiaoKind;
          console.log("OTA页：", otaCmd, kind)

          if (otaCmd === 1 && kind == 1) {
            wx.hideLoading();
            // 开始发送
            _this.startSendOtaData()
          } else if (otaCmd === 0 && kind == 1) {
            // 发送结束
            _this.endOta(0)
          } else if (kind == 0) {
            wx.hideLoading()
            wx.showModal({
              title: 'OTA升级失败了',
              showCancel: false
            })
          }
          break;
      }
    }, this)
  },
  onUnload() {
    EventManager.removeNotification(CmdEvent.eventName, this)
  },

})