<!-- 交易商管理-个性化管理-交易商个性化-新增 -->
<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" :rules="formRules" :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')" prop="usergroupid">
                    <el-select v-model="formData.usergroupid" @change="onGroupChange">
                        <template v-for="(item, index) in groupTrees" :key="index">
                            <el-option :label="item.name" :value="item.usergroupid" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('investor.custom.tradecfg.edit.marketid')" prop="marketid">
                    <el-select v-model="formData.marketid" @change="onMarketChange">
                        <template v-for="(item, index) in marketData?.markets" :key="index">
                            <el-option :label="item.marketname" :value="item.marketid" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('investor.custom.tradecfg.edit.goodsid')" prop="goodsid">
                    <el-select v-model="formData.goodsid" @change="onGoodsChange">
                        <template v-for="(item, index) in goodsData?.goods" :key="index">
                            <el-option :label="item[getLocalizedKey()] || item.goodscode || item.goodsid"
                                :value="item.goodsid" />
                        </template>
                    </el-select>
                </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="resultData?.rulesConfigVos" :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" :min="0"
                            :placeholder="t('common.pleaseenter')" v-else />
                    </template>
                </template>
            </app-table>
            <app-table :data="resultData?.feesConfigVos" :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 { ref, reactive, computed } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { handleNoneValue } from '@/filters'
import { Language } from '@/constants/language'
import { getFeeAlgorithmName } from '@/constants/order'
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 getLocalizedKey: () => keyof Investor.InvestorPersonRsp['goods'][number] = () => {
    switch (i18n.global.locale) {
        case Language.Simplified:
            return 'goodsname'
        case Language.Thai:
            return 'goodsnameth'
        case Language.Traditional:
            return 'goodsnametw'
        case Language.Vietnamese:
            return 'goodsnamevi'
        default:
            return 'goodsnameen'
    }
}

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

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

const formData = reactive<Investor.TraderPersonAddReq>({
    feeList: [],
    flag: 0,
    ruleList: []
})

// 分组树列表
const groupTrees = computed(() => {
    return nodeList.value.filter((e) => e.pid === '-1')
})

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

// 获取市场列表
const { data: marketData, run: getMarketList } = useRequest(initInvestorPerson)

// 获取商品列表
const { data: goodsData, run: getGoodsList } = useRequest(initInvestorPerson, {
    manual: true,
})

// 获取保证金类别列表
const { data: resultData, run: getResultList } = useRequest(initInvestorPerson, {
    manual: true,
    onSuccess: (res) => {
        formData.ruleList = []
        formData.feeList = []

        res.data.rulesConfigVos.forEach((e) => {
            formData.ruleList.push({
                paramid: e.ruleid
            })
        })

        res.data.feesConfigVos.forEach((e) => {
            formData.feeList.push({
                feealgorithm: e.feealgorithm,
                paramid: e.tradefeeid
            })
        })
    }
})

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) => getFeeAlgorithmName(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 formRules: FormRules = {
    usergroupid: [{ required: true }],
    marketid: [{ required: true }],
    goodsid: [{ required: true }],
}

// 选择分组
const onGroupChange = (value: number) => {
    formData.marketid = undefined
    formData.goodsid = undefined
    formData.paramid = undefined
    formData.feealgorithm = undefined
    goodsData.value = undefined
    resultData.value = undefined
    getMarketList({
        usergroupid: value,
    })
}

// 选择市场
const onMarketChange = (value: number) => {
    formData.goodsid = undefined
    formData.paramid = undefined
    formData.feealgorithm = undefined
    goodsData.value = undefined
    resultData.value = undefined
    getGoodsList({
        usergroupid: formData.usergroupid,
        marketid: value,
    })
}

// 选择商品
const onGoodsChange = (value: number) => {
    formData.paramid = undefined
    formData.feealgorithm = undefined
    getResultList({
        marketid: formData.marketid,
        usergroupid: formData.usergroupid,
        goodsid: value
    })
}

// 选择保证金类别
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.add.tips1'))
            }
        }
    })
}

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