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 { formatPriceDiv } from '@/common/format'
import Popup from '@/components/popup'
import useCheckAuthorize from '@/use/useCheckAuthorize'
import { alert } from '@/common/common'
import { GetReturnPayCode } from '@/api/order'
import { formatDateTime, formatWeightDiv } from '@/common/format'

interface Props {
  obj: any
  // picUrl?: string,
  showPopup: boolean
  popupClose: () => void
}
const RefundCodelist = (props: Props) => {
  const { fetchData: payFetch } = GetReturnPayCode()
  const [PicUrl, setPicUrl] = useState<string>('')

  const totalNums = useMemo(() => {
    if (props?.obj.type == 1 || props?.obj.type == 3) {
      return props?.obj.quality_check_pass_number
    }
    else {
      return props?.obj.total_number
    }
  }, [props?.obj])

  const getPic = async() => {
    Taro.showLoading({
      title: '请稍等...',
      mask: true,
    })
    const list: any = []
    let arr: any[] = []
    if (props.obj.type == 1 || props?.obj.type == 3) {
      arr = props.obj.quality_check_pass_product
    }
    else {
      arr = props.obj.product_list
    }
    arr.forEach((item) => {
      item.product_colors.forEach((it) => {
        list.push({
          product_code: item.code,
          product_name: item.name,
          product_color_code: it.code,
          product_color_name: it.name,
          num: it.roll.toString(),
          weight: formatWeightDiv(it.label_weight).toString(),
          deduction_weight: formatWeightDiv(it.deductions_weight).toString(),
          settle_weight: formatWeightDiv(it.settle_weight).toString(),
          deduction_amount: (it.deductions_amount / 100).toString(),
          sale_price: (it.sale_price / 100).toString(),
          total_price: (it.estimate_amount / 100).toString(),
          length: (it.length / 100).toString(),
          weight_error: formatWeightDiv(it.settle_weight_error).toString(),
        })
      })
    })
    const query = {
      list,
      title: '售后确认单',
      order_type: props.obj.sale_mode_name,
      sale_user: props.obj.sale_user_name,
      order_created_time: formatDateTime(props.obj.create_time),
      order_no: props.obj.return_order_no,
      pay_account: props.obj.transfer_remittance_account,
      bank_account_name: props.obj.account_name,
      bank_name: props.obj.bank_of_deposit,
      client: props.obj.purchaser_name,
      order_total_length: (props.obj.total_number / 100).toString(),
      order_total_price: (
        props.obj.refund_amount / 100
      ).toString(),
      order_total_num: totalNums.toString(),
      order_total_settle_weight: (
        props.obj.order_total_settle_weight / 1000
      ).toString(),
      order_total_deduction_weight: (
        props.obj.order_total_deduction_weight / 1000
      ).toString(),
      order_total_deduction_amount: (
        props.obj.order_total_deduction_amount / 100
      ).toString(),
      order_total_weight_error: (
        props.obj.total_weight_error / 1000
      ).toString(),
      show_sale_price: props?.obj?.sale_mode === 0 && props?.obj?.is_display_price ? true : !!((props?.obj?.sale_mode === 1 || props?.obj?.sale_mode === 2)),
      show_total_price: props?.obj?.sale_mode === 0 && props?.obj?.is_display_price ? true : !!((props?.obj?.sale_mode === 1 || props?.obj?.sale_mode === 2)),
      show_deduction_amount: props?.obj?.sale_mode === 0 && props?.obj?.is_display_price ? true : !!((props?.obj?.sale_mode === 1 || props?.obj?.sale_mode === 2)),
      show_order_total_price: props?.obj?.sale_mode === 0 && props?.obj?.is_display_price ? true : !!((props?.obj?.sale_mode === 1 || props?.obj?.sale_mode === 2)),
      show_order_total_deduction_amount: props?.obj?.sale_mode === 0 && props?.obj?.is_display_price ? true : !!((props?.obj?.sale_mode === 1 || props?.obj?.sale_mode === 2)),
    }
    const res = await payFetch(query)
    if (res.data) {
      setPicUrl(res.data.base64)
      Taro.hideLoading()
    }
  }

  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: '您没授权，无法保存图片' })

  useEffect(() => {
    // 判断进来的是否是空对象，减少性能问题
    const length = Object.keys(props.obj)
    if (length.length > 0) { getPic() }
  }, [props.obj])

  // 保存图片
  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 (
    <Popup show={props.showPopup} title="退款码单" onClose={() => props.popupClose?.()}>
      <View className={styles.popupBox}>
        <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>
        <View className={styles.sure} onClick={() => saveImageCheck()}>保存图片</View>
      </View>
    </Popup>
  )
}
export default memo(RefundCodelist)
