import { getApiLoading } from '@/common/libraries/apiLoading'
import { Apis } from '@/gen/Apis'
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.WorkOrder.HouseWorkOrders.GetWorkOrderPayQrCode, {
    id: data?.id
  }).then((res: any) => {
    const fs = uni.getFileSystemManager()
    //随机定义路径名称
    let times = new Date().getTime()
    let codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png'
    console.log(codeimg, '二维码路径')
    // return fun?.(res?.data?.qr_code)
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: res?.data?.qr_code.slice(22),
      encoding: 'base64',
      success: () => {
        return fun?.(codeimg)
      }
    })
  })
}

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) {
    console.log(data, 'data')
    const context = uni.createCanvasContext('poster_firstCanvas')
    getQrCode(data, url => {
      uni.downloadFile({
        url: 'https://pay-prod-1369486729.cos.ap-guangzhou.myqcloud.com/uploads/cs-test/01KFYRR5Y37PR2C1EDJYZYCDJK.png',
        success(res) {
          context.drawImage(res.tempFilePath, 0, 0, 345, 504)
          context.font = 'bold 18px Arial'
          context.fillStyle = '#3D3D3D'
          context.setTextAlign('center')
          context.fillText(data?.full_name || '-', 345 / 2, 45)
          context.font = 'bold 20px Arial'
          context.fillStyle = '#3D3D3D'
          context.fillText(`¥${data?.amount || '-'}元`, 345 / 2, 85)
          context.font = '12px Arial'
          context.fillStyle = '#666'
          context.fillText('待支付', 345 / 2, 110)
          context.font = '14px Arial'
          context.fillStyle = '#00C800'
          context.fillText('请使用微信扫码支付', 345 / 2, 450)

          setTimeout(() => {
            context.drawImage(url, 72.5, 150, 200, 200)
            context.restore()
            context.draw()
          }, 500)
        }
      })
      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) {
        console.log(res, 'res')
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            console.log('save success')
            uni.hideLoading()
          },
          fail() {
            uni.hideLoading()
          }
        })
        console.log(res.tempFilePath)
      },
      fail(e) {
        console.log(e, 'err')
        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 });
    // });
  }
}
