import { Image, ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import { alert } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatRemoveHashTag, formatWeightDiv } from '@/common/fotmat'
import useCheckAuthorize from '@/use/useCheckAuthorize'
import { GetReturnPayCode } from '@/api/onlinePay'
import LoadingCard from '@/components/loadingCard'

interface Param {
  show?: true | false
  onClose?: () => void
  company?: string
  qrcode?: string
  orderInfo?: any
}
interface ListParam {
  product_code: string
  product_name: string
  product_color_code: string
  product_color_name: string
  num: string
  weight: string
  length: string
  sale_price: string
  total_price: string
  weight_error: string
  deduction_weight: string
  settle_weight: string
  deduction_amount: string
}
export default memo(({ show = true, onClose, orderInfo }: Param) => {
  const [detail, setDetail] = useState<any>()
  useEffect(() => {
    if (show && detail) {
      getCore()
    }
  }, [show, detail])
  const product_list = useMemo(() => {
    return orderInfo?.is_quality_check ? orderInfo?.quality_check_pass_product : orderInfo?.product_list
  }, [orderInfo])

  useEffect(() => {
    if (orderInfo) {
      const lists: ListParam[] = []
      product_list?.map((pitem) => {
        pitem?.product_colors?.map((citem) => {
          lists.push({
            product_code: formatRemoveHashTag(pitem.code),
            product_name: pitem.name,
            product_color_code: formatRemoveHashTag(citem.code),
            product_color_name: citem.name,
            num: citem.roll.toString(),
            length: (citem.length / 100).toString(),
            weight: formatWeightDiv(citem.label_weight).toString(),
            sale_price: formatPriceDiv(citem.sale_price).toString(),
            total_price: formatPriceDiv(citem.refund_amount).toString(), // 小计
            weight_error: formatWeightDiv(citem.settle_weight_error).toString(),
            deduction_weight: formatWeightDiv(citem.deductions_weight).toString(),
            settle_weight: formatWeightDiv(citem.settle_weight).toString(),
            deduction_amount: formatPriceDiv(citem.deductions_amount).toString(),
          })
        })
      })
      setDetail(() => ({
        title: '售后确认单',
        order_type: orderInfo.sale_mode_name, // 类型：大货
        client: orderInfo.purchaser_name,
        order_created_time: formatDateTime(orderInfo.create_time),
        order_no: orderInfo.return_order_no,
        pay_account: orderInfo.transfer_remittance_account,
        bank_account_name: orderInfo.account_name,
        bank_name: orderInfo.bank_of_deposit,
        order_total_length: (orderInfo.total_number / 100).toString(),
        order_total_price: formatPriceDiv(orderInfo.refund_amount).toString(),
        show_order_total_price: orderInfo.is_display_price,
        order_total_num: orderInfo.total_number.toString(),
        order_total_settle_weight: formatWeightDiv(orderInfo.order_total_settle_weight).toString(),
        order_total_deduction_weight: formatWeightDiv(orderInfo.order_total_deduction_weight).toString(),
        order_total_deduction_amount: formatPriceDiv(orderInfo.order_total_deduction_amount).toString(),
        show_order_total_deduction_amount: orderInfo.is_display_price,
        order_total_weight_error: formatWeightDiv(orderInfo.total_weight_error).toString(),
        list: lists,
        show_total_price: orderInfo.is_display_price,
        show_sale_price: orderInfo.is_display_price,
        show_deduction_amount: orderInfo.is_display_price,
      }))
    }
  }, [orderInfo])

  // 收货地址
  const address = (addressInfo) => {
    if (addressInfo?.shipment_mode == 2) {
      return addressInfo?.province_name ? addressInfo.province_name + addressInfo.city_name + addressInfo.district_name + addressInfo.address_detail : ''
    }
    else {
      return addressInfo?.take_goods_address
    }
  }

  // 收件人
  const userName = (addressInfo) => {
    return addressInfo?.shipment_mode == 2 ? orderInfo.target_user_name : ''
  }

  // 手机号
  const userPhone = (addressInfo) => {
    return addressInfo?.shipment_mode == 2 ? orderInfo.target_user_phone : orderInfo.take_goods_phone
  }

  // 获取支付二维码
  const [payCodeImage, setPayCodeImage] = useState<string>('')
  const fileData = useRef({
    filePath: '',
    base64: '',
  })
  const { fetchData, state } = GetReturnPayCode()
  const getCore = async() => {
    const res = await fetchData(detail)
    const base64 = res.data.base64
    setPayCodeImage(() => base64)
    const time = new Date().valueOf()
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || []
    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',
    })
  }

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

  // 保存图片
  const saveImage = () => {
    alert.loading('正在保存图片')
    Taro.saveImageToPhotosAlbum({
      filePath: fileData.current.filePath,
      success() {
        alert.success('图片保存成功')
      },
      fail(err) {
        console.log('err::', err)
      },
    })
  }

  // 预览图片
  const showImage = () => {
    console.log('fileData.current.filePath::', fileData.current.filePath)
    Taro.previewImage({
      current: fileData.current.filePath, // 当前显示
      urls: [fileData.current.filePath], // 需要预览的图片http链接列表
    })
  }

  // 复制功能
  return (
    <View className={styles.scanPay_main}>
      <Popup show={show} showTitle={false} onClose={onClose}>
        <View className={styles.scanPay_con}>
          <View className={classnames('iconfont icon-a-moreback', styles.miconfont_title)} onClick={onClose}></View>
          <View className={styles.title}>查看退款码单</View>
          <View className={styles.scanPay_list}>
            {(state.loading && <LoadingCard />) || (
              <ScrollView scrollY className={styles.scanPay_list}>
                <Image mode="widthFix" src={payCodeImage} onClick={showImage}></Image>
              </ScrollView>
            )}
          </View>
          <View className={styles.btns} onClick={saveImageCheck}>
            保存码单
          </View>
        </View>
      </Popup>
    </View>
  )
})
