<!-- 货币列表 -->
<template>
    <div class="currency-list-wrapper">
        <div class="search-input-wrapper">
            <input class="input" :style="{ width: !showRefresh ? '100%' : '88%' }" v-model="keywords"
                placeholder="Search name" @input="onInput" />

            <img :src="require('@/assets/svg/icon-form-refresh.svg')" v-if="showRefresh" class="icon"
                :class="{ 'icon-refresh-rotate': refreshRotate }" @click="refresh">

            <img :src="require('@/assets/svg/icon-clear-search.svg')" class="icon-clear" v-if="keywords"
                :style="{ right: !showRefresh ? '6%' : '16%' }" @click="clearIpt">
        </div>
        <div class="list-wrapper" :style="{ 'paddingBottom': showGeneralLottery ? '50px' : '0' }" 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)">
                            <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.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">
                    Not found
                </div>
            </div>
            <!-- 显示搜索结果列表 -->
            <div class="search-list" v-else>
                <div class="item-detail" v-for="(data, idx) in searchList" :key="idx" @click="selectCurrency(data)">
                    <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">
                    Not found
                </div>
            </div>
            <!-- 添加通用奖品 -->
            <div class="add-general-lottery" v-if="showGeneralLottery" @click="addGeneralLottery">
                <img class="add-general-lottery-icon" :src="require('@/assets/svg/icon-add-white.svg')" />
                <span class="add-general-lottery-text">Customize</span>
            </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
    },
    showRefresh: {
        type: Boolean,
        default: true
    },
    // 是否显示 通用奖品选项
    showGeneralLottery: {
        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,
    requestIng: false
};
let show_empty = ref(false);
const emits = defineEmits(["selectCurrency", "setCurrencyList", "addGeneralLottery"]);

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(() => {
            listReqParams.params.pageNum = 1;
            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 currencyCategories = res.data.currencyCategories;

                let arr = [];
                for (let i = 0; i < currencyCategories.length; i++) {
                    let item = currencyCategories[i];
                    arr = arr.concat(item.data);
                }

                currencyCategories[0]['data'] = arr;

                let list = currencyCategories[0];

                if (list && list.data && list.data.length) {
                    searchList.value = list.data;
                } else {
                    searchList.value = [];
                }
            } else {
                searchList.value = [];
            }
        }
    })
}, 500)

/**
 * 获取货币列表
 */
const getCurrencyInfoList = (_params = {}) => {

    if (listReqParams.requestIng) {
        return;
    }
    listReqParams.requestIng = true;
    if (_params.pageNum) {
        listReqParams.params.pageNum = _params.pageNum;
    }
    let params = {
        params: {
            pageNum: listReqParams.params.pageNum,
            pageSize: listReqParams.params.pageSize,
            filterFiatCurrency: props.page == 'top-up',
            filterEmptyBalance: props.filterEmptyBalance
        }
    };
    getCurrencyInfo(params).then(res => {
        listReqParams.requestIng = false;
        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;

                    if (currencyCategories.length) {
                        let tokenData = currencyCategories.find(item => item.type == 2);
                        if (tokenData && tokenData.data && tokenData.data.length) {
                            let index = data.findIndex(item => item.type == 2);
                            let tokenList = data[index]['data'];
                            data[index]['data'] = tokenList.concat(tokenData.data);
                            currencyInfoList.value = data;
                        }
                    }

                }
                listReqParams.loadMore = false;
            } else {
                show_empty.value = true
            }
        }
    }).catch(err => {
        listReqParams.requestIng = false;
    })
}


/**
 * 同步链上交易
 */
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 - 50)
    ) {
        listReqParams.loadMore = true;
        listReqParams.params.pageNum++;
        getCurrencyInfoList();
    }
}

/**
 * 添加通用奖品 按钮点击
 */
const addGeneralLottery = () => {
    emits('addGeneralLottery');
}

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

defineExpose({
    getCurrencyInfoList,
    refresh
})

</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;
            color: #adadad;
        }

        input::placeholder {
            color: #adadad;
        }

        .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-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;
                    margin-top: 4px;
                }

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

                    .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%);
        }

        .add-general-lottery {
            position: absolute;
            bottom: 0;
            left: 0;
            display: flex;
            width: 100%;
            height: 50px;
            align-items: center;
            justify-content: center;
            background-color: #1D9BF0;
            color: #fff;
            cursor: pointer;

            &-icon {
                margin-right: 8px;
            }

            &-text {
                font-size: 16px;
            }
        }
    }
}
</style>
