<!-- 交易商管理-个性化管理-资金账户个性化-编辑 -->
<template>
    <app-drawer :title="t('investor.custom.accountcfg.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.accountcfg.edit.subtitle1') }}</legend>
                <el-form-item :label="t('investor.custom.accountcfg.edit.userid')" >
                    {{ handleNoneValue(investorItem?.name) }}
                </el-form-item>
                <el-form-item :label="t('investor.custom.accountcfg.edit.accountid')" >
                    {{ handleNoneValue(accountItem?.name) }}
                </el-form-item>
                <el-form-item :label="t('investor.custom.accountcfg.edit.goodsid')" >
                    {{ handleNoneValue(goodsItem?.name) }}
                </el-form-item>
                <el-form-item :label="t('investor.custom.accountcfg.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="item.enumdicname" :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 #gvalue="{ row }">
                    <span v-if="row.ruleid === 105">
                        {{ handleNoneValue(feetypeEnum.getEnumTypeName(row.gvalue)) }}
                    </span>
                    <span v-else>{{ handleNoneValue(row.gvalue) }}</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">
                        <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 #gvalue="{ row }">
                    <template v-if="row.grithm">
                        <span>{{ scfRiskMode.getEnumTypeName(row.grithm) }}：</span>
                        <span>{{ row.gvalue + (row.grithm === 1 && '‱') }}</span>
                    </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 { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { getAccTradeTree } from '@/services/api/investor'
import { tradeConfigEdit } from '@/services/api/member'
import { loadSelectOption } from '@/services/api/member'
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.AccTradeConfigViewRsp>,
        required: true
    }
})

const feetypeEnum = useEnum('feetype')
const scfRiskMode = useEnum('SCFRiskMode')
const traderule = useEnum('traderule')
const tradefee = 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<Member.TradeConfigAddReq>({
    memberuserid: props.record.memberuserid,
    accountid: props.record.accountid,
    feeList: [],
    goodsid: props.record.goodsid,
    marketid: props.record.marketid,
    ruleList: [],
    paramid: props.record.paramid,
    tradetype: props.record.tradetype,
    userid: props.record.userid,
    feealgorithm: props.record.feealgorithm,
})

// 获取树列表
const { dataList: nodeList } = useRequest(getAccTradeTree)

// 交易商对象
const investorItem = computed(() => nodeList.value.find((e) => e.pid === '-1' && e.userid === formData.userid))

// 资金账户对象
const accountItem = computed(() => nodeList.value.find((e) => e.pid === investorItem.value?.id && e.accountid === formData.accountid))

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

// 获取保证金类别列表
const { data: resultData } = useRequest(loadSelectOption, {
    params: {
        memberuserid: formData.marketid,
        userid: formData.userid,
        accountid: formData.accountid,
        marketid: formData.marketid,
        goodsid: formData.goodsid
    }
})

const ruleColumns = computed<Model.TableColumn[]>(() => [
    { field: 'ruleid', label: 'investor.custom.accountcfg.edit.rulename', formatValue: (val) => traderule.getEnumTypeName(val) },
    { field: 'paramvalue', label: 'investor.custom.accountcfg.edit.paramvalue' },
    { field: 'dvalue', label: 'investor.custom.accountcfg.edit.dvalue' },
    { field: 'gvalue', label: 'investor.custom.accountcfg.edit.gvalue' },
    { field: 'cvalue', label: 'investor.custom.accountcfg.edit.cvalue' },
])

const feeColumns = computed<Model.TableColumn[]>(() => [
    { field: 'tradefeeid', label: 'investor.custom.accountcfg.edit.tradefeename', formatValue: (val) => tradefee.getEnumTypeName(val) },
    { field: 'exchangevalue', label: 'investor.custom.accountcfg.edit.exchangevalue' },
    { field: 'dvalue', label: 'investor.custom.accountcfg.edit.dvalue' },
    { field: 'gvalue', label: 'investor.custom.accountcfg.edit.gvalue' },
    { field: 'feealgorithm', label: 'investor.custom.accountcfg.edit.feealgorithm', formatValue: (val) => scfRiskMode.getEnumTypeName(val) },
    { field: 'memberminvalue', label: 'investor.custom.accountcfg.edit.memberminvalue' },
    { field: 'fee', label: 'investor.custom.accountcfg.edit.fee', width: 200 },
    { field: 'membermaxvalue', label: 'investor.custom.accountcfg.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
                tradeConfigEdit({
                    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.accountcfg.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>