<!-- 交易商管理-开户管理-交易商开户-编辑 -->
<template>
    <app-drawer :title="t('investor.user.open.edit.title')" width="900" v-model:show="show" :refresh="refresh"
        :loading="loading">
        <el-form ref="formRef" class="el-form--horizontal" label-width="140px" :model="formData" :rules="formRules"
            :show-message="false">
            <el-form-item :label="t('investor.user.open.edit.memberareaid')" prop="memberareaid"
                v-if="userStore.userInfo.releType === 1">
                <app-select-member ref="memberareaidRef" v-model="formData.memberareaid"
                    :params="{ usertype: '2', roles: '7' }" :placeholder="t('investor.user.open.edit.tips1')"
                    @change="selectMemberareaid" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.areaid')" prop="areaid">
                <app-select-member ref="areaidRef" v-model="formData.areaid" :params="{ usertype: '3', parentuserid }"
                    :placeholder="t('investor.user.open.edit.tips1')" @change="selectAreaid" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.brokerid')" prop="brokerid">
                <app-select-member ref="brokeridRef" v-model="formData.brokerid"
                    :params="{ usertype: '4', parentuseridfirst }" :placeholder="t('investor.user.open.edit.tips1')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.referral')" prop="referral">
                <app-select-investor ref="referralRef" v-model="formData.referral"
                    :placeholder="t('investor.user.open.edit.tips1')" />
            </el-form-item>
            <el-form-item class="el-form-item--row" :label="t('investor.user.open.edit.userinfotype')"
                prop="userinfotype">
                <app-enum code="userinfotype" type="radio" v-model="formData.userinfotype" :disabled="!!record?.userId" />
            </el-form-item>
            <template v-if="isPerson">
                <el-form-item :label="t('investor.user.open.edit.username')" prop="username">
                    <el-input v-model="formData.username" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.sex')" prop="sex">
                    <app-enum code="Sex" type="radio" v-model="formData.sex" />
                </el-form-item>
            </template>
            <template v-else>
                <el-form-item :label="t('investor.user.open.edit.username1')" prop="username">
                    <el-input v-model="formData.username" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.legalpersonname')" prop="legalpersonname">
                    <el-input v-model="formData.legalpersonname" maxlength="50"
                        :placeholder="t('common.pleaseenter')" />
                </el-form-item>
            </template>
            <el-form-item :label="t('investor.user.open.edit.cardtype')" prop="cardtype">
                <app-enum code="certypeperson" v-model="formData.cardtype" v-if="isPerson" />
                <app-enum code="certypecompany" v-model="formData.cardtype" v-else />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.cardnum')" prop="cardnum">
                <el-input v-model="formData.cardnum" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <template v-if="isPerson">
                <el-form-item :label="t('investor.user.open.edit.cardfrontphotourl')" prop="cardfrontphotourl">
                    <app-upload v-model="uploadFiles.cardfrontphotourl" :file-types="['image']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.cardbackphotourl')" prop="cardbackphotourl">
                    <app-upload v-model="uploadFiles.cardbackphotourl" :file-types="['image']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
            </template>
            <template v-else>
                <el-form-item :label="t('investor.user.open.edit.cardfrontphotourl1')" prop="cardfrontphotourl">
                    <app-upload v-model="uploadFiles.cardfrontphotourl" :file-types="['image']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.legalcardfrontphotourl')"
                    prop="legalcardfrontphotourl">
                    <app-upload v-model="uploadFiles.legalcardfrontphotourl" :file-types="['image']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.legalcardbackphotourl')" prop="legalcardbackphotourl">
                    <app-upload v-model="uploadFiles.legalcardbackphotourl" :file-types="['image']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
            </template>
            <el-form-item class="el-form-item--row">
                <p>{{ t('investor.user.open.edit.tips2') }}</p>
                <p>{{ t('investor.user.open.edit.tips3') }}</p>
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.otherurl')" prop="otherurl" v-if="!isPerson">
                <div>
                    <app-upload v-model="uploadFiles.otherurl" :max-size="uploadConfig.maxFileSize" />
                    <a href="/template/法人授权书模板.zip" target="_blank"
                        style="color: royalblue; text-decoration: underline;">{{ t('investor.manage.user.edit.template') }}</a>
                </div>
            </el-form-item>
            <el-form-item class="el-form-item--row" :label="t('investor.user.open.edit.region')" prop="region">
                <app-region class="el-form-item--col" v-model:country="formData.countryid"
                    v-model:province="formData.provinceid" v-model:city="formData.cityid"
                    v-model:district="formData.districtid" />
            </el-form-item>
            <el-form-item class="el-form-item--row" :label="t('investor.user.open.edit.cardaddress')"
                prop="cardaddress">
                <el-input v-model="formData.cardaddress" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <template v-if="!isPerson">
                <el-form-item :label="t('investor.user.open.edit.contactname')" prop="contactname">
                    <el-input v-model="formData.contactname" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.sex')" prop="sex">
                    <app-enum code="Sex" type="radio" v-model="formData.sex" />
                </el-form-item>
            </template>
            <el-form-item :label="t('investor.user.open.edit.mobilephone')" prop="mobilephone">
                <el-input type="number" v-model="formData.mobilephone" maxlength="50"
                    :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.telphone')" prop="telphone">
                <el-input v-model="formData.telphone" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.postalcode')" prop="postalcode">
                <el-input v-model="formData.postalcode" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.company')" prop="company" v-if="isPerson">
                <el-input v-model="formData.company" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.wechat')" prop="wechat">
                <el-input v-model="formData.wechat" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.email')" prop="email">
                <el-input v-model="formData.email" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item class="el-form-item--row" :label="t('investor.user.open.edit.remark')" prop="remark">
                <el-input type="textarea" v-model="formData.remark" maxlength="200" :rows="3"
                    :placeholder="t('common.pleaseenter')" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.close') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ t('operation.submitaduit') }}</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, onMounted, computed } from 'vue'
