<!-- 货币列表 -->
<template>
    <div class="currency-list-wrapper">
        <div class="search-input-wrapper">
            <input class="input" v-model="keywords" @input="onInput" placeholder="Search name" />
            <img :src="require('../../assets/svg/icon-form-refresh.svg')" 
                class="icon"
                :class="{ 'icon-refresh-rotate': refreshRotate }"
                @click="refresh">
            <img :src="require('../../assets/svg/icon-clear-search.svg')" class="icon-clear"
            v-if="keywords"
            @click="clearIpt" >
        </div>
        <div class="list-wrapper" ref="listWrapperDom" @scroll="listScroll">
            <div class="page-list" ref="listContentDom" v-if="!showSearch">
                <div class="list-item" v-for="(item, index) in currencyInfoList" :key="index">

                    <template v-if="props.page != 'top-up' || item.type != 1">
                        <div class="item-title" v-if="item.data.length">
                            <img class="icon"
                                :src="item.type == 1 ? require('../../assets/svg/icon-currency-category-01.svg') : require('../../assets/svg/icon-currency-category-02.svg')" />
                            {{ item.type == 1 ? 'Cash' : 'Crypto' }}
                        </div>
                        <div class="item-detail" v-for="(data, idx) in item.data" :key="idx"
                            @click="selectCurrency(data.currencies)">
                            <div class="left">
                                <img class="icon-currency" :src="data.currencies[0].iconPath" />
                                <div class="currency-info">
                                    <div class="name">{{ data.currencies[0].currencyCode == 'USD' ? 'USD' : data.currencies[0].tokenSymbol }}</div>
                                    <div class="desc">{{ data.currencies[0].currencyCode == 'USD' ? 'Paypal' : data.currencies[0].currencyName }}
                                    </div>
                                </div>
                            </div>
                            <div class="right">
                                <div class="num">
                                    <a-tooltip :title="data.totalBalance">
                                        {{ getBit(data.totalBalance) }}
                                    </a-tooltip>
                                </div>
                                <div class="amount" v-if="data.currencies[0].currencyType == 2">
                                    <a-tooltip :title="'$'+data.totalUsdEstimateBalance">
                                        ${{ getBit(data.totalUsdEstimateBalance) }}
                                    </a-tooltip>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
                <div class="no-data" v-if="show_empty">
                    {{page != 'top-up' ? 'Not found' : 'No balance'}}
                </div>

            </div>
            <!-- 显示搜索结果列表 -->
            <div class="search-list" v-else>
                <div class="item-detail" v-for="(data, idx) in searchList" :key="idx" @click="selectCurrency(data.currencies)">
                    <div class="left">
                        <img class="icon-currency" :src="data.currencies[0].iconPath" />
                        <div class="currency-info">
                            <div class="name">{{ data.currencies[0].currencyCode == 'USD' ? 'USD' : data.currencies[0].tokenSymbol }}</div>
                            <div class="desc">{{ data.currencies[0].currencyName }}</div>
                        </div>
                    </div>
                    <div class="right">
                        <div class="num">
                            <a-tooltip :title="data.currencies[0].balance">
                                {{ getBit(data.currencies[0].balance) }}
                            </a-tooltip>
                        </div>
                        <div class="amount" v-if="data.currencies[0].currencyType == 2">
                            <a-tooltip :title="'$'+data.currencies[0].usdEstimateBalance">
                                ${{ getBit(data.currencies[0].usdEstimateBalance) }}
                            </a-tooltip>
                        </div>
                    </div>
                </div>
                <div class="no-data" v-if="!searchList.length">
                    {{page != 'top-up' ? 'Not found' : 'No balance'}}
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
/* eslint-disable */
import { defineEmits, ref, onMounted, defineProps, defineExpose } from "vue";
import { getCurrencyInfo, searchCurrencyInfo, syncChainTokenRechargeRecord } from "@/http/publishApi";
import { debounce, getBit } from "@/uilts/help";

const props = defineProps({
    page: {
        type: String,
        default: '',
    },
    filterEmptyBalance: {
        type: Boolean,
        default: false
    }
})
let keywords = ref('');
let showSearch = ref(false);
let currencyInfoList = ref([]);
let searchList = ref([]);
let refreshRotate = ref(false);
let listWrapperDom = ref(null);
let listContentDom = ref(null);
let listReqParams = {
    params: {
        pageNum: 1,
        pageSize: 100,
    },
    loadMore: false,
};
let show_empty = ref(false)
const emits = defineEmits(["selectCurrency", "setCurrencyList"]);

const selectCurrency = (params) => {
    emits("selectCurrency", params);
};

const onInput = (val) => {
    console.log(keywords.value);
    if (keywords.value) {
        showSearch.value = true;
        searchCurrency(keywords.value);
    } else {
        showSearch.value = false;
        searchList.value = [];
    }
}

const clearIpt = () => {
    keywords.value = '';
    showSearch.value = false;
    searchList.value = [];
}

const refresh = () => {
    if (!refreshRotate.value) {
        refreshRotate.value = true;
        setTimeout(() => {
            refreshRotate.value = false;
        }, 1000)
        asyncTokenRechRecord(() => {
            getCurrencyInfoList();
        })
    }
}

