<!-- 交易商管理-个性化管理-交易商分组管理-编辑 -->
<template>
    <app-drawer :title="t('investor.custom.group.edit.title')" width="900" v-model:show="show" :refresh="refresh"
        :loading="loading">
        <el-form ref="formRef" label-width="140px" :model="formData" :rules="formRules" :show-message="false">
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('investor.custom.group.edit.subtitle1') }}</legend>
                <el-form-item :label="t('investor.custom.group.edit.areauserid')" prop="areauserid"
                    v-if="userStore.userInfo.releType !== 2">
                    <app-select-member ref="areauseridRef" v-model="formData.areauserid" :params="{ usertype: '2' }"
                        :placeholder="t('investor.custom.group.edit.tips1')" />
                </el-form-item>
                <el-form-item :label="t('investor.custom.group.edit.groupname')" prop="groupname">
                    <el-input v-model="formData.groupname" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('investor.custom.group.edit.customertype')" prop="customertype">
                    <el-select v-model="formData.customertype" clearable>
                        <template v-for="(item, index) in configs" :key="index">
                            <el-option :label="customerTypeEnum.getEnumTypeName(item.customertype)"
                                :value="item.customertype" />
                        </template>
                    </el-select>
                </el-form-item>
            </fieldset>
        </el-form>
        <app-table-details :title="t('investor.custom.group.edit.subtitle2')" :data="selectedItem" :label-width="160"
            :cell-props="detailProps" :column="2" v-if="selectedItem" />
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.close') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ t('operation.save') }}</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, computed, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useEnum } from '@/hooks/enum'
import { addPersonalized, getRiskRatioTypeForMarketer } from '@/services/api/investor'
import { CellProp } from '@pc/components/base/table-details/types'
import { i18n, useUserStore } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppSelectMember from '@pc/components/modules/select-member/index.vue'
import AppTableDetails from '@pc/components/base/table-details/index.vue'

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

const flagEnum = useEnum('flag') // 确认状态
const customerTypeEnum = useEnum('customerType') // 风险客户类别

const userStore = useUserStore()
const { global: { t } } = i18n
const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)
const loading = ref(false)
const configs = reactive<Investor.RiskRatioTypeForMarketerRsp[]>([])

const areauseridRef = ref() // 经纪会员组件实例

const formData = ref<Investor.AddPersonalizedReq>({
    groupname: ''
})

// 选中的风险率配置
const selectedItem = computed(() => configs.find((e) => e.customertype === formData.value.customertype))

customerTypeEnum.registerEnumReadyCallback(async () => {
    const options = customerTypeEnum.getEnumOptions()
    for (const item of options) {
        const res = await getRiskRatioTypeForMarketer({
            data: {
                riskcontrolmode: 1,
                customertype: item.value
            }
        })
        if (res.data) {
            configs.push(res.data)
        }
    }
    formData.value.customertype = selectedItem.value?.customertype
})

// 表单验证规则
const formRules: FormRules = {
    areauserid: [{ required: true }],
    groupname: [{ required: true }],
}

const detailProps = computed<CellProp[]>(() => {
    const { notesaferatio } = selectedItem.value ?? {}
    return [
        { prop: 'riskcontrolmode', label: 'investor.custom.group.edit.riskcontrolmode', formatValue: (val) => val === 1 ? t('investor.custom.group.edit.riskcontrolmode1') : t('investor.custom.group.edit.riskcontrolmode2') },
        { prop: 'customertype', label: 'investor.custom.group.edit.customertype1', formatValue: (val) => customerTypeEnum.getEnumTypeName(val) },
        { prop: 'riskratiocalcmode', label: 'investor.custom.group.edit.riskratiocalcmode', formatValue: (val) => val === 1 ? t('investor.custom.group.edit.riskratiocalcmode1') : t('investor.custom.group.edit.riskratiocalcmode2') },
        { prop: 'notemarginriskratio', label: 'investor.custom.group.edit.notemarginriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'addmarginriskratio', label: 'investor.custom.group.edit.addmarginriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'cutriskratio', label: 'investor.custom.group.edit.cutriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'cutbackriskratio', label: 'investor.custom.group.edit.cutbackriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'notesaferatio', label: 'investor.custom.group.edit.notesaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'addsaferatio', label: 'investor.custom.group.edit.addsaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'recoversaferatio', label: 'investor.custom.group.edit.recoversaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'cutsaferatio', label: 'investor.custom.group.edit.cutsaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'isdefault', label: 'investor.custom.group.edit.isdefault', formatValue: (val) => flagEnum.getEnumTypeName(val) },
        { prop: 'markets', label: 'investor.custom.group.edit.markets' },
    ]
})

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            loading.value = true
            addPersonalized({
                data: formData.value
            }).then(() => {
                ElMessage.success(t('common.tips3'))
                onCancel(true)
            }).catch((err) => {
                ElMessage.error(t('common.tips4') + err)
            }).finally(() => {
                loading.value = false
            })
        }
    })
}

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

onMounted(() => {
    const record = props.record
    if (record) {
        formData.value = {
            autoid: record.autoid,
            areauserid: record.areauserid,
            customertype: record.customertype,
            groupname: record.groupname,
        }
        areauseridRef.value.onReset(record.areauserid)
    }
})
</script>