import { ElMessage, FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { parseFilePaths, extractFilePaths } from '@/filters'
import { uploadConfig } from '@/constants/common'
import { decryptAES } from '@/services/crypto'
import { useRequest } from '@/hooks/request'
import { dealSunOrgan, queryInvestorDetail } from '@/services/api/investor'
import {   UserInfoType, Gender } from '@/constants/member'
import { i18n, useUserStore } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppUpload from '@pc/components/base/upload/index.vue'
import AppEnum from '@pc/components/modules/enum/index.vue'
import AppRegion from '@pc/components/modules/region/index.vue'
import AppSelectMember from '@pc/components/modules/select-member/index.vue'
import AppSelectInvestor from '@pc/components/modules/select-investor/index.vue'

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

const { global: { t } } = i18n
const userStore = useUserStore()
const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)

const memberareaidRef = ref() // 所属会员组件实例
const areaidRef = ref() // 所属机构组件实例
const brokeridRef = ref() // 经纪人组件实例
const referralRef = ref() // 推荐人组件实例

const formData = ref<Partial<Member.MemberDetail>>({
    userinfotype: UserInfoType.Personal,
    sex: Gender.Male
})

const uploadFiles = reactive<{
    cardfrontphotourl: UploadUserFile[];
    cardbackphotourl: UploadUserFile[];
    legalcardfrontphotourl: UploadUserFile[];
    legalcardbackphotourl: UploadUserFile[];
    otherurl: UploadUserFile[];
}>({
    cardfrontphotourl: [],
    cardbackphotourl: [],
    legalcardfrontphotourl: [],
    legalcardbackphotourl: [],
    otherurl: []
})

const parentuserid = computed(() => formData.value.memberareaid || userStore.userInfo.areauserid)

const parentuseridfirst = computed(() => formData.value.areaid || userStore.userInfo.areauserid)

// 是否个人
const isPerson = computed(() => formData.value.userinfotype === UserInfoType.Personal)

