// pages/reportPreview/reportPreview.ts
// import drawQrcode = require('../../utils/weapp-qrcode')
// import QRCode from '../../utils/weapp-qrcode.js'
let qrcode = require("../../utils/weapp-qrcode.js");
const app = getApp<IAppOption>()
import { reportPreview, visitReport, reportSave, certificateDetail, certificateDetail2, reportCreateDate } from "../../apis/report";
import { baseUrl } from '../../utils/request'
import { card, certifivate } from '../../utils/painter'
import { querystrToObj } from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    active: 1, // 1:证书,2:报告,3:二维码报告
    switch: false,
    toggles: {
      基础信息: true,
      学历教育: true,
      非学历教育: true,
      职业经历: true,
      社会活动经历: true
    },
    type: 0,  // 0:预览,
    report: {},
    isSourceShow: true,
    cardQr: '',
    myQrcode: '',
    certificateInfo: {},
    cardPainter: {},
    certifivatePainter: {},
    // reportCreateDate: ''
  },
  getReport(payload: any) {
    reportPreview(payload).then((res: any) => {
      let temp = res.d
      // console.log(temp);

      Object.keys(temp).forEach(key1 => {
        if (key1 !== '基础信息') {
          temp[key1].map((tempData: any) => {
            if (tempData['附件']) {
              let temps = this.strToArr(tempData['附件'].dataValue)
              temps.map((item: any, index: number) => {
                // console.log('###',item);
                temps[index] = item//.slice(0,item.lastIndexOf(':')+1)+'附件_'+item.slice(item.lastIndexOf(':')+1)
              })
              tempData['附件'].dataValue = temps
            }
            if (tempData['事件/活动记录']) {
              tempData['事件/活动记录'].map((item: any, index: any) => {
                if (item['附件']) {
                  let temps = this.strToArr(item['附件'].dataValue || '')
                  tempData['事件/活动记录'][index]['附件'].dataValue = temps
                }
              })
            }

            if (tempData['岗位记录']) {
              tempData['岗位记录'].map((item: any, index: number) => {
                if (item['附件']) {
                  let temps = this.strToArr(item['附件'].dataValue || '')
                  tempData['岗位记录'][index]['附件'].dataValue = temps
                }
              })
            }
          })
        }
      })

      this.setData({
        report: temp
      })
    })
  },
  strToArr(str: string) {
    return (str || '').split(',')
  },
  getVisitReport(id: string) {
    visitReport(id).then((res: any) => {
      this.setData({
        report: res.d
      })
    })
  },
  getVisitReport2(id: string) {
    certificateDetail2(id).then((res: any) => {
      this.setData({
        report: res.d
      })
    })
  },
  setQrcode() {
    const { type } = this.data
    // const path = encodeURIComponent('/pages/reportPreview/reportPreview')
    let url = `${baseUrl}/consumer/wechatshare/getUrlLink`
    const query = encodeURIComponent(`type=2&active=3&source=2&id=${this.data.id}`)
    // &env_version=${__wxConfig.envVersion}
    // @ts-ignore
    if (type !== 0) {
      url = `${url}?b=2&query=${query}`
    } else {
      url = 'https://www.chrivc.com'
    }
    // console.log(url)
    qrcode({
      width: 105,
      height: 105,
      canvasId: 'myQrcode',
      text: url,
      callback: (response: any) => {
        // 生成二维码的临时文件
        console.log(response)
        setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'myQrcode',
            success: (res) => {
              console.log(res)
              // resolve(res.tempFilePath)
              this.setData({
                myQrcode: res.tempFilePath
              })
            },
            fail: (err) => {
              console.log(err)
            }
          }, this)
        }, 500)
      }
    })

    qrcode({
      width: 253,
      height: 253,
      canvasId: 'cardQr',
      text: url,
      image: {
        imageResource: '/assets/images/logo.png',
        dx: 89.5,
        dy: 89.5,
        dWidth: 74,
        dHeight: 74
      },
      callback: (response: any) => {
        // 生成二维码的临时文件
        console.log(response)
        setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'cardQr',
            success: (res) => {
              console.log(res)
              // resolve(res.tempFilePath)
              this.setData({
                cardQr: res.tempFilePath
              })
            },
            fail: (err) => {
              console.log(err)
            }
          }, this)
        }, 500)
      }
    })
    console.log('setqr');

  },
  handleTabChange(e: WechatMiniprogram.BaseEvent) {
    console.log('handleTab', e);
    console.log(e.currentTarget.dataset.active);


    this.setData({
      active: e.currentTarget.dataset.active
    })
  },
  handleSwitch() {
    this.setData({
      switch: !this.data.switch
    })
  },
  handleToggle(e: WechatMiniprogram.BaseEvent) {
    console.log(e);

    const { toggled, key } = e.currentTarget.dataset
    // if (show) {
    // const { toggles } = this.data
    // toggles[key] = !toggled
    this.setData({
      // toggles: toggles
      [`toggles.${key}`]: !toggled
    })
    // }
  },
  // openpreviewImg() {
  //   this.selectComponent("#previewComponent").showPreview();
  // },
  toggleAll() {
    this.setData({
      toggles: {
        基础信息: false,
        学历教育: false,
        非学历教育: false,
        职业经历: false,
        社会活动经历: false
      },
    })
  },
  goTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  async downLoadCard() {
    const { cardQr } = this.data
    if (!cardQr) {
      wx.showToast({
        icon: 'error',
        title: '二维码生成中...'
      })
      return
    }
    const cardPainter = await card(this.data.cardQr)
    this.setData({
      cardPainter
    })
  },
  async downLoadCertifivate() {
    const { myQrcode } = this.data
    if (!myQrcode) {
      wx.showToast({
        icon: 'error',
        title: '二维码生成中...'
      })
      return
    }
    wx.showLoading({
      title: '请稍等...'
    })
    const cardPainter = await certifivate(this.data.myQrcode, this.data.certificateInfo, false)
    this.setData({
      cardPainter
    })
  },
  async downLoadCertifivateNoIdCard() {
    const { myQrcode } = this.data
    if (!myQrcode) {
      wx.showToast({
        icon: 'error',
        title: '二维码生成中...'
      })
      return
    }
    wx.showLoading({
      title: '请稍等...'
    })
    const cardPainter = await certifivate(this.data.myQrcode, this.data.certificateInfo, true)
    this.setData({
      cardPainter
    })
  },
  onImgOK(e: WechatMiniprogram.CustomEvent) {
    const { path } = e.detail
    console.log('path', path);

    // wx.saveImageToPhotosAlbum({
    //   filePath: path,
    //   success: () => {
    //     wx.showToast({
    //       title: '保存成功',
    //       duration: 1500
    //     })
    //   },
    //   fail: (err) => {
    //     console.log(err)
    //     wx.showToast({
    //       icon: 'error',
    //       title: '保存失败!',
    //       duration: 1500
    //     })
    //   },
    //   complete: () => {
    //     wx.hideLoading()
    //   }
    // })
    wx.showShareImageMenu({  //分享给朋友
      path,
      success: (res) => {
        console.log("分享成功：", res);
      },
      fail: (err) => {
        console.log("分享失败：", err);
        wx.showToast({
          title: "分享失败",
          duration: 2000
        })
      },
    })
  },
  getReportCreateDate(id: any) {
    reportCreateDate(id).then((res: any) => {
      this.setData({
        reportCreateDate: res.d
      })
    })
  },
  myInformation() {
    wx.reLaunch({
      url: '/pages/information/information'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!app.globalData.ready) return
    let { active, type, id, q } = options
    if (q) {
      q = decodeURIComponent(q)
      const queryStr = q.split('?')[1]
      const query = querystrToObj(decodeURIComponent(querystrToObj(queryStr).query))
      id = query.id
      type = query.type
      active = query.active
    }
    this.setData({
      active: Number(active),
      id: id,
      type: Number(type),
      certificateInfo: {
        id: '',
        username: app.globalData.userInfo?.name,
        idCard: app.globalData.userInfo?.idCard,
        createDate: Math.floor(new Date().getTime() / 1000),
        blockchain: new Array(64).fill('x')
      },
      reportCreateDate: wx.getStorageSync('reportCreateDate')
    })
  },
  createReport() {
    wx.navigateTo({
      url: '/pages/createReport/createReport'
    })
  },
  getCertificate(id: string) {
    certificateDetail(id).then((res: any) => {
      this.setData({
        certificateInfo: res.d
      })
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setQrcode()
    if (this.data.type === 1) {
      this.getReport({ id: this.data.id })
      this.getReportCreateDate(this.data.id)
    } else if (this.data.type === 2) {
      if (this.data.active == 1) {
        this.getCertificate(this.data.id)
        this.getReportCreateDate(this.data.id)
      } else if (this.data.active == 2) {
        this.getVisitReport(this.data.id)
        this.getReportCreateDate(this.data.id)
      } else {
        this.getVisitReport2(this.data.id)
        this.getReportCreateDate(this.data.id)
      }
    } else {
      this.getReport({ dataIds: wx.getStorageSync('reportIds') })
      this.setData({
        reportCreateDate: new Date().getTime()
      })
    }
  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '溯源优才个人信息报告',
      path: `/pages/reportPreview/reportPreview?id=${this.data.id}&type=2&active=3`,
      imageUrl: 'https://chrivc.obs.cn-north-4.myhuaweicloud.com/6c3f23310db6439db7872a38ef753097:附件_1659085634.png'
    }
  },
  getPaper() {
    console.log('getPaper');

    wx.showToast({
      icon: 'none',
      title: '暂未开通，敬请等待'
    })
  }
})