<!-- 交易商管理-开户管理-交易商开户-编辑 -->
<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">
                <el-input v-model="formData.memberareaid" maxlength="50" :placeholder="t('common.pleaseenter')" />
            </el-form-item> -->
            <el-form-item :label="t('investor.user.open.edit.areaid')" prop="areaid">
                <app-select-member v-model="formData.areaid" usertype="3" :placeholder="t('investor.user.open.edit.tips1')" />
            </el-form-item>
            <el-form-item :label="t('investor.user.open.edit.brokerid')" prop="brokerid">
                <app-select-member v-model="formData.brokerid" usertype="4" :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 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">
                <el-radio-group v-model="formData.userinfotype">
                    <template v-for="item in getUserInfoTypeList()" :key="item.value">
                        <el-radio :label="item.label" :value="item.value" />
                    </template>
                </el-radio-group>
            </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">
                    <el-radio-group v-model="formData.sex">
                        <template v-for="item in getGenderList()" :key="item.value">
                            <el-radio :label="item.label" :value="item.value" />
                        </template>
                    </el-radio-group>
                </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')" />
                </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')" />
                </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')" />
                </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')" />
                </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')" />
                </el-form-item>
                <el-form-item :label="t('investor.user.open.edit.otherurl')" prop="otherurl">
                    <app-upload v-model="uploadFiles.otherurl" :file-types="['image']" :type-message="t('common.tips21')" />
                </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 class="el-form-item--row" :label="t('investor.user.open.edit.region')" prop="region">
                <app-region class="el-form-item--col" 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">
                    <el-radio-group v-model="formData.sex">
                        <template v-for="item in getGenderList()" :key="item.value">
                            <el-radio :label="item.label" :value="item.value" />
                        </template>
                    </el-radio-group>
                </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 type="number" 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="2" :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 { useRequest } from '@/hooks/request'
import { dealSunOrgan, queryInvestorDetail } from '@/services/api/investor'
import { getUserInfoTypeList, getGenderList, UserInfoType, Gender } from '@/constants/member'
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'
import service from '@/services'
import { decryptAES } from '@/services/crypto'
import { i18n } from '@/stores'

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

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

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


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

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

const getUploadFiles = (value?: string) => {
    const paths = value ? value.split(',') : []
    return paths.map((url) => {
        const urlObj = new URL(url, service.getConfig('apiUrl'))
        const name = urlObj.pathname.split('/').pop()
        return {
            name: name ?? urlObj.href,
            url: urlObj.href,
            response: {
                data: [{ filePath: value }]
            }
        }
    })
}

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 = getUploadFiles(res.data.cardfrontphotourl)
        uploadFiles.cardbackphotourl = getUploadFiles(res.data.cardbackphotourl)
        uploadFiles.legalcardfrontphotourl = getUploadFiles(res.data.legalcardfrontphotourl)
        uploadFiles.legalcardbackphotourl = getUploadFiles(res.data.legalcardbackphotourl)
        uploadFiles.otherurl = getUploadFiles(res.data.otherurl)
    }),
    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 onCancel = (isRefresh = false) => {
    show.value = false
    refresh.value = isRefresh
}

// 更新上传文件到表单中
const updateUploadFiles = (uploadFiles: UploadUserFile[]) => {
    return uploadFiles.map((e) => {
        const res = e.response as { data: { filePath: string }[] }
        return res.data.map((e) => e.filePath)
    }).join(',')
}

const onSubmit = () => {
    const rawData = { ...formData.value }
    rawData.userstate = 2
    rawData.cardfrontphotourl = updateUploadFiles(uploadFiles.cardfrontphotourl)
    rawData.cardbackphotourl = updateUploadFiles(uploadFiles.cardbackphotourl)
    rawData.legalcardfrontphotourl = updateUploadFiles(uploadFiles.legalcardfrontphotourl)
    rawData.legalcardbackphotourl = updateUploadFiles(uploadFiles.legalcardbackphotourl)
    rawData.otherurl = updateUploadFiles(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>