<!-- 查询管理-内部订单查询-持仓单查询 -->
<template>
    <app-view>
        <template #header>
            <el-form ref="formRef" class="el-form--filter" :model="queryParams" :rules="formRules"
                :show-message="false">
                <el-form-item :label="t('query.internal.position.marketid')" prop="marketId">
                    <el-select v-model="queryParams.marketId">
                        <template v-for="item in getMarketOptions([15, 40, 41, 48, 51, 71, 97, 99], true)"
                            :key="item.value">
                            <el-option :label="item.label" :value="item.value" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('query.internal.position.buyOrSell')" prop="buyOrSell">
                    <el-select v-model="queryParams.buyOrSell" clearable>
                        <template v-for="item in getBuyOrSellList()" :key="item.value">
                            <el-option :label="item.label" :value="item.value" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('query.internal.position.isHis')" prop="isHis">
                    <el-select v-model="queryParams.isHis" @change="onTypeChange">
                        <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.position.date')" prop="date" v-if="queryParams.isHis === 1">
                    <el-date-picker type="daterange" v-model="dateValue" value-format="YYYY-MM-DD"
                    :start-placeholder="t('common.start')" :end-placeholder="t('common.end')" @change="onDateChange" />
                </el-form-item>
                <el-form-item :label="t('query.internal.position.tradeId')" prop="tradeId">
                    <el-input type="number" v-model="queryParams.tradeId" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('query.internal.position.goodsId')" prop="goodsId">
                    <el-input type="number" v-model="queryParams.goodsId" :placeholder="t('query.internal.position.tips1')" />
                </el-form-item>
                <el-form-item :label="t('query.internal.position.loginId')" prop="loginId">
                    <el-input v-model="queryParams.loginId" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('query.internal.position.accountId')" prop="accountId">
                    <el-input v-model="queryParams.accountId" :placeholder="t('query.internal.position.tips2')" />
                </el-form-item>
                <el-form-item :label="t('query.internal.position.parentAreaId')" prop="parentAreaId">
                    <el-input type="number" v-model="queryParams.parentAreaId" :placeholder="t('query.internal.position.tips3')" />
                </el-form-item>
                <el-form-item :label="t('query.internal.position.validHolderQty')" prop="validHolderQty">
                    <el-switch v-model="queryParams.validHolderQty" active-value="1" inactive-value="0" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSearch(false)">{{ t('operation.search') }}</el-button>
                    <el-button type="primary" @click="onSearch(true)">{{ t('operation.reset') }}</el-button>
                </el-form-item>
            </el-form>
        </template>
        <app-table :data="dataList" :columns="tableColumns" :loading="loading">
            <template #headerLeft>
                <app-operation :data-list="getActionButtons(['query_internal_position_export'])"
                    @click="openComponentOnClick" />
            </template>
            <!-- 操作 -->
            <template #operate="{ row }">
                <app-operation size="small" :data-list="getActionButtons(['query_internal_position_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, FormInstance, FormRules } from 'element-plus'
import { formatDate } from '@/filters'
import { getBuyOrSellList, getBuyOrSellName } from '@/constants/order'
import { useEnum } from '@/hooks/enum'
import { useMarket } from '@/hooks/market'
import { useRequest } from '@/hooks/request'
import { useOperation } from '@/hooks/operation'
import { queryPositionSheet } 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 { i18n } from '@/stores'

const { getMarketOptions } = useMarket()

// 机构类型
const usertype2Enum = useEnum('usertype2')

const { global: { t } } = i18n
const formRef = ref<FormInstance>()
const dateValue = ref<string[] | null>([])

const queryParams = ref<Partial<Model.PositionSheetReq>>({
    isHis: 0,
    validHolderQty: '1'
})

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

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

const tableColumns = ref<Model.TableColumn[]>([
    { field: 'tradeid', label: 'query.internal.position.tradeid' },
    { field: 'tradedate', label: 'query.internal.position.tradedate' },
    { field: 'accountNameId', label: 'query.internal.position.accountNameId' },
    { field: 'goodsCodeName', label: 'query.internal.position.goodsCodeName' },
    { field: 'buyorsell', label: 'query.internal.position.buyorsell', formatValue: (val) => getBuyOrSellName(val) },
    { field: 'openqty', label: 'query.internal.position.openqty' },
    { field: 'openprice', label: 'query.internal.position.openprice' },
    { field: 'tradeamount', label: 'query.internal.position.tradeamount' },
    { field: 'holderqty', label: 'query.internal.position.holderqty' },
    { field: 'holderprice', label: 'query.internal.position.holderprice' },
    { field: 'holderamount', label: 'query.internal.position.holderamount' },
    { field: 'actuallYplS', label: 'query.internal.position.actuallYplS' },
    { field: 'holderdays', label: 'query.internal.position.holderdays' },
    { field: 'tradetime', label: 'query.internal.position.tradetime', formatValue: (val) => formatDate(val) },
    { field: 'usertype', label: 'query.internal.position.usertype', formatValue: (val) => usertype2Enum.getEnumTypeName(val) },
    { field: 'memberusername', label: 'query.internal.position.memberusername' },
    { field: 'parentusername', label: 'query.internal.position.parentusername' },
    { field: 'marketname', label: 'query.internal.position.marketname' },
    { field: 'operate', label: 'common.operate', fixed: 'right' }
])

// 表单验证规则
const formRules: FormRules = {
    marketId: [{ required: true }],
    date: [{
        required: true,
        validator: (rule, value, callback) => {
            if (dateValue.value && dateValue.value.length === 2) {
                callback()
            } else {
                callback(new Error(t('common.pleasechoicedate')))
            }
        },
    }],
}

// 选择单据类型
const onTypeChange = (value: number) => {
    if (!value) {
        dateValue.value = []
        onDateChange()
    }
}

// 选择日期
const onDateChange = () => {
    const [startDate, endDate] = dateValue.value || []
    queryParams.value.startDate = startDate
    queryParams.value.endDate = endDate
}

const onSearch = (clear = false) => {
    if (clear) {
        queryParams.value = {
            isHis: 0,
            validHolderQty: '1'
        }
        dateValue.value = []
    } else {
        formRef.value?.validate((valid) => {
            if (valid) {
                run(queryParams.value)
            }
        })
    }
}

const openComponentOnClick = (code: string) => {
    formRef.value?.validate((valid) => {
        if (valid) {
            openComponent(code)
        }
    })
}
</script>