<!-- 交易商管理-个性化管理-交易商个性化-编辑 -->
<template>
    <app-drawer :title="t('investor.custom.tradecfg.edit.title')" width="1100" v-model:show="show" :refresh="refresh"
        :loading="loading">
        <el-form ref="formRef" label-width="140px" :model="formData" :show-message="false">
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('investor.custom.tradecfg.edit.subtitle1') }}</legend>
                <el-form-item :label="t('investor.custom.tradecfg.edit.usergroupid')">
                    {{ handleNoneValue(groupItem?.name) }}
                </el-form-item>
                <el-form-item :label="t('investor.custom.tradecfg.edit.marketid')">
                    {{ handleNoneValue(marketItem?.name) }}
                </el-form-item>
                <el-form-item :label="t('investor.custom.tradecfg.edit.goodsid')">
                    {{ handleNoneValue(goodsItem?.[getLocalizedKey()]) }}
                </el-form-item>
                <el-form-item :label="t('investor.custom.tradecfg.edit.paramid')" prop="paramid">
                    <el-select v-model="formData.paramid" @change="onResultChange" clearable>
                        <template v-for="(item, index) in resultData?.results" :key="index">
                            <el-option :label="customerTypeEnum.getEnumTypeName(item.enumitemname)"
                                :value="item.enumitemname" />
                        </template>
                    </el-select>
                </el-form-item>
            </fieldset>
            <app-table :data="record.druleList" :columns="ruleColumns">
                <!-- 商品设置值 -->
                <template #paramvalue="{ row }">
                    <span v-if="row.ruleid === 105">{{ feetypeEnum.getEnumTypeName(row.paramvalue) }}</span>
                    <span v-else>{{ row.paramvalue || 0 }}</span>
                </template>
                <!-- 会员 -->
                <template #dvalue="{ row }">
                    <span v-if="row.ruleid === 105">
                        {{ handleNoneValue(feetypeEnum.getEnumTypeName(row.dvalue)) }}
                    </span>
                    <span v-else>{{ handleNoneValue(row.dvalue) }}</span>
                </template>
                <!-- 个性化 -->
                <template #cvalue="{ row, index }">
                    <template v-if="formData.ruleList[index]">
                        <el-select v-model="formData.ruleList[index].paramvalue" clearable v-if="row.ruleid === 105">
                            <template v-for="item in feetypeEnum.getEnumOptions()" :key="item.id">
                                <el-option :label="item.label" :value="item.value" />
                            </template>
                        </el-select>
                        <el-input-number v-model="formData.ruleList[index].paramvalue"
                            :placeholder="t('common.pleaseenter')" v-else />
                    </template>
                </template>
            </app-table>
            <app-table :data="record.dfeeList" :columns="feeColumns">
                <!-- 商品设置值 -->
                <template #exchangevalue="{ row }">
                    <template v-if="row.feealgorithm">
                        {{ row.exchangevalue + (row.feealgorithm === 1 && '‱') }}
                    </template>
                    <template v-else>
                        {{ handleNoneValue() }}
                    </template>
                </template>
                <!-- 会员设置值 -->
                <template #dvalue="{ row }">
                    <template v-if="row.drithm">
                        {{ row.dvalue + (row.drithm === 1 && '‱') }}
                    </template>
                    <template v-else>
                        {{ handleNoneValue() }}
                    </template>
                </template>
                <!-- 最小值 -->
                <template #memberminvalue="{ row }">
                    {{ row.memberminvalue + (row.feealgorithm === 1 && '‱') }}
                </template>
                <!-- 最大值 -->
                <template #membermaxvalue="{ row }">
                    {{ row.membermaxvalue + (row.feealgorithm === 1 && '‱') }}
                </template>
                <!-- 服务费 -->
                <template #fee="{ row, index }">
                    <template v-if="formData.feeList[index]">
                        <el-input-number v-model="formData.feeList[index].paramvalue" :min="row.memberminvalue"
                            :max="row.membermaxvalue" :placeholder="t('common.pleaseenter')" />
                    </template>
                </template>
            </app-table>
        </el-form>
        <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 { reactive, shallowRef, PropType, computed, onMounted } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { handleNoneValue } from '@/filters'
