<!-- 会员机构管理-机构管理-做市会员管理-新增/修改 -->
<template>
    <app-drawer :title="t('member.institution.marketer.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.marketer.edit.userid1') }}</legend>
                <el-form-item :label="t('member.institution.marketer.edit.userid')" prop="userid">
                    <app-select-member v-model="formData.userid" :placeholder="t('investor.custom.riskcfg.edit.tips1')" :params="{ exists: '8' }" 
                      :disabled="!!record" @change="onMemberChange"/>
                </el-form-item>
                <el-form-item :label="t('member.institution.marketer.edit.userid1')" prop="userid" v-if="!record" >
                    <el-button @click="openComponent('Roles')">{{ t('member.institution.marketer.edit.look') }}</el-button>
                    <span>{{ manger }}</span>
                </el-form-item>
                <el-form-item :label="t('member.institution.marketer.edit.customertype')" prop="marketerType">
                    <app-enum code="marketerType" v-model="formData.customertype" />
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('member.institution.marketer.edit.title1') }}</legend>
                <el-form-item :label="t('member.institution.marketer.edit.currency')" prop="currency">{{ currency }}</el-form-item>
                <el-form-item :label="t('member.institution.marketer.edit.accountid')" prop="accountid">
                    <el-select v-model="formData.accountid" :placeholder="t('common.pleasechoice')" @change="onTaAccount">
                        <el-option v-for="item in talist" :key="item.accountid" :label="item.accountid"
                        :value="item.accountid" />
                    </el-select>
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('member.institution.marketer.edit.title2') }}</legend>
                <app-table-details :title="t('member.institution.marketer.edit.title2')" :data="marker" :label-width="160" :cell-props="detailProps3" :column="2" v-if="marker" />
            </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: 8 }" :is="componentMap.get(componentId)" @closed="closeComponent" v-if="componentId" />
    </app-drawer>
</template>

<script lang="ts" setup>
import { shallowRef, PropType, ref, defineAsyncComponent, onMounted, computed } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useComponent } from '@/hooks/component'
import { i18n } from '@/stores'
import { roleadd, initAdd, getOragnDefaultManager, queryRoleDetail } from '@/services/api/member'
import { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { getRiskRatioTypeForMarketer } from '@/services/api/investor'
import { CellProp } from '@pc/components/base/table-details/types'
import { queryAccountIdForMarket } from '@/services/api/common'
import AppSelectMember from '@pc/components/modules/select-member/index.vue'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppTableDetails from '@pc/components/base/table-details/index.vue'
import AppEnum from '@pc/components/modules/enum/index.vue'

// 币种
const currencyEnum = useEnum('currency')
const flagEnum = useEnum('flag') // 确认状态
const marketerTypeEnum = useEnum('marketerType') // 风险率类型

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

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 currency = ref('')

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

const { loading } = useRequest(initAdd, {
    params: {
        role: 'marketer'
    },
    onSuccess: (res) => {
        formData.value.enumdicnames = res.data.enumDicItems.map(e => e.enumitemname)
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const { run: runRoleDetail } = useRequest(queryRoleDetail, {
    manual: true,
    params: {
        rolename: 'marketer',
        userid: props.record?.userid
    },
    onError: (err) => {
        ElMessage.error(err)
    },
    onSuccess: (res) => {
        formData.value.customertype = res.data.customertype.customertype
        // 获取资金账号信息
        runAccountIdForMarket({
            userid: props.record?.userid
        })
    }
})


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

const { dataList: talist, run: runAccountIdForMarket } = useRequest(queryAccountIdForMarket, {
    manual: true,
    params: {
        userid: formData?.value.userid
    },
    onSuccess: (res) => {
        if (res.data) {
            formData.value.accountid = res.data.accountid
            currency.value = currencyEnum.getEnumTypeName(res.data.currencyid) ?? ''
        }
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

const { data: marker, run } = useRequest(getRiskRatioTypeForMarketer, {
    params: {
        riskcontrolmode: 2,
        customertype: formData.value.customertype ?? 1
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

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

const onSubmit = () => {
    const { accountid } = formData.value
    if (accountid) {
        formData.value.accountids = [accountid]
    }
    const rawData = { ...formData.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 detailProps3 = computed<CellProp[]>(() => {
    const { notesaferatio } = marker.value ?? {}
    return [
        { prop: 'riskcontrolmode', label: 'member.institution.marketer.details.riskcontrolmode', formatValue: (val) => val === 1 ? t('member.institution.marketer.details.riskcontrolmode1') : t('member.institution.marketer.details.riskcontrolmode2') },
        { prop: 'customertype', label: 'member.institution.marketer.details.customertype1', formatValue: (val) => marketerTypeEnum.getEnumTypeName(val) },
        { prop: 'riskratiocalcmode', label: 'member.institution.marketer.details.riskratiocalcmode', formatValue: (val) => val === 1 ? t('member.institution.marketer.details.riskratiocalcmode1') : t('member.institution.marketer.details.riskratiocalcmode2') },
        { prop: 'notemarginriskratio', label: 'member.institution.marketer.details.notemarginriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'addmarginriskratio', label: 'member.institution.marketer.details.addmarginriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'cutriskratio', label: 'member.institution.marketer.details.cutriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'cutbackriskratio', label: 'member.institution.marketer.details.cutbackriskratio', formatValue: (val) => val + '%', show: !notesaferatio },
        { prop: 'notesaferatio', label: 'member.institution.marketer.details.notesaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'addsaferatio', label: 'member.institution.marketer.details.addsaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'recoversaferatio', label: 'member.institution.marketer.details.recoversaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'cutsaferatio', label: 'member.institution.marketer.details.cutsaferatio', formatValue: (val) => val + '%', show: !!notesaferatio },
        { prop: 'isdefault', label: 'member.institution.marketer.details.isdefault', formatValue: (val) => flagEnum.getEnumTypeName(val) },
        { prop: 'markets', label: 'member.institution.marketer.details.markets' },
    ]
})

const onTaAccount = (accountid: number) => {
    currency.value = currencyEnum.getEnumTypeName(talist.value.find(e => e.accountid === accountid)?.currencyid) ?? ''
}

const onMemberChange = (item?: Model.OrganSelectRsp) => {
    organSelect.value = item
    
    const { userid } = formData.value
    if (userid) {
        runDefaultManager({
            userid: userid.toString()
        })
        // 获取资金账号信息
        runAccountIdForMarket({
            userid: userid
        })
    }
}

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

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