import { Image, ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useEffect, 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 { GetPayCode } 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
}
const ScanPayCheck = ({ show = true, onClose, company, orderInfo }: Param) => {
  const [detail, setDetail] = useState<any>()

  // 收货地址
  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 } = GetPayCode()
  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 saveImage = () => {
    alert.loading('正在保存图片')
    Taro.saveImageToPhotosAlbum({
      filePath: fileData.current.filePath,
      success() {
        alert.success('图片保存成功')
      },
      fail(err) {
        console.log('err::', err)
      },
    })
  }
  // 检查是否开启保存图片权限
  const { check } = useCheckAuthorize({ scope: 'scope.writePhotosAlbum', msg: '您没授权，无法保存图片' })
  const saveImageCheck = async() => {
    const res = await check()
    res && saveImage()
  }
  // 预览图片
  const showImage = () => {
    console.log('fileData.current.filePath::', fileData.current.filePath)
    Taro.previewImage({
      current: fileData.current.filePath, // 当前显示
      urls: [fileData.current.filePath], // 需要预览的图片http链接列表
    })
  }
  useEffect(() => {
    if (show) {
      getCore()
    }
  }, [show])

  useEffect(() => {
    if (orderInfo) {
      const lists: ListParam[] = []
      orderInfo.product_list?.forEach((pitem) => {
        pitem?.product_colors?.forEach((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.actual_weight || citem.estimate_weight).toString(),
            sale_price: formatPriceDiv(citem.sale_price).toString(),
            total_price: formatPriceDiv(citem.total_sale_price || citem.estimate_amount).toString(), // 小计
            weight_error: formatWeightDiv(citem.weight_error).toString(),
          })
        })
      })
      setDetail(() => ({
        title: '面料销售电子确认单',
        company: orderInfo.company_name, // 后端公司
        order_type: orderInfo.sale_mode_name, // 类型：大货
        sale_user: orderInfo.sale_user_name, // 业务员
        order_created_time: formatDateTime(orderInfo.create_time),
        order_no: orderInfo.order_no,
        shipment_mode: orderInfo.shipment_mode_name, // 发货方式
        target_user_name: userName(orderInfo), // 收件人
        target_address: address(orderInfo), // 收货地址
        target_description: orderInfo.remark, // 发货备注
        pay_account: orderInfo.transfer_remittance_account, // 专属收款账号
        bank_account_name: orderInfo.account_name, // 账户名称
        bank_name: orderInfo.bank_of_deposit, // 开户银行
        pay_type: '', // 支付方式, 可不传
        client: orderInfo.purchaser_name, // 客户名称
        phone: userPhone(orderInfo), // 收货手机号码
        order_total_length: (orderInfo.total_number / 100).toString(), // 订单布匹长度
        order_total_price: formatPriceDiv(orderInfo.bill_total_sale_price).toString(), // 订单价格
        order_total_num: orderInfo.total_number.toString(),
        qrcode: '', // 跳转链接
        order_total_weight: formatWeightDiv(orderInfo.total_weight || orderInfo.total_estimate_weight).toString(), // 订单布匹重量
        list: lists,

        estimate_amount: formatPriceDiv(orderInfo.estimate_amount).toString(),
        show_estimate_amount: orderInfo.estimate_amount > 0 && orderInfo.total_sale_price <= 0 && orderInfo.is_display_price,
        total_sale_price: formatPriceDiv(orderInfo.total_sale_price).toString(),
        show_total_sale_price: orderInfo.total_sale_price > 0 && orderInfo.is_display_price,
        total_weight_error_discount: formatPriceDiv(orderInfo.total_weight_error_discount).toString(),
        show_total_weight_error_discount: orderInfo.total_weight_error_discount > 0 && orderInfo.is_display_price,
        actual_amount: formatPriceDiv(orderInfo.actual_amount).toString(),
        show_actual_amount: orderInfo.actual_amount > 0 && orderInfo.is_display_price,
        wait_pay_amount: formatPriceDiv(orderInfo.wait_pay_amount).toString(),
        show_wait_pay_amount: orderInfo.wait_pay_amount > 0 && orderInfo.is_display_price,
        show_barcode: true,
        order_total_weight_error: formatWeightDiv(orderInfo.total_weight_error).toString(), // 总空差重量
        show_total_price: orderInfo.is_display_price,
        show_sale_price: orderInfo.is_display_price,
        show_tips: true,
        tips: `请核对本单后验收， <b>如发现质量问题，请于收到货之日起3天内与平台客服联系协商解决，</b>逾期不作处理即表示购方默认对货物无异议；<b>购方确认无任何问题方可裁剪/加工，一经裁剪，缩水等工艺，平台概不负责；</b>
        看布购货，请先试缩水，并注意分缸裁布！如需撞色拼接，请先试色牢度。非质量问题，恕不退换，谢谢合作！`,
      }))
    }
  }, [orderInfo])
  // 复制功能
  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>
  )
}
export default memo(ScanPayCheck)
