<!-- 账号管理-资金账户管理-编辑 -->
<template>
    <app-drawer :title="t('account.fundacct.edit.title')" width="900" v-model:show="show" :refresh="refresh" :loading="loading">
        <el-form ref="formRef" class="el-form--horizontal" label-width="180px" :model="formData" :show-message="false">
            <el-form-item :label="t('account.fundacct.edit.accountId')">
                <span>{{ record.accountId }}</span>
            </el-form-item>
            <el-form-item :label="t('account.fundacct.edit.accounttype')" v-if="record.isMain === 1">
                <span>{{ mainaccounttypeEnum.getEnumTypeName(record.isMain) }}</span>
            </el-form-item>
            <template v-else>
                <el-form-item :label="t('account.fundacct.edit.parentAccountId')">
                    <span>{{ record.parentAccountId }}</span>
                </el-form-item>
            </template>
            <template v-if="data && data.selfFlag === 1">
                <template v-if="!data.cannotEdit">
                    <el-form-item class="el-form-item--row" :label="t('account.fundacct.edit.markets')">
                        <el-table ref="tableRef" :data="formData.dtype" @selection-change="handleSelectionChange"
                            border>
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="marketName" :label="t('account.fundacct.edit.marketName')" />
                            <el-table-column prop="tradeMode" :label="t('account.fundacct.edit.tradeMode')"
                                v-if="multipleSelection.some((e) => e.tradeProperty === 4 || e.tradeMode === 79)">
                                <template #default="{ row }">
                                    <span v-if="row.tradeMode === 79">{{ t('account.fundacct.edit.tradeMode79') }}</span>
                                    <template v-else-if="row.tradeMode === 17 && row.tradeProperty === 4">
                                        <el-select v-model="row.dtype">
                                            <template v-for="item in getMarketbstypeOptions(row.fdType)"
                                                :key="item.value">
                                                <el-option :label="item.label" :value="item.value" />
                                            </template>
                                        </el-select>
                                    </template>
                                    <template v-else>
                                        {{ handleNoneValue() }}
                                    </template>
                                </template>
                            </el-table-column>
                            <el-table-column prop="tradeMode" :label="t('account.fundacct.edit.tradeMode1')"
                                v-if="multipleSelection.some((e) => e.tradeProperty === 4 || [77, 78].includes(e.tradeMode))">
                                <template #default="{ row }">
                                    <span v-if="[77, 78].includes(row.tradeMode)">{{ t('account.fundacct.edit.tradeMode78') }}</span>
                                    <template v-else-if="row.tradeProperty === 4">
                                        <el-select v-model="row.spotRightType">
                                            <template v-for="item in getMarketbstypeOptions(row.fspotRightType)"
                                                :key="item.value">
                                                <el-option :label="item.label" :value="item.value" />
                                            </template>
                                        </el-select>
                                    </template>
                                    <template v-else>
                                        {{ handleNoneValue() }}
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </template>
                <el-form-item class="el-form-item--row" :label="t('account.fundacct.edit.tips1')">
                    <!-- <el-checkbox-group v-model="formData.loginIds">
                        <template v-for="value in data.loginaccount" :key="value">
                            <el-checkbox :label="value" :value="value" />
                        </template>
                    </el-checkbox-group> -->
                    {{ handleNoneValue(data.loginaccount.join(',')) }}
                </el-form-item>
                <el-form-item class="el-form-item--row" :label="t('account.fundacct.edit.tips2')">
                    {{ handleNoneValue(data.defaultloginaccount.join(',')) }}
                </el-form-item>
            </template>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.close') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ t('operation.submit') }}</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, toRaw, nextTick } from 'vue'
import { ElMessage, FormInstance, TableInstance } from 'element-plus'
import { handleNoneValue } from '@/filters'
import { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { updateTaAccountInit, updateTaAccount, queryTaAccountDetail } from '@/services/api/account'
import { i18n } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'

const props = defineProps({
    record: {
        type: Object as PropType<Model.TaAccountRsp>,
        required: true
    }
})

const mainaccounttypeEnum = useEnum('mainaccounttype') // 账户类型
const marketbstypeEnum = useEnum('marketbstype')

const t = i18n.global.t
const tableRef = ref<TableInstance>()
const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)
const multipleSelection = ref<Model.UpdateTaAccountReq['dtype']>([]) // 已选中的市场数据

const formData = reactive<Partial<Model.UpdateTaAccountReq>>({
    dtype: [],
    loginIds: []
})

const { data } = useRequest(updateTaAccountInit, {
    params: {
        accountId: props.record.accountId
    },
    onSuccess: (res) => {
        formData.dtype = Object.values(res.data.clildmarkets)
        // 初始化已选中的市场
        nextTick(() => {
            formData.dtype?.forEach((e) => {
                if (e.checked) {
                    tableRef.value?.toggleRowSelection(e)
                }
            })
        })
    }
})

const { loading } = useRequest(queryTaAccountDetail, {
    params: {
        accountId: props.record.accountId
    },
    onSuccess: (res) => {
        const data = res.data
        formData.accountId = data.accountId
        formData.loginIds = data.loginIds
        formData.relatedaccountstatus = data.relatedAccountStatus
        formData.relateduserid = data.relatedUserId
        formData.userid = data.userId
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const getMarketbstypeOptions = (type: number) => {
    switch (type) {
        case 1:
            return marketbstypeEnum.getEnumOptions()
        case 2:
            return marketbstypeEnum.getEnumOptions([1, 3], true)
        case 3:
            return marketbstypeEnum.getEnumOptions([1, 2], true)
        default:
            return marketbstypeEnum.getEnumOptions(0)
    }
}

const handleSelectionChange = (selection: Model.UpdateTaAccountReq['dtype']) => {
    multipleSelection.value = selection
}

const onCancel = (isRefresh = false) => {
    show.value = false
    refresh.value = isRefresh
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            loading.value = true
            const rawData = toRaw(formData)
            rawData.dtype = multipleSelection.value

            updateTaAccount({
                data: rawData
            }).then(() => {
                ElMessage.success(t('common.tips3'))
                onCancel(true)
            }).catch((err) => {
                ElMessage.error(t('common.tips4') + err)
            }).finally(() => {
                loading.value = false
            })
        }
    })
}
</script>