<!-- 会员机构管理-机构管理-机构资料管理-编辑 -->
<template>
    <app-drawer :title="t('member.institution.open.edit.title')" width="900" 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">基本信息</legend>
                <el-form-item label="机构代码">
                    {{ handleNoneValue(data?.rspResult.userid) }}
                </el-form-item>
                <el-form-item label="所有者类型" prop="userinfotype">
                    {{ data ? getUserInfoTypeName(data.userinfo.userinfotype) : handleNoneValue() }}
                </el-form-item>
                <el-form-item label="机构名称" prop="username">
                    <el-input v-model="formData.username" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="机构类型">
                    {{ data ? usertype2Enum.getEnumTypeName(data.rspResult.usertype) : handleNoneValue() }}
                </el-form-item>
                <el-form-item label="推荐人" prop="refereeuserid">
                    <app-select-member ref="refereeuseridRef" v-model="formData.refereeuserid" />
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ isPerson ? '个人' : '企业' }}资料</legend>
                <el-form-item label="名称" prop="customername">
                    <el-input v-model="formData.customername" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="公司" prop="company" v-if="isPerson">
                    <el-input v-model="formData.company" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="企业性质" prop="biznature" v-if="!isPerson">
                    <app-enum code="biznature" v-model="formData.biznature" />
                </el-form-item>
                <el-form-item label="证件类型" prop="cardtypeid">
                    <app-enum code="certypecompany" v-model="formData.cardtypeid" v-if="!isPerson" />
                    <app-enum code="certypeperson" v-model="formData.cardtypeid" v-else />
                </el-form-item>
                <el-form-item label="证件号码" prop="cardnum">
                    <el-input v-model="formData.cardnum" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="证件照正面" prop="cardfrontphotourl">
                    <app-upload v-model="uploadFiles.cardfrontphotourl" :file-types="['image']"
                        type-message="请选择正确的图片类型" />
                </el-form-item>
                <el-form-item label="证件照反面" prop="cardbackphotourl" v-if="isPerson">
                    <app-upload v-model="uploadFiles.cardbackphotourl" :file-types="['image']"
                        type-message="请选择正确的图片类型" />
                </el-form-item>
                <template v-if="!isPerson">
                    <el-form-item label="法人姓名" prop="legalpersonname">
                        <el-input v-model="formData.legalpersonname" maxlength="50" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="法人身份证正面" prop="legalcardfrontphotourl">
                        <app-upload v-model="uploadFiles.legalcardfrontphotourl" :file-types="['image']"
                            type-message="请选择正确的图片类型" />
                    </el-form-item>
                    <el-form-item label="法人身份证反面" prop="legalcardbackphotourl">
                        <app-upload v-model="uploadFiles.legalcardbackphotourl" :file-types="['image']"
                            type-message="请选择正确的图片类型" />
                    </el-form-item>
                    <el-form-item label="联系人" prop="contactname">
                        <el-input v-model="formData.contactname" maxlength="50" placeholder="请输入" />
                    </el-form-item>
                </template>
                <el-form-item label="性别" 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>
                <el-form-item label="手机号" prop="mobile">
                    <el-input type="number" v-model="formData.mobile" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="联系电话" prop="telphone">
                    <el-input type="number" v-model="formData.telphone" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item class="el-form-item--row" label="地区" prop="provinceid">
                    <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="地址" prop="address">
                    <el-input v-model="formData.address" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="邮政编码" prop="postalcode">
                    <el-input v-model="formData.postalcode" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="formData.email" maxlength="50" placeholder="请输入" />
                </el-form-item>
                <el-form-item class="el-form-item--row" label="备注" prop="remark">
                    <el-input type="textarea" v-model="formData.remark" maxlength="200" :rows="3" placeholder="请输入" />
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal" v-if="data && data.rspResult.usertype !== 4">
                <legend class="g-fieldset__legend">管理员及账户信息</legend>
                <el-form-item label="管理员名称">
                    {{ data.users.username }}
                </el-form-item>
                <el-form-item label="资金账户" prop="userinfotype" v-if="data.rspResult.usertype === 2">
                    {{ data.rspResult.reckonaccountid }}
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">附件</legend>
                <el-form-item label="附件1" prop="attachment1">
                    <app-upload v-model="uploadFiles.attachment1" :file-types="['image', 'pdf']"
                        type-message="请选择正确的图片类型" />
                </el-form-item>
                <el-form-item label="附件2" prop="attachment2">
                    <app-upload v-model="uploadFiles.attachment2" :file-types="['image', 'pdf']"
                        type-message="请选择正确的图片类型" />
                </el-form-item>
            </fieldset>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.cancel') }}</el-button>
            <el-button type="primary" :disabled="!data" @click="onSubmit">保存</el-button>
        </template>
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, computed } from 'vue'
import { ElMessage, FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { handleNoneValue } from '@/filters'
import { useEnum } from '@/hooks/enum'
import { decryptAES } from '@/services/crypto'
import { useRequest } from '@/hooks/request'
import { editOrgan, queryOrganDetail } from '@/services/api/member'
import { getGenderList, UserInfoType, getUserInfoTypeName } 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 service from '@/services'
import { i18n } from '@/stores'

const props = defineProps({
    record: {
        type: Object as PropType<Model.OrganDetailListRsp>,
        required: true
    }
})

// 机构类型
const usertype2Enum = useEnum('usertype2')

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

const refereeuseridRef = ref() // 推荐人组件实例

const formData = ref<Partial<Model.EditOrganReq>>({})

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

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

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 { data, loading } = useRequest(queryOrganDetail, {
    params: {
        areaId: props.record.userid
    },
    onSuccess: ((res) => {
        const { rspResult, userinfo, users } = res.data

        if (userinfo) {
            uploadFiles.cardfrontphotourl = getUploadFiles(userinfo.cardfrontphotourl)
            uploadFiles.cardbackphotourl = getUploadFiles(userinfo.cardbackphotourl)
            uploadFiles.legalcardfrontphotourl = getUploadFiles(userinfo.legalcardfrontphotourl)
            uploadFiles.legalcardbackphotourl = getUploadFiles(userinfo.legalcardbackphotourl)
            uploadFiles.attachment1 = getUploadFiles(userinfo.attachment1)
            uploadFiles.attachment2 = getUploadFiles(userinfo.attachment2)
        }

        formData.value = {
            accountname: rspResult.accountname,
            address: userinfo.address,
            attachment1: userinfo.attachment1,
            attachment2: userinfo.attachment2,
            autoid: users.autoid,
            biznature: userinfo.biznature,
            cardbackphotourl: userinfo.cardbackphotourl,
            cardfrontphotourl: userinfo.cardfrontphotourl,
            cardnum: decryptAES(userinfo.cardnum),
            cardtypeid: userinfo.cardtypeid,
            cityid: userinfo.cityid,
            company: userinfo.company,
            contactname: userinfo.contactname,
            customername: userinfo.customername,
            districtid: userinfo.districtid,
            email: decryptAES(userinfo.email),
            legalcardbackphotourl: userinfo.legalcardbackphotourl,
            legalcardfrontphotourl: userinfo.legalcardfrontphotourl,
            legalpersonname: userinfo.legalpersonname,
            logincode: userinfo.logincode,
            mobile: decryptAES(userinfo.mobile),
            modifystatus: rspResult.modifystatus,
            parentuserid: rspResult.parentuserid,
            postalcode: userinfo.postalcode,
            provinceid: userinfo.provinceid,
            qq: userinfo.qq,
            reckonaccountid: rspResult.reckonaccountid,
            refereeuserid: rspResult.refereeuserid,
            remark: userinfo.remark,
            sex: userinfo.sex,
            telphone: decryptAES(userinfo.telphone),
            userid: userinfo.userid,
            userinfotype: userinfo.userinfotype,
            username: users.username,
            usertype: userinfo.usertype,
            wechat: userinfo.wechat
        }

        refereeuseridRef.value.onReset(rspResult.refereeuserid)
    }),
    onError: (err) => {
        ElMessage.error(err)
    }
})

// 表单验证规则
const formRules: FormRules = {
    cardtypeid: [{ required: true }],
    username: [{ required: true }],
    customername: [{ required: true }],
    cardnum: [{ required: true }],
}

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.cardfrontphotourl = updateUploadFiles(uploadFiles.cardfrontphotourl)
    rawData.cardbackphotourl = updateUploadFiles(uploadFiles.cardbackphotourl)
    rawData.legalcardfrontphotourl = updateUploadFiles(uploadFiles.legalcardfrontphotourl)
    rawData.legalcardbackphotourl = updateUploadFiles(uploadFiles.legalcardbackphotourl)
    rawData.attachment1 = updateUploadFiles(uploadFiles.attachment1)
    rawData.attachment2 = updateUploadFiles(uploadFiles.attachment2)

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