<!-- 交易商管理-个性化管理-交易商个性化 -->
<template>
    <div class="g-view-tree">
        <app-view>
            <el-tree ref="treeRef" :data="nodeList" node-key="id" :props="{ label: getLocalizedKey() }"
                :default-expanded-keys="['-1']" @node-click="nodeClick" highlight-current />
        </app-view>
        <app-view>
            <div style="display: flex;justify-content: space-between;">
                <app-operation :data-list="getActionButtons(['investor_custom_tradecfg_add'])" @click="openComponent" />
                <app-operation
                    :data-list="getActionButtons(['investor_custom_tradecfg_modify', 'investor_custom_tradecfg_delete'])"
                    @click="openComponent" v-if="data" />
            </div>
            <template v-if="data">
                <app-table-details :title="t('common.baseinfo')" :data="currentInfo" :label-width="160"
                    :cell-props="detailProps" :column="3" />
                <app-table :data="data.druleList" :columns="ruleColumns">
                    <template #headerLeft>
                        <b>{{ t('investor.custom.tradecfg.subtitle') }}</b>
                    </template>
                    <!-- 商品设置值 -->
                    <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 }">
                        <span v-if="row.ruleid === 105">
                            {{ handleNoneValue(feetypeEnum.getEnumTypeName(row.cvalue)) }}
                        </span>
                        <span v-else>{{ handleNoneValue(row.cvalue) }}</span>
                    </template>
                </app-table>
                <app-table :data="data.dfeeList" :columns="feeColumns">
                    <template #headerLeft>
                        <b>{{ t('investor.custom.tradecfg.subtitle1') }}</b>
                    </template>
                    <!-- 商品设置值 -->
                    <template #exchangevalue="{ row }">
                        <template v-if="row.feealgorithm">
                            <span>{{ scfRiskMode.getEnumTypeName(row.feealgorithm) }}：</span>
                            <span>{{ row.exchangevalue + (row.feealgorithm === 1 && '‱') }}</span>
                        </template>
                        <template v-else>
                            {{ handleNoneValue() }}
                        </template>
                    </template>
                    <!-- 会员设置值 -->
                    <template #dvalue="{ row }">
                        <template v-if="row.drithm">
                            <span>{{ scfRiskMode.getEnumTypeName(row.drithm) }}：</span>
                            <span>{{ row.dvalue + (row.drithm === 1 && '‱') }}</span>
                        </template>
                        <template v-else>
                            {{ handleNoneValue() }}
                        </template>
                    </template>
                    <!-- 个性化 -->
                    <template #cvalue="{ row }">
                        <template v-if="row.crithm">
                            <span>{{ scfRiskMode.getEnumTypeName(row.crithm) }}：</span>
                            <span>{{ row.cvalue + (row.crithm === 1 && '‱') }}</span>
                        </template>
                        <template v-else>
                            {{ handleNoneValue() }}
                        </template>
                    </template>
                </app-table>
            </template>
            <el-empty v-else />
        </app-view>
        <component :is="componentMap.get(componentId)" v-bind="{ record: toRaw(data) }" @closed="closeComponent"
            v-if="componentId" />
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, toRaw, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { buildTree, handleNoneValue } from '@/filters'
import { Language } from '@/constants/language'
import { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { useOperation } from '@/hooks/operation'
import { getInvestorTree, tradeConfigView } from '@/services/api/investor'
import { CellProp } from '@pc/components/base/table-details/types'
import AppTable from '@pc/components/base/table/index.vue'
import AppOperation from '@pc/components/base/operation/index.vue'
import AppTableDetails from '@pc/components/base/table-details/index.vue'
import { i18n } from '@/stores'

// 获取本地化属性键
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 { global: { t } } = i18n
const customerTypeEnum = useEnum('customerType')
const feetypeEnum = useEnum('feetype')
const scfRiskMode = useEnum('SCFRiskMode')
const traderuleEnum = useEnum('traderule') // 交易规则
const tradefeeEnum = useEnum('tradefee') // 交易费用

const treeRef = ref()
const nodeList = ref<(Investor.InvestorTreeRsp & { children: Investor.InvestorTreeRsp[]; })[]>([])
const selectedNode = ref<Node>()

const currentInfo = reactive({
    groupName: '',
    marketName: '',
    goodsName: '',
    customerType: '',
    marginValue: ''
})

const qs = computed<Investor.TradeConfigViewReq>(() => {
    const data = selectedNode.value?.data
    return {
        usergroupid: data?.usergroupid,
        marketid: data?.marketid,
        goodsid: data?.goodsid,
    }
})

const { componentMap, componentId, openComponent, closeComponent, getActionButtons } = useOperation<Investor.TradeConfigViewRsp>({
    onClose: (componentId) => {
        getNodeList()
        if (componentId === 'investor_custom_tradecfg_modify') {
            getDetails(qs.value)
        }
        if (componentId === 'investor_custom_tradecfg_delete') {
            data.value = undefined
        }
    }
})

const { run: getNodeList } = useRequest(getInvestorTree, {
    onSuccess: (res) => {
        res.data.push(
            {
                goodsid: 0,
                id: '-1',
                level: 0,
                marketid: 0,
                name: t('investor.custom.tradecfg.subtitle2'),
                nameen: t('investor.custom.tradecfg.subtitle2'),
                nameth: t('investor.custom.tradecfg.subtitle2'),
                nametw: t('investor.custom.tradecfg.subtitle2'),
                namevi: t('investor.custom.tradecfg.subtitle2'),
                pid: '0',
                usergroupid: 0
            }
        )
        nodeList.value = buildTree(res.data, 'id', 'pid', (node) => node.pid === '0')

        // 设置选中节点
        nextTick(() => {
            const data = selectedNode.value?.data
            if (data) {
                treeRef.value.setCurrentKey(data.id)
            }
        })
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const { data, run: getDetails } = useRequest(tradeConfigView, {
    manual: true,
    onError: (err) => {
        ElMessage.error(err)
    }
})

const detailProps = computed<CellProp[]>(() => [
    { prop: 'groupName', label: 'investor.custom.tradecfg.usergroupid1' },
    { prop: 'marketName', label: 'investor.custom.tradecfg.marketid1' },
    { prop: 'goodsName', label: 'investor.custom.tradecfg.goodsid1' },
    { prop: 'customerType', label: 'investor.custom.tradecfg.paramid', formatValue: () => customerTypeEnum.getEnumTypeName(data.value?.paramid) },
    { prop: 'marginValue', label: 'investor.custom.tradecfg.marketmarginvaluedisplay', formatValue: () => data.value?.marketmarginvaluedisplay },
])

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

const feeColumns = computed<Model.TableColumn[]>(() => [
    { field: 'tradefeeid', label: 'investor.custom.tradecfg.edit.tradefeename', formatValue: (val) => tradefeeEnum.getEnumTypeName(val) },
    { field: 'exchangevalue', label: 'investor.custom.tradecfg.exchangevalue' },
    { field: 'dvalue', label: 'investor.custom.tradecfg.dvalue', show: qs.value.usergroupid !== 0 },
    { field: 'cvalue', label: 'investor.custom.tradecfg.cvalue' },
])

const nodeClick = (data: Investor.InvestorTreeRsp, node: Node) => {
    if (data.goodsid) {
        selectedNode.value = node
        currentInfo.goodsName = node.label
        currentInfo.marketName = node.parent.label
        currentInfo.groupName = node.parent.parent.label
        getDetails(qs.value)
    }
}
</script>