const { BtHelper } = require("../../devices/bt_helper");
import { EnumCmdEvent, CmdEvent } from '../../devices/cmd_key_event';
import EventManager from '../../utils/event_bus'
import route_util from '../../utils/route_util';
import route_constant from '../../utils/route_constant.js';
import { BtCmd } from '../../devices/bluetooth/bt_cmd.js';
import strings from '../../utils/strings.js';
const {
  deviceVersion
} = require('../../request/deviceListRequest')

// pages/OTA/ota.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //
      title: '固件信息',
    },
    device: {},
    _otaData: {},
    hasNewVersion: false,
    progress: 0, // 进度条初始值
    otaStatus: 0,
    buttonTips: "固件更新",
    _chunks: [],
    progressPercent: 0,
    progress: 0,
    progressTextLeft: "0%",
    _timer: null,
  },
  checkOtaVersion(device) {
    let _this = this;
    device.clientType = "MW-S2"
    _this.setData({
      device: device,
    })
    deviceVersion(device.clientType, device.connectType, device.version ?? "1.0.0").then(res => {
      console.log("OTA2：", res);
      let updateData = res ?? {};

      let hasNewVersion = updateData.isEnforcement === 1 || updateData.isEnforcement === 2;
      updateData.hasNewVersion = hasNewVersion;
      _this.data._otaData = updateData;
      _this.setData({
        hasNewVersion: hasNewVersion
      });
    })
  },

  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;
      case 5:
        this.setData({
          otaStatus: 4,
          buttonTips: "更新完成"
        });
        break;
      default:
        break;
    }

  },
  startOtaTap() {

    // this.goToWifi()
    // return;
    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;
    }
    if (this.data.otaStatus != 0) {
      console.log("没有可升级的固件2")
      return;
    }

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

        }

        if (res.confirm) {
          wx.showLoading({
            title: '升级设备中，请稍后',
          })
          _this.sendOtaCmd(1)

          // _this.startDownloadFile()
          // _this.downloadOtaFile(_this.data._otaData.url ?? "")
        }
      }
    })
    // const btHelper = BtHelper.getInstance();
    // btHelper.ota(this.data._otaData.file_url)

  },
  goToWifi() {
    route_util.jump(route_constant.setWifi)
  },
  sendUrlData() {
    let url = this.data._otaData.url ?? ""
    let codeUrl = BtCmd.stringToUint8Array(url)
    BtHelper.getInstance().otaUrl(codeUrl);
  },

  // 读取文件废弃代码
  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;
    _this.setOtaStatus(2);

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

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

        } else {
          _this.downloadOtaFile(urlPath, localPath)
        }
      }, 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);

          // 将下载的文件移动到本地路径
          fs.rename({
            oldPath: filePath,
            newPath: localPath,
            success: () => {
              wx.showToast({
                title: '文件下载成功',
              });
              _this.readFile(localPath);
            },
            fail: (err) => {
              _this.setOtaStatus(4);

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

    if (!localFilePath) {
      wx.showToast({
        title: '下载文件为空',
      });
      return;
    }
    wx.showLoading({
      title: '开始传输文件',
    })
    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);
        _this.setOtaStatus(4);
      }

    });
  },
  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.sendOtaCmd(1)
    // this.startSendOtaData()
  },

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

    if (length === 0) {
      wx.showToast({
        title: '下载文件失败',
        icon: 'none'
      })
      _this.sendOtaCmd(2)
      return;
    }
    _this.sendOtaData(this.data._chunks, 0)
    // }
  }, sendOtaData(imageBuffer, index) {
    let _this = this

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


    let total = imageBuffer.length
    let next = index + chunkSize;
    const chunk = imageBuffer.slice(index, next);
    // todo 改成设备wifi下载
    // 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
    //     })
    //   }
    // })

  },
  sendOtaCmd(value) {
    BtHelper.getInstance().otaCmd(value)
    if (value == 0) {
      this.setOtaStatus(0);
    } else {
      // this.setOtaStatus(4);
    }
  },

  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,
      });
    }
  },
  otaSuccess() {

    var pages = getCurrentPages();
    var length = pages.length;
    var currentPage = pages[length - 1];
    console.log("currentPage==", currentPage.route)
    if (currentPage.route == "pages/setWifi/setWifi") {
      console.log("currentPage==222", currentPage.route)
      currentPage.wifiPageSuccess()
    }
    wx.hideLoading();
    // 流程成功
    wx.showModal({
      title: '设备开始升级中，请等待',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          route_util.goBackHomePage();
        }
      }
    })
  },
  otaFailure() {
    wx.hideLoading();
    // 流程失败
    wx.showModal({
      title: '设备升级失败了',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          // 
        }
      }
    })
  },
  addNotification() {
    let _this = this;
    EventManager.addNotification(CmdEvent.eventName, function (event) {
      let name = event.cmdEvent;
      let kind = event.heiJiaoKind;
      // 74，1，1是wifi连接成功，74，0 2连接wifi失败/没有wifi。   
      // 发送url给你后，你回：74 0 1是流程成功，74 0 3是流程失败。
      let otaCmd = event.otaCmd;
      console.log("OTA页：", otaCmd, kind, name)

      switch (name) {
        case EnumCmdEvent.otaCmd:

          if (otaCmd === 1 && kind == 1) {
            wx.showLoading({
              title: '正在下载ota文件...',
              mask: true
            });
            // 设备收到开启OTA的回复，发送url
            _this.sendUrlData()
          } else if (otaCmd === 0 && kind == 2) {
            wx.hideLoading();
            // 去设置wifi界面
            _this.goToWifi()
          } else if (otaCmd === 0 && kind == 3) {
            _this.otaFailure()
          } else if (otaCmd === 0 && kind == 1) {
            _this.otaSuccess()
          }
          else if (kind == 0) {

          }
          break;
        case EnumCmdEvent.otaUrl:
          // 小程序发：0x75,  0
          if (otaCmd === 1 && kind == 1) {
            // _this.sendOtaCmd(0)
            _this.otaSuccess()
            // BtHelper.getInstance().otaUrl(BtCmd.stringToUint8Array(_this.data._otaData.url))
          } else if (otaCmd === 0 && kind == 3) {
            wx.showModal({
              title: 'OTA升级失败，请重启设备再试试吧',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          } else {
            _this.otaFailure()
          }
          break;
        case EnumCmdEvent.otaWifi:
          //0x76 
          wx.hideLoading()
          // 0x76, 发送wifi成功
          if (otaCmd === 1 && kind == 1) {
            wx.showLoading({
              title: 'wifi连接成功，正在下载ota文件...',
              mask: true
            });
            _this.sendUrlData()
          } else if (otaCmd === 0 && kind == 3) {
            wx.showModal({
              title: 'OTA升级失败，请重启设备再试试吧',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          } else {
            // wifi失败
            _this.otaFailure()
          }
          break;
        case EnumCmdEvent.onoffline:
          let state = event.commonValue
          if (event.deviceId === _this.data.device.deviceId) {
            _this.data.device.state = state
          }
          wx.hideLoading()
          break;
        case EnumCmdEvent.version:
          _this.data.device.version = event.version;
          console.log("OTA1：", event.version)

          _this.checkOtaVersion(_this.data.device);
          break;
      }
    }, _this)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let param = JSON.parse(options.param)
    console.log("OTA界面：", param)
    // let otaData = param.otaData
    let device = param.device
    device.mac = strings.isEmpty(device.mac) ? device.deviceId : device.mac
    this.setData({
      device: device,
      isShowOta: device.clientType === 'MW-S2'
    })
    const btHelper = BtHelper.getInstance();
    let isShowOta = device.clientType === 'MW-S2'
    if (isShowOta) {
      btHelper.getVersion()
    }

    this.addNotification()
  },
  onUnload() {
    console.log("移除OTA通知")
    EventManager.removeNotification(CmdEvent.eventName, this)
  },

})