import { getApiLoading } from '@/common/libraries/apiLoading';
import { showToast } from '@/common/libraries/naviHelper';
import { Apis } from '@/gen/Apis';
import dayjs from 'dayjs';
import UQRCode from 'uqrcodejs';
import useModel from './model';
// import { handleFloors } from "@/common/libraries/public";
type ImgInfo = {
  leftNum?: number
  imgWidth?: number
  imgHeight?: number
}
const calculateAspectRatio = (iw: number, ih: number) => {
  // 计算图片的长宽比
  let imgWidth = iw
  let imgHeight = ih
  const maxWidth = 300
  const maxHeight = 200
  let leftNum = 0
  let topNum = 0 // 用于垂直居中的偏移

  // 计算等比缩放后的尺寸
  let ratio = imgWidth / imgHeight

  if (imgWidth > maxWidth || imgHeight > maxHeight) {
    if (imgWidth / maxWidth > imgHeight / maxHeight) {
      // 宽度超过最大宽度
      imgWidth = maxWidth
      imgHeight = Math.round(imgWidth / ratio)
    } else {
      // 高度超过最大高度
      imgHeight = maxHeight
      imgWidth = Math.round(imgHeight * ratio)
    }
  }

  // 如果图片宽度小于最大宽度，计算 leftNum 以使图片水平居中
  if (imgWidth < maxWidth) {
    const leNum = maxWidth - imgWidth
    leftNum = leNum / 2 + 22.5
  }

  // 如果图片高度小于最大高度，计算 topNum 以使图片垂直居中
  if (imgHeight < maxHeight) {
    const toNum = maxHeight - imgHeight
    topNum = toNum / 2
  }
  return { leftNum: leftNum, topNum: topNum, imgWidth, imgHeight }
}

const getImagesInfo = (url: string, fun: any) => {
  //获取图片等比例缩放后的宽高
  uni.getImageInfo({
    src: url,
    success: function (img) {
      return fun(calculateAspectRatio(img.width, img.height))
    }
  })
}

const send_code = (code: string, fun: (url: string) => void) => {
  /*code是指图片base64格式数据*/
  //声明文件系统
  const fs = uni.getFileSystemManager()
  //随机定义路径名称
  var times = new Date().getTime()
  var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png'

  //将base64图片写入
  fs.writeFile({
    filePath: codeimg,
    data: code.slice(22),
    encoding: 'base64',

    success: () => {
      return fun(codeimg)
    }
  })
}

const getQrCode = (data: any, fun?: (url: string) => void) => {
  //获取二维码
  getApiLoading(Apis.HouseOrder.HouseOrders.GetPayQrCode, {
    id: data?.order_id
  }).then((res: any) => {
    const fs = uni.getFileSystemManager()
    //随机定义路径名称
    let times = new Date().getTime()
    let codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png'
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: res?.data?.qr_code.slice(22),
      encoding: 'base64',
      success: () => {
        return fun?.(codeimg)
      }
    })
  })
}



  const GetAndSetAlipayQrcode = () =>{
    console.log('进来:');
    const context = uni.createCanvasContext('poster_firstCanvas')
    uni.canvasToTempFilePath({
    canvasId: 'alipay_qrcode',
    x: 0,
    y: 0,
    width: 170,
    height: 170,
    destWidth: 170,
    destHeight: 170,
    success: (json) => {
      context.clearRect(0, 0, 345, 504);
       uni.downloadFile({
        url: 'https://pay-prod-1369486729.cos.ap-guangzhou.myqcloud.com/uploads/cs-test/01KP2XJ54TN4DVMCCJJ0AVNJK8.png',
        success(res) {
          context.drawImage(res.tempFilePath, 0, 0, 345, 504)
          context.font = 'bold 18px Arial'
          context.setTextAlign('center')
          context.fillText(useModel.orderInfo.value?.name || '-', 345 / 2, 45)
          context.font = 'bold 16px Arial'
          context.fillStyle = '#DF3600'
          context.fillText(`缴费金额：¥${useModel.orderInfo.value?.amount}元`, 345 / 2, 78)
          context.font = '14px Arial'
          context.fillStyle = '#333'
          context.fillText('请使用支付宝扫码支付', 345 / 2, 450)
          context.font = '12px Arial'
          context.fillStyle = '#666'
          context.fillText(`生成时间：${useModel?.alipayQrCode?.value?.time} 有效时间30分钟`, 345 / 2, 475)
          context.drawImage(json.tempFilePath, 72.5, 150, 200, 200)
          context.restore()
          context.draw()
        }
      })

      console.log(json, '支付宝二维码路径')
    },fail: (err) => {
      console.log(err, '支付宝二维码路径失败')
    }
    })
  }

const GetAlipayQrcode = () =>{
  //已经获取支付宝二维码串
  if(useModel?.alipayQrCode?.value?.payinfo){
    //已经生成过支付宝二维码
    GetAndSetAlipayQrcode()
    return
  }
  //第一次获取支付宝二维码串
  getApiLoading(Apis.HouseOrder.HouseOrders.AlipayQrCode, {
    id: useModel.orderInfo.value?.order_id,
    pay_type: 'Alipay'
  }).then( (res: any) => {
    useModel.alipayQrCode.value = {...res?.data, time: dayjs().format('YYYY-MM-DD HH:mm')}
    //第一次生成支付宝二维码
    SetAlipayQrcode()
    })
  }

