<!-- 会员机构管理-机构管理-账户个性化设置-新增 -->
<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('member.institution.tradecfg.add.subtitle')" @change="onTradeTypeChange">
                    <el-radio-group v-model="formData.tradetype">
                        <el-radio :label="t('member.institution.tradecfg.add.userid1')" :value="1" />
                        <el-radio :label="t('member.institution.tradecfg.add.userid2')" :value="2" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="t('member.institution.tradecfg.add.userid1')" prop="userid" v-if="formData.tradetype === 1">
                    <app-select-member v-model="formData.userid" :params="{ usertype: '2', roles: '6' }"
                        @change="onMemberChange" />
                </el-form-item>
                <el-form-item :label="t('member.institution.tradecfg.add.userid2')" prop="userid" v-if="formData.tradetype === 2">
                    <app-select-member v-model="formData.userid" :params="{ usertype: '2', roles: '8' }"
                        @change="onMemberChange" />
                </el-form-item>
                <el-form-item :label="t('member.institution.tradecfg.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('member.institution.tradecfg.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('member.institution.tradecfg.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('member.institution.tradecfg.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="customerType.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 #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 #fee="{ index }">
                    <template v-if="formData.feeList[index]">
                        <el-input-number v-model="formData.feeList[index].paramvalue" :min="0"
                            :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 AppSelectMember from '@pc/components/modules/select-member/index.vue'

const customerType = useEnum('customerType')
const scfRiskMode = useEnum('SCFRiskMode')
const feetypeEnum = useEnum('feetype')
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: 0,
    feeList: [],
    ruleList: [],
    tradetype: 1
})

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

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

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

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

const feeColumns = computed<Model.TableColumn[]>(() => [
    { field: 'tradefeeid', label: 'member.institution.tradecfg.add.tradefeename', formatValue: (val) => tradefee.getEnumTypeName(val) },
    { field: 'exchangevalue', label: 'member.institution.tradecfg.add.exchangevalue' },
    { field: 'feealgorithm', label: 'member.institution.tradecfg.add.feealgorithm', formatValue: (val) => scfRiskMode.getEnumTypeName(val) },
    { field: 'fee', label: 'member.institution.tradecfg.add.fee', width: 200 },
])

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

// 选择个性化
const onTradeTypeChange = () => {
    formData.userid = undefined
    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
}

// 选择会员
const onMemberChange = (item?: Model.OrganSelectRsp) => {
    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({
            tradetype: formData.tradetype,
            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({
        tradetype: formData.tradetype,
        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({
        tradetype: formData.tradetype,
        userid: formData.userid,
        accountid: formData.accountid,
        marketid: value,
    })
}

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

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