import { Text, View } from "@tarojs/components";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import AmountShow from "../amountShow";
import classnames from "classnames";
import styles  from './index.module.scss'

import MCheckbox from "@/components/checkbox";
import Popup from "@/components/popup";
import OfflinePay from "../offlinePay";
import ScanPay from "../scanPay";
import { GetOrderPayApi, SubmitOrderPayApi } from "@/api/orderPay";
import { formatPriceDiv } from "@/common/fotmat";
import {alert} from "@/common/common"
import { PAYMENT_METHOD, PAYMENT_METHOD_PARAM } from "@/common/enum";

type Param = {
    show?: true|false,
    onClose?: () => void,
    onSubmitSuccess?: () => void, //支付成功
    orderInfo?: OrderInfo
}

type OrderInfo = {
    orderId: number, //应付单id
    payment_method: 0|PAYMENT_METHOD_PARAM //支付方式
}

type PayStatus = 1|2|3|4|5|null //1:预存款， 2:账期，3：线下汇款， 4：扫码支付, 5:货到付款
export default memo(({show = false, onClose, orderInfo, onSubmitSuccess}:Param) => {

    //提交参数
    const [submitData, setSubmitData] = useState<{id:number, payment_method: PayStatus}>({
        id:0,
        payment_method: null
    })

    //线下付款
    const [offlinePayShow, setofflinePayShow] = useState(false)
    const onShowOfflinePay = () => {
        setofflinePayShow(true)
        onClose?.()
    }

    //扫码支付
    const [scanPayShow, setScanPayShow] = useState(false)
    const onShowScanPay = () => {
        setScanPayShow(true)
        onClose?.()
    }

    //获取支付方式数据
    const [payInfo, setPayInfo] = useState<any>()
    const {fetchData: orderFetchData} = GetOrderPayApi()
    const getOrderPay = async () => {
        let {data} = await orderFetchData({id: orderInfo?.orderId})
        setPayInfo(() => data)
    }
    useEffect(() => {
        if(show&&orderInfo?.orderId) {
            setSubmitData((val) => ({...val, id:orderInfo.orderId}))
            getOrderPay()
        }
    }, [show, orderInfo]) 

    //预存款选择
    const advanceSelectData = useCallback((val) => {
        setSubmitData((e) => ({...e, payment_method:val}))
    }, [])

    //账期选择
    const periodSelectData = (val) => {
        setSubmitData((e) => ({...e, payment_method:val}))
    }

    //提交支付
    const {fetchData: submitFetchData} = SubmitOrderPayApi()
    const submitPay = async () => {
        if(submitData.payment_method === null) {
            alert.error('请选择支付方式')
            return false
        }
        alert.loading('正在支付')
        let res = await submitFetchData(submitData)
        if(res.success) {
            alert.success('支付成功')
            onSubmitSuccess?.()
        } else {
            alert.none(res.msg)
        }
    }

    //预付款
    const advance_payment = useMemo(() => {
        const price = payInfo?.should_collect_money - payInfo?.amount_paid
        return (
            <View className={styles.payment_list_item_left_price}>{(payInfo?.advance_deposit_balance < price)&&'余额不足，' }剩余 ¥{formatPriceDiv(payInfo?.advance_deposit_balance)}</View>
        )
    }, [payInfo])

    //账期
    const account_peyment = useMemo(() => {
        const price = payInfo?.should_collect_money - payInfo?.amount_paid
        return (
            <View className={styles.payment_list_item_left_price}>{(payInfo?.account_period_credit_available_line < price)&&'额度不足, '}剩余 ¥{formatPriceDiv(payInfo?.account_period_credit_available_line)}</View>
        )
    }, [payInfo])

    //支付方式枚举
    const {PaymentMethodPreDeposit, PaymentMethodAccountPeriod} = PAYMENT_METHOD

    return (
        <View className={styles.payment_main}>
            <Popup show={show} showTitle={false} onClose={onClose} >
                <View className={styles.payment_con}>
                    <View className={classnames('iconfont icon-a-moreback', styles.miconfont_title)} onClick={onClose}></View>
                    <View className={styles.title}>订单支付</View>
                    <View className={styles.amount}>
                        <AmountShow status={2} number={formatPriceDiv(payInfo?.should_collect_money - payInfo?.amount_paid)}/>
                    </View>
                    <View className={styles.payment_list}>
                        <View className={styles.payment_list_top_border}></View>
                        <View className={styles.payment_list_title}>
                            {/* <Text>向商家发起支付</Text> */}
                            <View className={styles.payment_list_title_price}>
                                <View className={styles.payment_list_title_price_item}>
                                    <Text>订单金额</Text>
                                    <Text>¥{formatPriceDiv(payInfo?.should_collect_money)}</Text>
                                </View>
                                <View className={styles.payment_list_title_price_item}>
                                    <Text>已付金额</Text>
                                    <Text>¥{formatPriceDiv(payInfo?.amount_paid)}</Text>
                                </View>
                            </View>
                        </View>
                        <View className={styles.payment_list_con}>
                            <View className={styles.payment_list_item}>
                                <View className={styles.payment_list_item_left}>
                                    <View className={styles.payment_list_item_left_name}>
                                        <View className={classnames('iconfont icon-a-tuikuanshouhou', styles.miconfont)}></View>
                                        <View className={styles.payment_list_item_left_text}>预存款</View>
                                    </View>
                                    {advance_payment}
                                </View>
                                <MCheckbox status={submitData.payment_method == PaymentMethodPreDeposit.value} onSelect={() => advanceSelectData(PaymentMethodPreDeposit.value)} onClose={() => advanceSelectData(null)}/>
                            </View>
                            {(orderInfo?.payment_method != PaymentMethodAccountPeriod.value)&&<View className={styles.payment_list_item}>
                                <View className={styles.payment_list_item_left}>
                                    <View className={styles.payment_list_item_left_name}>
                                        <View className={classnames('iconfont icon-a-tuikuanshouhou', styles.miconfont)}></View>
                                        <View className={styles.payment_list_item_left_text}>{payInfo?.account_period}天账期</View>
                                    </View>
                                    {/* <View className={styles.payment_list_item_left_price}>可用额度 ¥{formatPriceDiv(payInfo?.account_period_credit_available_line)}</View> */}
                                    {account_peyment}
                                </View>
                                <MCheckbox  status={submitData.payment_method == PaymentMethodAccountPeriod.value} onSelect={() => periodSelectData(PaymentMethodAccountPeriod.value)} onClose={() => periodSelectData(null)}/>
                            </View>}
                            <View className={styles.payment_list_item} onClick={onShowOfflinePay}>
                                <View className={styles.payment_list_item_left}>
                                    <View className={styles.payment_list_item_left_name}>
                                        <View className={classnames('iconfont icon-a-tuikuanshouhou', styles.miconfont)}></View>
                                        <View className={styles.payment_list_item_left_text}>线下汇款</View>
                                    </View>
                                </View>
                                <View className={classnames('iconfont icon-a-moreback', styles.miconfont_more)}></View>
                            </View>
                            <View className={styles.payment_list_item} onClick={onShowScanPay}>
                                <View className={styles.payment_list_item_left}>
                                    <View className={styles.payment_list_item_left_name}>
                                        <View className={classnames('iconfont icon-a-tuikuanshouhou', styles.miconfont)}></View>
                                        <View className={styles.payment_list_item_left_text}>扫码支付</View>
                                    </View>
                                </View>
                                <View className={classnames('iconfont icon-a-moreback', styles.miconfont_more)}></View>
                            </View>
                        </View>
                    </View>
                    <View className={styles.btns} onClick={submitPay}>确认交易</View>
                </View>
            </Popup>
            <OfflinePay show={offlinePayShow} onClose={() => setofflinePayShow(false)}/>
            <ScanPay show={scanPayShow} onClose={() => setScanPayShow(false)}/>
        </View>
        
    )
})