<!-- 会员机构管理-机构管理-经纪会员管理-新增/修改 -->
<template>
    <app-drawer :title="t('member.institution.broker.edit.title') " width="900" v-model:show="show" :loading="loading" :refresh="refresh">
        <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('member.institution.broker.edit.userid') }}</legend>
                <el-form-item :label="t('member.institution.broker.edit.userid') " prop="userid">
                    <app-select-member v-model="formData.userid" :placeholder="t('investor.custom.riskcfg.edit.tips1')" :params="{ exists: '7' }"
                      :disabled="!!record" @change="onMemberChange"/>
                </el-form-item>
                <el-form-item :label="t('member.institution.broker.edit.title1')" prop="userid" v-if="!record" >
                    <el-button @click="openComponent('Roles')">{{ t('member.institution.broker.edit.look') }}</el-button>
                    <span>{{ manger }}</span>
                </el-form-item>
                <el-form-item :label="t('member.institution.broker.edit.parentuserid')" prop="parentuserid">
                    <app-select-member2 v-model="formData.parentuserid"  :placeholder="t('investor.custom.riskcfg.edit.tips1')" :params="{ roles: '3' }"/>
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('member.institution.broker.edit.userid2') }}</legend>
                <el-table ref="tableRef" :data="formData.dtype" style="width: 100%;" @selection-change="handleSelectionChange" border>
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="marketName" :label="t('member.institution.broker.edit.marketName')" />
                    <el-table-column prop="tradeMode" :label="t('member.institution.broker.edit.tradeMode')" 
                       v-if="multipleSelection.some((e) => e.tradeProperty === 4 || e.tradeMode === 79)">
                       <template #default="{ row }">
                            <span v-if="row.tradeMode === 79">{{ t('member.institution.broker.edit.tradeMode79') }}</span>
                            <template v-else-if="row.tradeMode === 17 && row.tradeProperty === 4">
                                <el-select v-model="row.dtype">
                                    <template v-for="item in marketbstype" :key="item.value">
                                        <el-option :label="item.label" :value="item.value" />
                                    </template>
                                </el-select>
                            </template>
                            <template v-else>
                                {{ handleNoneValue() }}
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tradeMode" :label="t('member.institution.broker.edit.tradeMode1')" 
                       v-if="multipleSelection.some((e) => e.tradeProperty === 4 || [77, 78].includes(e.tradeMode))" >
                       <template #default="{ row }">
                            <span v-if="[77, 78].includes(row.tradeMode)">{{ t('member.institution.broker.edit.tradeMode78') }}</span>
                            <template v-else-if="row.tradeProperty === 4">
                                <el-select v-model="row.spotRightType">
                                    <template v-for="item in marketbstype" :key="item.value">
                                        <el-option :label="item.label" :value="item.value" />
                                    </template>
                                </el-select>
                            </template>
                            <template v-else>
                                {{ handleNoneValue() }}
                            </template>
                        </template>
                    </el-table-column>
                </el-table>
            </fieldset> 
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ t('operation.save') }}</el-button>
        </template>
        <component ref="componentRef" v-bind="{ record, roleid: 7 }" :is="componentMap.get(componentId)" @closed="closeComponent" v-if="componentId" />
    </app-drawer>
</template>

<script lang="ts" setup>
import { shallowRef, PropType, ref, defineAsyncComponent, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useComponent } from '@/hooks/component'
import { i18n } from '@/stores'
import { handleNoneValue } from '@/filters'
import { roleadd, initAdd, getOragnDefaultManager } from '@/services/api/member'
import { useRequest } from '@/hooks/request'
import AppSelectMember from '@pc/components/modules/select-member/index.vue'
import AppSelectMember2 from '@pc/components/modules/select-member2/index.vue'
import AppDrawer from '@pc/components/base/drawer/index.vue'

const props = defineProps({
    record: {
        type: Object as PropType<Member.OrganRoleRsp>
    }
})

const formData = ref<Partial<Member.RoleAddReq>>({
    roleid: 7,
    type: props.record ? 2 : 1
})

const componentMap = new Map<string, unknown>([
    ['Roles', defineAsyncComponent(() => import('@pc/components/modules/roles/index.vue'))], // 角色权限信息
])
const { componentRef, componentId, openComponent, closeComponent } = useComponent()

const { global: { t } } = i18n
const formRef = ref<FormInstance>()
const show = shallowRef(true)
const refresh = shallowRef(false)
const organSelect = ref<Model.OrganSelectRsp>()
const multipleSelection = ref<Model.UpdateTaAccountReq['dtype']>([]) // 已选中的市场数据
const marketbstype = [{value: 0, label: "无"}, {value:1, label: "可挂可摘"}, {value:2, label: "可挂"}, {value:3, label: "可摘"}]

const { loading } = useRequest(initAdd, {
    params: {
        role: 'broker'
    },
    onSuccess: (res) => {
        // 赋值数据
        formData.value.dtype = res.data.markets.map(e => ({
            checked: 0,
            dtype: 0,
            fdType: 0,
            fspotRightType: 0,
            marketId: e.marketid,
            marketName: e.marketname,
            spotRightType: 0, 
            tradeMode: e.trademode,
            tradeProperty: e.tradeproperty,
        })) ?? []
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const { data: manger, run: runDefaultManager } = useRequest(getOragnDefaultManager, {
    manual: true,
    params: {
        userid: formData?.value.userid?.toString()
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

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

const handleSelectionChange = (selection: Model.UpdateTaAccountReq['dtype']) => {
    multipleSelection.value = selection
}

const onSubmit = () => {
    const rawData = { ...formData.value }
    rawData.dtype = multipleSelection.value
    formRef.value?.validate((valid) => {
        if (valid) {
            loading.value = true
            roleadd({
                data: rawData
            }).then(() => {
                ElMessage.success(t('common.tips3'))
                onCancel(true)
            }).catch((err) => {
                ElMessage.error(t('common.tips4') + err)
            }).finally(() => {
                loading.value = false
            })
        }
    })
}

const onMemberChange = (item?: Model.OrganSelectRsp) => {
    organSelect.value = item

    const { userid } = formData.value
    if (userid) {
        runDefaultManager({
            userid: userid.toString()
        })
    }
}

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

onMounted(() => {
    const { userid, } = props.record ?? {}
    if (userid) {
        formData.value.userid = userid
    }
})
</script>