<template>
    <div class="table_form-container">
        <!-- 搜索 -->
        <CustomerTradeOrderSearch :buttonLoading="loading" :search-form="searchForm" :search-options="searchOptions"
            @search="handleSearch" @reset="handleReset" @blur-input="getSubAccountList">
        </CustomerTradeOrderSearch>
        <div class="bar" v-if="searchForm.orderId === '1'">
            <div>持仓量:0</div>
            <div>手续费:0.00 USD</div>
            <div>交易盈亏:0.00 USD</div>
        </div>
        <!-- 表格 -->
        <CustomerTradeOrderTable :table-data="tableTree" :columns="tableColumnsOptions" row-key="id"
            :loading="loading" />

        <!-- 分页 -->
        <CustomerTradeOrderPagination v-model="currentPage" v-model:pageSizeValue="pageSize" :total="total"
            @pagination-change="handlePaginationChange" />

    </div>
</template>

<script setup lang="ts">

defineOptions({
    name: 'History'
})
// 组件
import CustomerTradeOrderSearch from '@/components/common/Search.vue'
import CustomerTradeOrderTable from '@/components/common/Table.vue'
import { usePageLoading } from '@/composables/useLoading'
import CustomerTradeOrderPagination from '@/components/common/Pagination.vue'
// 配置以及表单验证
import { search, tradeOrderTableColumns, positionOrderTableColumns } from './options'

// 接口
import { getCustomTradeOrderListApi, getSubAccountListApi } from '@/api/modules/agent/customerTradeOrder'
// 本地存储
import { getStorage } from '@/utils/storage'
// 日期处理
import dayjs from 'dayjs'

// 公用方法
import { getRecentSevenDays } from '@/utils/handleTime.ts'

/**
 * @description: 定义搜索数据
 */
// 获取近一周的时间范围
const initTime = getRecentSevenDays()
const searchForm = ref<any>({
    accountName: '',
    orderId: '2',
    tradeType: '',
    dateRange: [initTime.start, initTime.end],
    subAccountName: '',
})
const searchOptions = ref(search)
const subAccountOptions = ref([])
//获取用户数据，用来判断当前查询的是不是自己的账号
const userInfo: any = getStorage('userInfo')

const { loading, startLoading, stopLoading } = usePageLoading()
/**
 * @description: 定义表格数据
 */
const tableTree = ref([])
const tableColumnsOptions = computed(() => {
    return searchForm.value.orderId === "1" ? tradeOrderTableColumns : positionOrderTableColumns
})
/**
 * @description: 定义分页数据
 */
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
/**
 * @description: 定义公共请求数据方法
 */
const getCustomerTradeOrderList = async () => {
    try {
        startLoading()
        // 从 dateRange 中提取开始和结束时间
        let startTime = initTime.start
        let endTime = initTime.end
        if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
            startTime = dayjs(searchForm.value.dateRange[0]).format('YYYY-MM-DD HH:mm:ss')
            endTime = dayjs(searchForm.value.dateRange[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        const params = {
            page: currentPage.value,
            page_size: pageSize.value,
            user_name: searchForm.value.accountName,
            account_id: searchForm.value.subAccountName || '',
            order_no: '',
            type: searchForm.value.tradeType,
            start_time: startTime,
            end_time: endTime,
        }
        console.log(params)
        const data: any = await getCustomTradeOrderListApi(params)
        //表格数据
        // table数据映射
        tableTree.value = data.data.map((item: any) => ({
            accountName: item.user.username,
            orderId: item.order_id,
            variety: item.variety.name,
            type: item.type === 1 ? '买入' : '卖出',
            quantity: item.num,
            openPrice: item.build_price,
            closePrice: item.close_price,
            closeProfitLoss: item.profit_loss,
            amount: item.amount,
            createdTime: item.created_at,
        }))

        //分页数据
        total.value = data.total
        currentPage.value = data.current_page
        pageSize.value = Number(data.per_page)
    } finally {

        stopLoading()
    }
}

const getSubAccountList = async () => {
    const accountName = searchForm.value.accountName
    // 空值不请求
    if (!accountName) {
        subAccountOptions.value = []
        searchForm.value.subAccountName = ''
        return
    }

    try {
        const params = {
            username: userInfo.username === searchForm.value.accountName ? '' : accountName,
        }
        const data: any = await getSubAccountListApi(params)
        subAccountOptions.value = data.map((item: any) => ({
            label: item.name || item.account_name, // 子账户名称
            value: item.id || item.account_id    // 子账户值
        }))
        searchOptions.value.find(item => item.prop === 'subAccountName')!.options = subAccountOptions.value
    } catch (error) {
        subAccountOptions.value = []
        console.error('获取子账户失败', error)
    }
}

/**
 * @description: 页面加载完成需要请求的数据
 */
onMounted(() => {
    getCustomerTradeOrderList()
})

/**
 * @description: 定义搜索方法
 */
const handleSearch = () => {
    getCustomerTradeOrderList()
}
const handleReset = () => {
    searchForm.value = {
        accountName: '',
        orderId: '2',
        tradeType: '',
        dateRange: [initTime.start, initTime.end],
        subAccountName: '',
    }
    getCustomerTradeOrderList()
}
/**
 * @description: 定义分页方法
 */
const handlePaginationChange = (page: { currentPage: number; pageSize: number }) => {
    currentPage.value = page.currentPage
    pageSize.value = page.pageSize
    getCustomerTradeOrderList()
}
</script>

<style scoped lang="scss">
.bar {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 20px;
}
</style>
