<!-- 账号管理-交易账号管理-新增/修改 -->
<template>
    <app-drawer :title="record ? t('account.tradingacct.edit.title') : t('account.tradingacct.edit.title1')" width="480" v-model:show="show" :refresh="refresh" :loading="loading">
        <el-form ref="formRef" class="el-form--vertical" label-width="120px" :model="formData" :rules="formRules">
            <el-form-item :label="t('account.tradingacct.edit.loginid')">
                {{ formData.loginid }}
            </el-form-item>
            <el-form-item :label="t('account.tradingacct.edit.password')" prop="password" v-if="!record">
                <el-popover placement="top" trigger="click" :width="244" :hide-after="0"
                    :content="validateRules.password.message">
                    <template #reference>
                        <el-input type="password" v-model="formData.password" maxlength="50"
                            :placeholder="t('common.pleaseenter')" />
                    </template>
                </el-popover>
            </el-form-item>
            <el-form-item :label="t('account.tradingacct.edit.confirmPassword')" prop="confirmPassword" v-if="!record">
                <el-input type="password" v-model="formData.confirmPassword" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item :label="t('account.tradingacct.edit.accountids')" prop="accountids">
                <el-select v-model="selectedAccountIds" :placeholder="t('common.pleasechoice')" multiple>
                    <el-option v-for="item in initData?.taaccounts" :key="item.accountid" :label="item.accountid"
                        :value="item.accountid" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ t('operation.submit') }}</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, PropType } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { validateRules } from '@/constants/regex'
import { useRequest } from '@/hooks/request'
import { tradingAccView, tradingAccInitAdd, tradingAccAdd, tradingAccEdit } from '@/services/api/account'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import { i18n } from '@/stores'

const props = defineProps({
    record: {
        type: Object as PropType<Model.TradingAccRsp>
    }
})

const { global: { t } } = i18n

const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)
const loading = ref(false)
const selectedAccountIds = ref<number[]>([])

const formData = ref<Model.TradingAccAddReq>({
    accountids: '',
    confirmPassword: '',
    loginid: props.record?.loginid ?? 0,
    loginusertype: 2,
    password: ''
})

const { data: initData } = useRequest(tradingAccInitAdd, {
    onSuccess: (res) => {
        if (props.record) {
            loading.value = true
            tradingAccView({
                data: {
                    loginid: formData.value.loginid
                }
            }).then((res) => {
                selectedAccountIds.value = res.data.accountIdS
            }).finally(() => {
                loading.value = false
            })
        } else {
            formData.value.loginid = res.data.loginid
        }
    }
})

// 表单验证规则
const formRules: FormRules = {
    password: [{
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (validateRules.password.validate(value)) {
                callback()
            } else {
                callback(new Error(t('account.tradingacct.password.tips2')))
            }
        },
    }],
    confirmPassword: [{
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (value === formData.value.password) {
                callback()
            } else {
                callback(new Error(t('account.tradingacct.password.tips3')))
            }
        },
    }],
    accountids: [{
        required: true,
        validator: (rule, value, callback) => {
            if (selectedAccountIds.value.length) {
                callback()
            } else {
                callback(new Error(t('account.tradingacct.edit.tips1')))
            }
        },
    }]
}

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

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            const rawData = { ...formData.value }
            rawData.accountids = selectedAccountIds.value.join(',')
            loading.value = true

            if (props.record) {
                tradingAccEdit({
                    data: rawData
                }).then(() => {
                    ElMessage.success(t('account.tradingacct.edit.tips4'))
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error(t('account.tradingacct.edit.tips5') + err)
                }).finally(() => {
                    loading.value = false
                })
            } else {
                tradingAccAdd({
                    data: rawData
                }).then(() => {
                    ElMessage.success(t('account.tradingacct.edit.tips6'))
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error(t('account.tradingacct.edit.tips7') + err)
                }).finally(() => {
                    loading.value = false
                })
            }
        }
    })
}
</script>