import { Language } from '@/constants/language'
import { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { traderPersonAdd, getInvestorTree, initInvestorPerson } from '@/services/api/investor'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppTable from '@pc/components/base/table/index.vue'
import { i18n } from '@/stores'

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

// 获取本地化属性键
const getLocalizedKey: () => keyof Investor.InvestorTreeRsp = () => {
    switch (i18n.global.locale) {
        case Language.Simplified:
            return 'name'
        case Language.Thai:
            return 'nameth'
        case Language.Traditional:
            return 'nametw'
        case Language.Vietnamese:
            return 'namevi'
        default:
            return 'nameen'
    }
}

const feetypeEnum = useEnum('feetype')
const scfRiskMode = useEnum('SCFRiskMode')
const customerTypeEnum = useEnum('customerType') // 保证金类别
const traderuleEnum = useEnum('traderule') // 交易规则
const tradefeeEnum = useEnum('tradefee') // 交易费用

const { global: { t } } = i18n
const formRef = shallowRef<FormInstance>()
const show = shallowRef(true)
const refresh = shallowRef(false)
const loading = shallowRef(false)

const formData = reactive<Investor.TraderPersonAddReq>({
    feeList: [],
    flag: 1,
    goodsid: props.record.goodsid,
    marketid: props.record.marketid,
    ruleList: [],
    paramid: props.record.paramid,
    usergroupid: props.record.usergroupid
})

// 获取分组列表
const { dataList: nodeList } = useRequest(getInvestorTree)

// 分组对象
const groupItem = computed(() => nodeList.value.find((e) => e.pid === '-1' && e.usergroupid === formData.usergroupid))

// 市场对象
const marketItem = computed(() => nodeList.value.find((e) => e.pid === groupItem.value?.id && e.marketid === formData.marketid))

// 商品对象
const goodsItem = computed(() => nodeList.value.find((e) => e.pid === marketItem.value?.id && e.goodsid === formData.goodsid))

// 获取保证金类别列表
const { data: resultData } = useRequest(initInvestorPerson, {
    params: {
        usergroupid: props.record.usergroupid,
        marketid: props.record.marketid,
        goodsid: props.record.goodsid
    }
})

const ruleColumns = computed<Model.TableColumn[]>(() => [
    { field: 'ruleid', label: 'investor.custom.tradecfg.edit.rulename', formatValue: (val) => traderuleEnum.getEnumTypeName(val) },
    { field: 'paramvalue', label: 'investor.custom.tradecfg.edit.paramvalue' },
    { field: 'dvalue', label: 'investor.custom.tradecfg.edit.dvalue', show: formData.usergroupid !== 0 },
    { field: 'cvalue', label: 'investor.custom.tradecfg.edit.cvalue' },
])

const feeColumns = computed<Model.TableColumn[]>(() => [
    { field: 'tradefeeid', label: 'investor.custom.tradecfg.edit.tradefeename', formatValue: (val) => tradefeeEnum.getEnumTypeName(val) },
    { field: 'feealgorithm', label: 'investor.custom.tradecfg.edit.feealgorithm', formatValue: (val) => scfRiskMode.getEnumTypeName(val) },
    { field: 'exchangevalue', label: 'investor.custom.tradecfg.edit.exchangevalue' },
    { field: 'dvalue', label: 'investor.custom.tradecfg.edit.dvalue', show: formData.usergroupid !== 0 },
    { field: 'memberminvalue', label: 'investor.custom.tradecfg.edit.memberminvalue' },
    { field: 'fee', label: 'investor.custom.tradecfg.edit.fee', width: 200 },
    { field: 'membermaxvalue', label: 'investor.custom.tradecfg.edit.membermaxvalue' },
])

// 选择保证金类别
const onResultChange = (value?: number) => {
    const res = resultData.value?.results.find((e) => e.enumitemname === value)
    formData.feealgorithm = res?.marginalgorithm
}

const onSubmit = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            if (formData.paramid || formData.ruleList.some((e) => e.paramid === 105 && e.paramvalue)) {
                loading.value = true
                traderPersonAdd({
                    data: formData
                }).then(() => {
                    ElMessage.success(t('common.tips3'))
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error(t('common.tips4') + err)
                }).finally(() => {
                    loading.value = false
                })
            } else {
                ElMessage.warning(t('investor.custom.tradecfg.edit.tips1'))
            }
        }
    })
}

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

onMounted(() => {
    formData.ruleList = props.record.druleList.map((e) => ({
        paramid: e.ruleid,
        paramvalue: e.cvalue
    }))

    formData.feeList = props.record.dfeeList.map((e) => ({
        feealgorithm: e.feealgorithm,
        paramid: e.tradefeeid,
        paramvalue: e.cvalue
    }))
})
</script>