<template>
    <div class="table_form-container">
        <!-- 搜索 -->
        <CustomerTradeOrderSearch :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'

// 公用方法

/**
 * @description: 定义搜索数据
 */
// 获取近一周的时间范围
const dateRange = {
    start: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
    end: dayjs().format('YYYY-MM-DD'),
}
const searchForm = ref({
    accountName: '',
    orderId: '2',
    tradeType: '',
    start_time: dateRange.start,
    end_time: dateRange.end,
    startTime: dateRange.start,
    endTime: dateRange.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()
        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: dateRange.start,
            end_time: dateRange.end,
        }
        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: '',
        tradeType: '',
        startTime: dateRange.start,
        endTime: dateRange.end,
        start_time: dateRange.start,
        end_time: dateRange.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>