const { loading, run } = useRequest(queryInvestorDetail, {
    manual: true,
    onSuccess: ((res) => {
        res.data.cardnum = decryptAES(res.data.cardnum)
        res.data.mobilephone = decryptAES(res.data.mobilephone)
        res.data.telphone = decryptAES(res.data.telphone)
        res.data.wechat = decryptAES(res.data.wechat)
        res.data.email = decryptAES(res.data.email)
        formData.value = res.data

        uploadFiles.cardfrontphotourl = parseFilePaths(res.data.cardfrontphotourl)
        uploadFiles.cardbackphotourl = parseFilePaths(res.data.cardbackphotourl)
        uploadFiles.legalcardfrontphotourl = parseFilePaths(res.data.legalcardfrontphotourl)
        uploadFiles.legalcardbackphotourl = parseFilePaths(res.data.legalcardbackphotourl)
        uploadFiles.otherurl = parseFilePaths(res.data.otherurl)

        memberareaidRef.value?.onReset(res.data.memberareaid)
        areaidRef.value.onReset(res.data.areaid)
        brokeridRef.value.onReset(res.data.brokerid)
        referralRef.value.onReset(res.data.referral)
    }),
    onError: (err) => {
        ElMessage.error(err)
    }
})

// 表单验证规则
const formRules: FormRules = {
    memberareaid: [{ required: true }],
    cardtype: [{ required: true }],
    username: [{ required: true }],
    cardnum: [{ required: true }],
    cardfrontphotourl: [{
        required: true,
        validator: (rule, value, callback) => {
            if (uploadFiles.cardfrontphotourl.length) {
                callback()
            } else {
                callback(new Error(isPerson.value ? t('investor.user.open.edit.tips4') : t('investor.user.open.edit.tips5')))
            }
        }
    }],
    cardbackphotourl: [{
        required: true,
        validator: (rule, value, callback) => {
            if (uploadFiles.cardbackphotourl.length) {
                callback()
            } else {
                callback(new Error(t('investor.user.open.edit.tips6')))
            }
        }
    }],
    region: [{
        required: true,
        validator: (rule, value, callback) => {
            const { provinceid, cityid, districtid } = formData.value
            if (provinceid && cityid && districtid) {
                callback()
            } else {
                callback(new Error(t('investor.user.open.edit.tips7')))
            }
        }
    }],
    cardaddress: [{ required: true }],
    mobilephone: [{ required: true }],
    legalpersonname: [{ required: true }],
    legalcardfrontphotourl: [{
        required: true,
        validator: (rule, value, callback) => {
            if (uploadFiles.legalcardfrontphotourl.length) {
                callback()
            } else {
                callback(new Error(t('investor.user.open.edit.tips8')))
            }
        }
    }],
    legalcardbackphotourl: [{
        required: true,
        validator: (rule, value, callback) => {
            if (uploadFiles.legalcardbackphotourl.length) {
                callback()
            } else {
                callback(new Error(t('investor.user.open.edit.tips9')))
            }
        }
    }],
}

// 选择所属会员
const selectMemberareaid = () => {
    areaidRef.value.onReset()
    brokeridRef.value.onReset()
}

// 选择所属机构
const selectAreaid = () => {
    brokeridRef.value.onReset()
}

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

const onSubmit = () => {
    const rawData = { ...formData.value }
    rawData.userstate = 2
    rawData.cardfrontphotourl = extractFilePaths(uploadFiles.cardfrontphotourl)
    rawData.cardbackphotourl = extractFilePaths(uploadFiles.cardbackphotourl)
    rawData.legalcardfrontphotourl = extractFilePaths(uploadFiles.legalcardfrontphotourl)
    rawData.legalcardbackphotourl = extractFilePaths(uploadFiles.legalcardbackphotourl)
    rawData.otherurl = extractFilePaths(uploadFiles.otherurl)

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

onMounted(() => {
    const userId = props.record?.userId
    if (userId) {
        run({ userId })
    }
})
</script>