<!-- 查询管理-内部订单查询-委托单查询 -->
<template>
    <app-view>
        <template #header>
            <app-filter :option="filterOption" :rules="filterRules">
                <!-- 查询类型 -->
                <template #isHis="{ item }">
                    <el-form-item :label="item.label">
                        <el-select v-model="item.value">
                            <el-option :label="t('common.current')" :value="0" />
                            <el-option :label="t('common.history')" :value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('query.internal.order.date')" prop="date" v-if="item.value === 1">
                        <el-date-picker type="daterange" v-model="dateValue" value-format="YYYY-MM-DD"
                            :start-placeholder="t('common.start')" :end-placeholder="t('common.end')" />
                    </el-form-item>
                </template>
                <!-- 商品 -->
                <template #goodsId="{ item }">
                    <el-form-item :label="item.label">
                        <app-select-goods ref="goodsRef" v-model="item.value"
                            :params="{ marketId: queryParams.marketId ?? -1, goodsStatusIds: '3,6,7' }" />
                    </el-form-item>
                </template>
                <!-- 账户 -->
                <template #accountId="{ item }">
                    <el-form-item :label="item.label">
                        <app-select-account v-model="item.value" />
                    </el-form-item>
                </template>
            </app-filter>
        </template>
        <app-table :data="dataList" :columns="tableColumns" :loading="loading">
            <template #headerLeft>
                <app-operation :data-list="getActionButtons(['query_internal_order_export'])"
                    @click="openComponentOnClick" />
            </template>
            <!-- 操作 -->
            <template #operate="{ row }">
                <app-operation size="small" :data-list="getActionButtons(['query_internal_order_details'])"
                    @click="(code: string) => openComponent(code, row)" circle />
            </template>
            <template #footer>
                <app-pagination :total="total" v-model:page-size="pageSize" v-model:page-index="pageIndex"
                    @change="onSearch" />
            </template>
        </app-table>
        <component :is="componentMap.get(componentId)" v-bind="{ record, queryParams }" @closed="closeComponent"
            v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, FormRules } from 'element-plus'
import { formatDate } from '@/filters'
import { useEnum } from '@/hooks/enum'
import { useMarket } from '@/hooks/market'
import { useRequest } from '@/hooks/request'
import { useDataFilter } from '@/hooks/datatable-v2'
import { useOperation } from '@/hooks/operation'
import { queryCommissionSheet } from '@/services/api/order'
import AppTable from '@pc/components/base/table/index.vue'
import AppPagination from '@pc/components/base/pagination/index.vue'
import AppOperation from '@pc/components/base/operation/index.vue'
import AppFilter from '@pc/components/base/table-filter-v2/index.vue'
import AppSelectGoods from '@pc/components/modules/select-goods/index.vue'
import AppSelectAccount from '@pc/components/modules/select-account/index.vue'
import { i18n } from '@/stores'

const { getMarketOptions, getMarketById } = useMarket()

const buyOrSellEnum = useEnum('buyOrSell') // 方向
const buildtypeEnum = useEnum('buildtype') // 委托类型
const orderstatusEnum = useEnum('orderstatus') // 委托状态

const { global: { t } } = i18n
const goodsRef = ref() // 商品组件实例
const dateValue = ref<string[] | null>([])

const { componentMap, componentId, record, openComponent, closeComponent, getActionButtons } = useOperation<Model.CommissionSheetRsp>({
    onClose: () => onSearch()
})

const { dataList, total, pageSize, pageIndex, loading, run } = useRequest(queryCommissionSheet, {
    manual: true,
    params: {
        pageNum: 1,
        pageSize: 20
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const tableColumns = ref<Model.TableColumn[]>([
    { field: 'orderId', label: 'query.internal.order.orderId' },
    { field: 'accountNameId', label: 'query.internal.order.accountNameId' },
    { field: 'goodscode', label: 'query.internal.order.goodsCodeName' },
    { field: 'buildType', label: 'query.internal.order.buildType', formatValue: (val) => buildtypeEnum.getEnumTypeName(val) },
    { field: 'buyOrSell', label: 'query.internal.order.buyOrSell', formatValue: (val) => buyOrSellEnum.getEnumTypeName(val) },
    { field: 'orderPrice', label: 'query.internal.order.orderPrice' },
    { field: 'orderQty', label: 'query.internal.order.orderQty' },
    { field: 'tradeQty', label: 'query.internal.order.tradeQty' },
    { field: 'orderStatus', label: 'query.internal.order.orderStatus', formatValue: (val) => orderstatusEnum.getEnumTypeName(val) },
    { field: 'orderTime', label: 'query.internal.order.orderTime', formatValue: (val) => formatDate(val) },
    { field: 'tradeDate', label: 'query.internal.order.tradeDate' },
    { field: 'operate', label: 'common.operate', fixed: 'right' }
])

const { queryParams, filterOption, getQueryParams, resetFilters } = useDataFilter<Model.CommissionSheetReq>({
    filters: [
        {
            field: 'marketId',
            label: t('query.internal.order.marketid'),
            required: true,
            options: () => getMarketOptions([15, 97, 99], true),
            onChange: () => goodsRef.value.onReset()
        },
        {
            field: 'goodsId',
            label: t('query.internal.order.goodsId')
        },
        {
            field: 'isHis',
            label: t('query.internal.order.isHis'),
            value: 0
        },
        {
            field: 'buildType',
            label: t('query.internal.order.buildType'),
            options: () => buildtypeEnum.getEnumOptions()
        },
        {
            field: 'orderStatus',
            label: t('query.internal.order.orderStatus'),
            options: () => orderstatusEnum.getEnumOptions()
        },
        {
            field: 'orderId',
            label: t('query.internal.order.orderId')
        },
        {
            field: 'accountId',
            label: t('query.internal.order.accountName')
        },
        {
            field: 'excludeAccountIdsStr',
            label: t('query.internal.order.excludeAccountIdsStr'),
            placeholder: t('query.internal.order.tips1'),
            width: 260
        }
    ],
    buttons: [
        { label: t('operation.search'), className: 'el-button--primary', onClick: () => onSearch() },
        { label: t('operation.reset'), className: 'el-button--primary', validateEvent: false, onClick: () => onReset() }
    ]
})

// 表单验证规则
const filterRules: FormRules = {
    date: [{
        required: true,
        validator: () => dateValue.value?.length === 2
    }]
}

const onSearch = (clear = false) => {
    const qs = getQueryParams(clear)

    const [startDate, endDate] = dateValue.value || []
    qs.startDateHis = startDate
    qs.endDateHis = endDate

    const market = getMarketById(qs.marketId)
    qs.tradeMode = market?.trademode

    run(qs)
}

const onReset = () => {
    resetFilters()
    dateValue.value = []
    goodsRef.value.onReset()
}

const openComponentOnClick = (code: string) => {
    //openComponent(code)
}
</script>