const fileManager = wx.getFileSystemManager();
var app = getApp() 
// canvas 全局配置
var context = null; // 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;
var arrx = [];
var arry = [];
var arrz = [];
var canvasw = 0;
var canvash = 0;
//获取系统信息
wx.getSystemInfo({
  success: function (res) {
    canvasw = res.windowHeight * 1.2; //设备宽度
    // canvash = res.windowWidth * 7 / 15;
    canvash = res.windowWidth * 1.2;
  }
});
//注册页面
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    signFlag: false,
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    context = wx.createCanvasContext('canvas');
    context.setFillStyle('#fff')
    context.fillRect(0, 0, canvasw * 2, canvash)
    context.draw(true)
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  onShow() {
    arrx = [];
    arry = [];
    arrz = [];
    if(context) {
        this.cleardraw()
    }
  },
 
  isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    }
  },
 
  canvasIdErrorCallback: function (e) { },
  //开始
  canvasStart: function (event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
    //context.moveTo(event.changedTouches[0].x, event.changedTouches[0].y);
 
  },
  //过程
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
      // context.lineTo(event.changedTouches[0].x, event.changedTouches[0].y);
      // context.stroke();
      // context.draw()
    };
 
    this.setData({
      signFlag: true,
    })
 
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };
 
    };
 
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
    context.draw(true);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  cleardraw: function () {
    //清除画布
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw * 10, canvash);
    context.draw(true);
  },
  //导出图片
  getimg: function () {
    let that = this
    if (arrx.length == 0) {
      wx.showModal({
        title: '提示',
        content: '签名内容不能为空！',
        showCancel: false
      });
      return false;
    };
    console.log(that.data.signFlag);
    if (!that.data.signFlag) {
      wx.showModal({
        title: '提示',
        content: '签名内容不能为空！',
        showCancel: false
      });
      return false;
    }
    //生成图片
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: function (res) {
        //将图片转换为base64 的格式
        // let signImage = 'data:image/jpg;base64,' + fileManager.readFileSync(res.tempFilePath, 'base64');
        let signImage = res.tempFilePath;
        //其他
        that.uploadFilePromise(signImage).then(res => {
            const tempUrl = JSON.parse(res).data
            console.log('000', tempUrl, wx.getStorageSync('signImage'));
            if(!wx.getStorageSync('signImage')) { // 新增签署图片
                that.addSignImage(tempUrl).then(() => {
                    wx.navigateBack()
                }).catch(() => {
                    wx.setStorageSync('signImage', '')
                })
            } else { // 更新签署图片
                that.updateSignImage(tempUrl).then(() => {
                    wx.navigateBack()
                }).catch(() => {
                    wx.setStorageSync('signImage', '')
                })
            }
        })
      }
    })
  },
    // 新增签名图片
    async addSignImage(signImage) {
        await new Promise(resolve => {
            wx.request({
                url: app.globalData.httpsUrl + "product/safe/add",
                data: {
                    openId: app.globalData.openid,
                    signImage: signImage, // 签署图片
                    projectId: app.globalData.selectProjectId, // 项目id
                },
                method: 'POST',
                success: function (res) {
                if(res.data.code === 200) { // 0未签署 1已签署
                    resolve()
                }
                },
                fail: function (err) {
                    wx.showToast({
                        title: '新增安全责任书签名失败,请联系管理员',
                        icon: 'none'
                    })
                    rejec()
                }
            })
        })
    },
     // 更新签名图片
     async updateSignImage(signImage) {
        await new Promise(resolve => {
            wx.request({
                url: app.globalData.httpsUrl + "product/safe/update",
                data: {
                    openId: app.globalData.openid,
                    signImage: signImage, // 签署图片
                    projectId: app.globalData.selectProjectId, // 项目id
                    id: app.globalData.updateSignImageId
                },
                method: 'POST',
                success: function (res) {
                if(res.data.code === 200) { 
                    resolve()
                }
                },
                fail: function (err) {
                    wx.showToast({
                        title: '更新安全责任书签名失败,请联系管理员',
                        icon: 'none'
                    })
                    rejec()
                }
            })
        })
    },
    // 上传图片
    uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
            let a = wx.uploadFile({
                url: app.globalData.httpsUrl  + 'appDeviceAdd/fileUpload', 
                filePath: url,
                name: 'file',
                formData: {
                    //图片张数
                    // 'length': 上边的filelist.length
                },
                header: {
                    "Content-Type": "multipart/form-data"
                },
                success: (res) => {
                    resolve(res.data)
                },
                fail: (res) => {
                    wx.showToast({
                        title: '上传图片失败、请联系管理员',
                        icon: 'none'
                    })
                    reject()
                },
            });
        })
    },
})