// pages/piano/cropper/cropper.js

const { BtCmd } = require('../../../devices/bluetooth/bt_cmd');
import EventManager from '../../../utils/event_bus'
import { EnumCmdEvent, CmdEvent } from '../../../devices/cmd_key_event';
const { BtHelper } = require('../../../devices/bt_helper');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: "",
    width: 300,//宽度
    height: 300,//高度

    max_width: 300,
    max_height: 300,
    disable_rotate: true, //是否禁用旋转
    disable_ratio: true, //锁定比例
    limit_move: true, //是否限制移动
    showProgress: false,
    _imageBuffer: null,
    progress: 0,
  },
  cropper: null,


  // 将 RGBA 数据转换为 RGB565 格式
  RGBAtoRGB565(data) {
    const rgb565Array = new Uint16Array(data.length / 4);

    for (let i = 0; i < data.length; i += 4) {
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      // 转换为 RGB565
      const rgb565 = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
      rgb565Array[i / 4] = rgb565;
    }

    return rgb565Array;
  },

  // 保存为 .bin 文件
  saveAsBinFile(data, width, height) {
    const arrayBuffer = data.buffer;

    wx.getFileSystemManager().writeFile({
      filePath: `${wx.env.USER_DATA_PATH}/image_rgb565_${width}x${height}.bin`,
      data: arrayBuffer,
      encoding: 'binary',
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
        });
      },
      fail: (err) => {
        console.error('文件保存失败：', err);
      },
    });
  },
  cropperload(e) {
    console.log('cropper加载完成');
  },
  upload() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success(res) {
        wx.showLoading({
          title: '加载中',
        })
        const tempFilePaths = res.tempFilePaths[0];
        //重置图片角度、缩放、位置
        that.cropper.imgReset();
        that.setData({
          src: tempFilePaths
        });
      }
    })
  },
  loadimage(e) {
    wx.hideLoading();
    console.log('图片', e);
    this.cropper.imgReset();
  },
  clickcut(e) {
    console.log("clickcut:", e.detail);
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url] // 需要预览的图片http链接列表
    })
  },
  cancel() {
    wx.navigateBack({
      delta: -1
    })
  },
  submit() {
    let _this = this
    wx.showLoading({
      title: '图片裁剪中',
    })
    this.cropper.getImg((obj) => {
      // app.globalData.imgSrc = obj.url;
      console.log("裁剪图片:", obj);
      _this.readLocalFileAndConvertToBase64(obj.url);
    });
  },
  // 读取本地文件并转换为 Base64 字符串
  readLocalFileAndConvertToBase64(filePath) {
    const fs = wx.getFileSystemManager();
    let _this = this;
    fs.readFile({
      filePath: filePath,
      encoding: 'base64',
      success: (res) => {
        // const base64Data = 'data:image/png;base64,' + res.data;
        let rgbData = _this.RGBAtoRGB565(res.data)
        console.log("转换rgb:", rgbData.length)
        _this.data._imageBuffer = rgbData;
        wx.hideLoading();
        wx.showLoading({
          title: '开始传输图片',
        })
        _this.startImage();
      },
      fail: (err) => {
        console.error('读取文件失败：', err);
      }
    });
  },

  startImage() {
    BtHelper.getInstance().sendData(BtCmd.wallPaper(1));
  },
  startSendImage(imageBuffer) {
    if (imageBuffer == null) {
      wx.showToast({
        title: '图片裁剪失败',
        icon: 'none'
      })
      _this.endImage(2)
      return;
    }
    _this.sendImage(imageBuffer, 0)
    // }
  }, sendImage(imageBuffer, index) {
    let _this = this

    if (index >= chunkSize) {
      _this.endImage(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("发送图片数据:", sendImage)
      _this.updateProgress(next, total);
      if (res) {
        _this.sendImage(imageBuffer)
      } else {
        wx.showModal({
          title: '图片上传失败了',
          showCancel: false
        })
      }
    })

  },
  endImage(value) {
    BtHelper.getInstance().wallPaper(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) {
    console.log(options.param)
    // let json = JSON.parse(options.param)

    this.cropper = this.selectComponent("#image-cropper");
    this.cropper.imgReset();
    // this.setData({
    //   scr:json,
    // })
    this.upload(); //上传图片

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

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

          if (otaCmd === 1 && kind == 1) {
            // 开始发送
            _this.sendImage(_this.data._imageBuffer)
            _this.startProgress()
          } else if (otaCmd === 0 && kind == 1) {
            // 发送结束
            _this.endImage(0)
          } else if (kind == 0) {
            wx.hideLoading()
            wx.showModal({
              title: '图片上传失败了',
              showCancel: false
            })
          }
          break;
        default:
          break;
      }
    }, this)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    EventManager.removeNotification(CmdEvent.eventName, this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})