const SetAlipayQrcode = () =>{
  //第一次生成支付宝二维码
const qr:any = new UQRCode();
  qr.data = useModel?.alipayQrCode?.value?.payinfo; // 设置要转换的链接
  qr.size = 170; // 二维码尺寸，需与 canvas 宽高一致
  qr.make();
  const canvasContext = uni.createCanvasContext('alipay_qrcode');
  qr.canvasContext = canvasContext;
  qr.drawCanvas();
    setTimeout(() => {
      GetAndSetAlipayQrcode()
    }, 300)
}

const SetCustQrcode = () =>{
  //客户端设置二维码
  const context = uni.createCanvasContext('poster_firstCanvas')
  uni.downloadFile({
      url: 'https://pay-prod-1369486729.cos.ap-guangzhou.myqcloud.com/uploads/cs-test/01KP2XJ54TN4DVMCCJJ0AVNJK8.png',
      success(res) {
        context.clearRect(0, 0, 345, 504);
        context.drawImage(res.tempFilePath, 0, 0, 345, 504)
        context.font = 'bold 18px Arial'
        context.setTextAlign('center')
        context.fillText(useModel.custQrcodeInfo.value?.name || '-', 345 / 2, 45)
        context.font = 'bold 16px Arial'
        context.fillStyle = '#DF3600'
        context.fillText(`缴费金额：¥${useModel.custQrcodeInfo.value?.amount}元`, 345 / 2, 78)
        context.font = '14px Arial'
        context.fillStyle = '#333'
        context.fillText('请使用微信扫码支付', 345 / 2, 450)
        context.font = '12px Arial'
        context.fillStyle = '#666'
        context.fillText(`生成时间：${useModel.custQrcodeInfo.value?.time}`, 345 / 2, 475)
        context.drawImage(useModel.custQrcodeInfo.value?.url, 72.5, 150, 200, 200)
        context.restore()
        context.draw()
      }
    })
}


export default {
  //method
  getHouseDetail(id: number) {
    // getApiLoading(Apis.SourceHouse.SourceHouses.Show, { id }).then(
    //   (res: any) => {
    //     useModel.houseDetail.value = res.data;
    //     this.getQrCode(res?.data);
    //   }
    // );
  },

  setCanvas(data: any) {
    getQrCode(data, url => {
      useModel.custQrcodeInfo.value = {...data, url: url}
      SetCustQrcode()
      console.log(url, '二维码路径')
    })
  },

  onDownloadPosters() {
    //保存se64转图片并保存到相册
    uni.showLoading({
      title: '正在保存中...'
    })
    uni.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 345,
      height: 504,
      destWidth: 345 * 4,
      destHeight: 504 * 4,
      canvasId: 'poster_firstCanvas',
      success: function (res) {
        // 在H5平台下，tempFilePath 为 base64
        uni.hideLoading()
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            console.log('save success')
            // uni.hideLoading()
            showToast('保存成功！')
          },
          fail() {
            uni.hideLoading()
          }
        })
        console.log(res.tempFilePath)
      },
      fail() {
        uni.hideLoading()
      }
    })
  },

  initActualImages: async (id: string | number) => {
    const { houseActualImages, posterImage } = useModel
    // clearActualImages();
    // const res = await Apis.SourceHouse.SourceHouseSurveys.List({
    //   source_houses_id: Number(id),
    // });
    // if (res.success) {
    //   if (res.data?.length) {
    //     useModel.choiceImgShow.value = !useModel.choiceImgShow.value;
    //   } else {
    //     uni.showToast({
    //       title: "当前房源暂无图片！",
    //       icon: "none",
    //       duration: 1000,
    //     });
    //   }
    //   // 接口调用成功
    //   let isRejected = false;
    //   res.data.some((item: any) => {
    //     if (item.status === "Rejected" || item.status === "PendingReview") {
    //       // 存在未过审图片
    //       isRejected = true;
    //       return true;
    //     }
    //     return false;
    //   });
    //   if (!isRejected) {
    //     // 不存在未过审图片
    //     if (!!res.data.length) {
    //       // 存在图片
    //       houseActualImages.value = res.data;
    //       posterImage.value = res.data[0].image_url;
    //     }
    //   }
    // }
  },
  choiceImgPopControl() {
    this.initActualImages(useModel.houseDetail.value?.id)
  },
  copyLink() {
    // getApiLoading(Apis.SourceHouse.SourceHouses.SourceHouseShortUrl, {
    //   id: useModel.houseDetail.value.id,
    // }).then((res: any) => {
    //   uni.setClipboardData({ data: res.data.short_link });
    // });
  },
  changeTab(idx: number) {
    useModel.tabCurrent.value = idx
    if(idx){
      GetAlipayQrcode()
    } else{
      SetCustQrcode()
    }
  }
}
