<!-- 会员机构管理-机构管理-风控个性化设置-新增/修改 -->
<template>
    <app-drawer :title="t('member.institution.riskcfg.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.riskcfg.edit.subtitle1') }}</legend>
                <el-form-item :label="t('member.institution.riskcfg.edit.userid')" prop="userid">
                    <app-select-member ref="useridRef" v-model="formData.userid"
                        :params="{ usertype: '2', roles: '6,8' }" :placeholder="t('investor.custom.riskcfg.edit.tips1')"
                        :disabled="!!record" @change="onMemberChange" />
                </el-form-item>
                <el-form-item :label="t('investor.custom.riskcfg.edit.accountid')" prop="accountid">
                    <el-select v-model="formData.accountid" :disabled="!!record">
                        <template v-for="(value, index) in taaccountList" :key="index">
                            <el-option :label="value" :value="value" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('investor.custom.riskcfg.edit.customertype')" prop="customertype">
                    <el-select v-model="formData.customertype">
                        <template v-for="(item, index) in configs" :key="index">
                            <el-option :label="marketerTypeEnum.getEnumTypeName(item.customertype)"
                                :value="item.customertype" />
                        </template>
                    </el-select>
                </el-form-item>
            </fieldset>
        </el-form>
        <app-table-details :title="t('investor.custom.riskcfg.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 { useRequest } from '@/hooks/request'
import { getRiskRatioTypeForMarketer, getTaaccountList } from '@/services/api/investor'
import { addAccountRiskConfig } from '@/services/api/member'
import { CellProp } from '@pc/components/base/table-details/types'
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'
import { i18n } from '@/stores'

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

const flagEnum = useEnum('flag') // 确认状态
const marketerTypeEnum = useEnum('marketerType') // 风险率类型

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 useridRef = ref() // 交易商组件实例

const formData = ref<Partial<Investor.AddAccountRiskConfigReq>>({})

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

marketerTypeEnum.registerEnumReadyCallback(async () => {
    const options = marketerTypeEnum.getEnumOptions()
    for (const item of options) {
        const res = await getRiskRatioTypeForMarketer({
            data: {
                riskcontrolmode: 2,
                customertype: item.value
            }
        })
        if (res.data) {
            configs.push(res.data)
        }
    }
})

const { dataList: taaccountList, run } = useRequest(getTaaccountList, {
    manual: true,
})

const onMemberChange = (item?: Model.OrganSelectRsp) => {
    taaccountList.value = []
    formData.value.accountid = undefined
    if (item) run({ userid: item.userid })
}

// 表单验证规则
const formRules: FormRules = {
    userid: [{ required: true }],
    accountid: [{ required: true }],
    customertype: [{ required: true }],
}

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

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            loading.value = true
            addAccountRiskConfig({
                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 = {
            accountid: record.accountid,
            customertype: record.customertype,
            userid: record.userid
        }
        useridRef.value.onReset(record.userid)
    }
})
</script>