/**
 * 搜索结果列表
 */
const searchCurrency = debounce(function (searchWords) {
    searchCurrencyInfo({
        params: {
            pageNum: 1,
            pageSize: 100,
            searchWords,
            filterFiatCurrency: props.page == 'top-up'
        }
    }).then(res => {
        if (res.code == 0) {
            if (res.data.currencyCategories && res.data.currencyCategories.length) {
                let list = res.data.currencyCategories[0];
                if (list && list.data && list.data.length) {
                    searchList.value = list.data;
                } else {
                    searchList.value = [];
                }
            } else {
                searchList.value = [];
            }
        }
    })
}, 500)

/**
 * 获取货币列表
 */
const getCurrencyInfoList = () => {
    let params = {
        params: {
            pageNum: listReqParams.params.pageNum,
            pageSize: listReqParams.params.pageSize,
            filterFiatCurrency: props.page == 'top-up',
            filterEmptyBalance: props.filterEmptyBalance
        }
    };
    getCurrencyInfo(params).then(res => {
        if (res.code == 0) {
            let resData = res.data;
            if (resData && resData.currencyCategories.length) {
                if (listReqParams.params.pageNum < 2) {
                    currencyInfoList.value = res.data.currencyCategories;   
                    emits('setCurrencyList', { list: currencyInfoList.value })
                    if(resData.currencyCategories.length == 1 && (!resData.currencyCategories[0]['data'] || !resData.currencyCategories[0]['data'].length)) {
                        show_empty.value = true
                    }
                } else {
                    let data = currencyInfoList.value;
                    let currencyCategories = resData.currencyCategories;
                    data = data.concat(currencyCategories);
                    currencyInfoList.value = data;
                }
                listReqParams.loadMore = false;
            }else{
                show_empty.value = true
            }
        }
    })
}


/**
 * 同步链上交易
 */
const asyncTokenRechRecord = (cb) => {
    syncChainTokenRechargeRecord({
        params: {
            currencyCode: ''
        }
    }).then(res => {
        if (res.code == 0) {
            cb && cb(res.data)
        }
    })
}

const listScroll = (e) => {
    let wrapperHeight = listWrapperDom.value.offsetHeight;
    let listContentHeight = listContentDom.value.offsetHeight;
    let scrollTop = e.target.scrollTop || 0;
    if (
        listReqParams.loadMore === false &&
        wrapperHeight + scrollTop >= listContentHeight
    ) {
        listReqParams.loadMore = true;
        listReqParams.params.pageNum++;
        getCurrencyInfoList();
    }
}

onMounted(() => {
    getCurrencyInfoList();
})

defineExpose({
    getCurrencyInfoList
})

</script>

<style scoped lang="scss">
.currency-list-wrapper {
    width: 100%;
    height: 100%;
    background-color: #fff;
    box-sizing: border-box;

    .search-input-wrapper {
        padding: 10px;
        box-sizing: border-box;
        background: #f7f7f7;
        display: flex;
        align-items: center;
        justify-content: space-between;
        position: relative;

        .input {
            background: #f1f1f1;
            border-radius: 110px;
            width: 88%;
            height: 40px;
            box-sizing: border-box;
            border: none;
            outline: none;
            padding: 10px 80px 10px 22px;
        }

        .icon {
            width: 32px;
            cursor: pointer;
        }

        .icon-refresh-rotate {
            transform: rotate(360deg);
            transition-duration: 1s;
        }


        .icon-clear {
            position: absolute;
            right: 16%;
            cursor: pointer;
        }
    }

    .list-wrapper {
        height: calc(100% - 60px);
        overflow-y: auto;

        .list-item {
            .item-title {
                display: flex;
                align-items: center;
                height: 42px;
                padding: 0 10px;
                box-sizing: border-box;
                background: #f7f7f7;
                font-weight: 500;
                font-size: 14px;
                color: #a2a2a2;

                .icon {
                    width: 24px;
                    height: 24px;
                    margin-right: 6px;
                }
            }
        }

        .item-detail {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 20px;
            box-sizing: border-box;
            cursor: pointer;

            .left {
                display: flex;

                .icon-currency {
                    width: 24px;
                    height: 24px;
                    margin-right: 12px;
                }

                .currency-info {
                    .name {
                        font-weight: 500;
                        font-size: 15px;
                        margin-bottom: 5px;
                    }

                    .desc {
                        font-weight: 400;
                        font-size: 12px;
                        color: #a2a2a2;
                    }
                }
            }

            .right {
                text-align: right;
                max-width: calc(100% - 150px);
                
                .num, .amount {
                    word-break: break-all;
                }

                .num {
                    font-weight: 500;
                    font-size: 15px;
                    margin-bottom: 5px;
                }

                .amount {
                    font-weight: 400;
                    font-size: 12px;
                    color: #a2a2a2;
                }
            }
        }

        .no-data {
            font-weight: 500;
            font-size: 22px;
            color: #BBBBBB;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }
}
</style>
