<!-- 交易商管理-个性化管理-资金账户个性化-新增 -->
<template>
    <app-drawer :title="t('investor.custom.accountcfg.add.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.accountcfg.add.subtitle1') }}</legend>
                <el-form-item :label="t('investor.custom.accountcfg.add.userid')" prop="userid">
                    <select-investor v-model="formData.userid" @change="onInvestorChange" />
                </el-form-item>
                <el-form-item :label="t('investor.custom.accountcfg.add.accountid')" prop="accountid">
                    <el-select v-model="formData.accountid" @change="onAccountChange">
                        <template v-for="(value, index) in accountData?.accountids" :key="index">
                            <el-option :label="value" :value="value" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('investor.custom.accountcfg.add.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.accountcfg.add.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.goodsname" :value="item.goodsid" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item :label="t('investor.custom.accountcfg.add.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="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 #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" :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">
                        <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 { ref, reactive, computed } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { handleNoneValue } from '@/filters'
import { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { loadSelectOption, tradeConfigAdd } from '@/services/api/member'
import { i18n } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppTable from '@pc/components/base/table/index.vue'
import SelectInvestor from './select-investor/index.vue'

const feetypeEnum = useEnum('feetype')
const scfRiskMode = useEnum('SCFRiskMode')
const traderule = useEnum('traderule')
const tradefee = 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<Member.TradeConfigAddReq>({
    memberuserid: 1,
    feeList: [],
    ruleList: [],
    tradetype: 1
})

// 获取资金账户列表
const { data: accountData, run: getAccountIds } = useRequest(loadSelectOption, {
    manual: true,
    params: {
        memberuserid: 1
    }
})

// 获取市场列表
const { data: marketData, run: getMarketList } = useRequest(loadSelectOption, {
    manual: true,
    params: {
        memberuserid: 1
    }
})

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

// 获取保证金类别列表
const { data: resultData, run: getResultList } = useRequest(loadSelectOption, {
    manual: true,
    params: {
        memberuserid: 1
    },
    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.accountcfg.add.rulename', formatValue: (val) => traderule.getEnumTypeName(val) },
    { field: 'paramvalue', label: 'investor.custom.accountcfg.add.paramvalue' },
    { field: 'dvalue', label: 'investor.custom.accountcfg.add.dvalue' },
    { field: 'gvalue', label: 'investor.custom.accountcfg.add.gvalue' },
    { field: 'cvalue', label: 'investor.custom.accountcfg.add.cvalue' },
])

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

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

// 选择交易商
const onInvestorChange = (item?: Investor.InitAccTradeRsp) => {
    formData.accountid = undefined
    formData.marketid = undefined
    formData.goodsid = undefined
    formData.paramid = undefined
    formData.feealgorithm = undefined
    accountData.value = undefined
    marketData.value = undefined
    goodsData.value = undefined
    resultData.value = undefined
    if (item) {
        getAccountIds({
            userid: item.userid,
        })
    }
}

// 选择资金账户
const onAccountChange = (value: number) => {
    formData.marketid = undefined
    formData.goodsid = undefined
    formData.paramid = undefined
    formData.feealgorithm = undefined
    marketData.value = undefined
    goodsData.value = undefined
    resultData.value = undefined
    getMarketList({
        userid: formData.userid,
        accountid: value,
    })
}

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

// 选择商品
const onGoodsChange = (value: number) => {
    formData.paramid = undefined
    formData.feealgorithm = undefined
    getResultList({
        userid: formData.userid,
        accountid: formData.accountid,
        marketid: formData.marketid,
        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
                tradeConfigAdd({
                    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.add.tips1'))
            }
        }
    })
}

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