
import { Image, ScrollView, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import BottomBtns from '@/components/BottomBtns'
import { formatImgUrl, formatPriceDiv } from '@/common/format'
import Popup from '@/components/popup'
import useCheckAuthorize from '@/use/useCheckAuthorize'
import { alert } from '@/common/common'
import IconFont from '@/components/iconfont/iconfont'

interface Props {
  showPopup: true | false
  popupClose?: () => void
  obj: {
    wait_pay_amount?: number | string
    actual_amount?: number | string
    total_sale_price?: number | string
    should_collect_order_id?: number | string
    pre_collect_order_id?: number | string
    status?: number | string
  }
  showSide?: boolean
  list?: any[]
  clickItem?: (any) => void
  handsurePay?: (any) => void
  title: string
  picUrl?: string
}
const PayPopup = (props: Props) => {
  const {
    showSide = true,
    showPopup = false,
    popupClose,
    obj = {
      wait_pay_amount: '',
      actual_amount: '',
      total_sale_price: '',
    },
    clickItem,
    handsurePay,
    list = [],
    title = '待支付款项',
    picUrl = '',
  } = props

  const fileData = useRef({
    filePath: '',
    base64: '',
  })

  // 预览图片
  const showImage = () => {
    const time = new Date().valueOf()
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(picUrl) || []
    const filePath = `${Taro.env.USER_DATA_PATH}/img${time}.${format}`
    fileData.current.filePath = filePath
    fileData.current.base64 = bodyData
    const save = Taro.getFileSystemManager()
    save.writeFile({
      filePath: fileData.current.filePath,
      data: fileData.current.base64,
      encoding: 'base64',
    })
    Taro.previewImage({
      current: fileData.current.filePath, // 当前显示
      urls: [fileData.current.filePath], // 需要预览的图片http链接列表
    })
  }

  // 检查是否开启保存图片权限
  const { check } = useCheckAuthorize({ scope: 'scope.writePhotosAlbum', msg: '您没授权，无法保存图片' })

  // 保存图片
  const saveImage = () => {
    const time = new Date().valueOf()
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(picUrl) || []
    const filePath = `${Taro.env.USER_DATA_PATH}/img${time}.${format}`
    fileData.current.filePath = filePath
    fileData.current.base64 = bodyData
    const save = Taro.getFileSystemManager()
    save.writeFile({
      filePath: fileData.current.filePath,
      data: fileData.current.base64,
      encoding: 'base64',
    })
    alert.loading('正在保存图片')
    Taro.saveImageToPhotosAlbum({
      filePath: fileData.current.filePath,
      success() {
        alert.success('图片保存成功')
      },
      fail(err) {
        console.log('err::', err)
      },
    })
  }
  const saveImageCheck = async() => {
    const res = await check()
    res && saveImage()
  }
  return (
    <View className={styles.popupBox}>
      <Popup show={showPopup} title={title} onClose={() => popupClose?.()}>
        <ScrollView enhanced scrollY className={styles.scrollStyle} >
          {
            showSide
                        && <View className={styles.contBox}>
                          <View className={styles.topMoney}>
                                ￥{formatPriceDiv(obj.wait_pay_amount)}
                          </View>
                          <View className={styles.itemMoney}>
                            <View className={styles.leftFont}>
                                    订单金额
                            </View>
                            <View className={styles.rightFont}>
                                    ￥{formatPriceDiv(obj.wait_pay_amount)}
                            </View>
                          </View>
                          <View className={styles.itemMoney}>
                            <View className={styles.leftFont}>
                                    已付金额
                            </View>
                            <View className={styles.rightFont}>
                                    ￥{formatPriceDiv(obj.actual_amount)}
                            </View>
                          </View>
                          <View className={styles.line}></View>
                          {
                            list.map((item, index) => {
                              return (
                                <View className={styles.itemBox} key={index} onClick={() => clickItem?.(item)}>
                                  <View className={styles.leftItem}>
                                    <View className={styles.leftCrile}
                                      style={{ backgroundColor: `${item.name == '线下汇款' ? '#fca846' : item.name == '货主自提' ? '#00c760' : '#4a7fff'}` }}
                                    >
                                      <IconFont name={item.iconfont} size={item.name === '扫码支付' || item.name === '货到付款' ? 35 : 50} color={item.color}></IconFont>
                                      {/* <View className={classnames('iconfont', item.iconfont, styles.lujing)}></View> */}
                                    </View>
                                    <View className={styles.rightLeft}>
                                      <View className={styles.title}>{item.name}</View>
                                      {
                                        item.fonts && <View className={styles.nums}>{item.fonts}{
                                          item.money !== '' ? '￥' : ''
                                        }{item.money}</View>
                                      }
                                    </View>
                                  </View>
                                  {
                                    item.name !== '扫码支付' && item.name !== '线下汇款'
                                                && <View className={item.checked ? styles.activeChecked : styles.checkYuan}>
                                                  {/* <View className={classnames('iconfont', 'icon-lujing', styles.gou)}></View> */}
                                                  <IconFont name="icon-lujing" size={20} color="#ffffff"></IconFont>
                                                </View>
                                  }
                                  {
                                    (item.name === '扫码支付' || item.name === '线下汇款')
                                                && <IconFont name="icon-chakanquanbukehu" size={50} color="#000000" customClassName={styles.chakanquanbukehu}></IconFont>
                                                // <View className={classnames('iconfont', 'icon-chakanquanbukehu', styles.chakanquanbukehu)}></View>
                                  }
                                </View>
                              )
                            })
                          }

                        </View>

          }
          {
            showSide && <View className={styles.sure} onClick={() => handsurePay?.(props?.obj)}>确认交易</View>
          }
          {
            !showSide
                        && <ScrollView enhanced scrollY className={styles.scroStyle}>
                          <View className={styles.pic}>
                            <Image lazyLoad mode="widthFix" style={{ width: '100%', height: '100%' }} src={picUrl} onClick={() => showImage()}></Image>
                          </View>
                        </ScrollView>

          }
          {
            !showSide && <View className={styles.sure} onClick={() => saveImageCheck()}>保存图片</View>
          }
          <View className={styles.safeBox}></View>
        </ScrollView>
      </Popup >
    </View >
  )
}
export default memo(PayPopup)
