<!-- 会员机构管理-子机构管理-子机构管理-编辑 -->
<template>
    <app-drawer :title="t('member.subinstitution.manage.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">{{ t('common.baseinfo') }}</legend>
                <el-form-item :label="t('member.subinstitution.manage.edit.referral')" prop="parentuserid"
                    v-if="!record">
                    <span v-if="selectedParent">{{ selectedParent.accountname }}</span>
                    <app-select-institution ref="parentuseridRef" v-model="formData.parentuserid"
                        :params="{ usertype: '3', level: 5, roles: '7' }"
                        :placeholder="t('member.subinstitution.manage.edit.tips1')" v-else />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.userinfotype')" prop="userinfotype">
                    <span v-if="record">{{ userinfotypeEnum.getEnumTypeName(formData.userinfotype) }}</span>
                    <app-enum code="userinfotype" type="radio" v-model="formData.userinfotype" v-else />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.userid')" prop="userid">
                    <span v-if="record">{{ formData.userid }}</span>
                    <el-input v-model="formData.userid" maxlength="4" :placeholder="t('common.pleaseenter')" v-else />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.usertype')" v-if="record">
                    {{ usertype2Enum.getEnumTypeName(record.usertype) }}
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.accountname')" prop="accountname">
                    <el-input v-model="formData.accountname" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.refereeuserid')" prop="refereeuserid">
                    <app-select-member ref="refereeuseridRef" v-model="formData.refereeuserid"
                        :params="{ usertype: '2,3' }" :placeholder="t('member.subinstitution.manage.edit.tips1')" />
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ isPerson ? t('member.subinstitution.manage.edit.person') :
                    t('member.subinstitution.manage.edit.companny') }}{{ t('member.subinstitution.manage.edit.profile')
                    }}</legend>
                <el-form-item :label="t('member.subinstitution.manage.edit.customername')" prop="customername">
                    <el-input v-model="formData.customername" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.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('member.subinstitution.manage.edit.biznature')" prop="biznature"
                    v-if="!isPerson">
                    <app-enum code="biznature" v-model="formData.biznature" :empty-values="[0]" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.cardtypeid')" 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="t('member.subinstitution.manage.edit.cardnum')" prop="cardnum">
                    <el-input v-model="formData.cardnum" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.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('member.subinstitution.manage.edit.cardbackphotourl')" prop="cardbackphotourl"
                    v-if="isPerson">
                    <app-upload v-model="uploadFiles.cardbackphotourl" :file-types="['image']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
                <template v-if="!isPerson">
                    <el-form-item :label="t('member.subinstitution.manage.edit.legalpersonname')"
                        prop="legalpersonname">
                        <el-input v-model="formData.legalpersonname" maxlength="50"
                            :placeholder="t('common.pleaseenter')" />
                    </el-form-item>
                    <el-form-item :label="t('member.subinstitution.manage.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('member.subinstitution.manage.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>
                    <el-form-item :label="t('member.subinstitution.manage.edit.contactname')" prop="contactname">
                        <el-input v-model="formData.contactname" maxlength="50"
                            :placeholder="t('common.pleaseenter')" />
                    </el-form-item>
                </template>
                <el-form-item :label="t('member.subinstitution.manage.edit.sex')" prop="sex">
                    <app-enum code="Sex" type="radio" v-model="formData.sex" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.mobile')" prop="mobile">
                    <el-input type="number" v-model="formData.mobile" maxlength="50"
                        :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.telphone')" prop="telphone">
                    <el-input v-model="formData.telphone" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item class="el-form-item--row" :label="t('member.subinstitution.manage.edit.provinceid')"
                    prop="provinceid">
                    <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('member.subinstitution.manage.edit.address')"
                    prop="address">
                    <el-input v-model="formData.address" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.postalcode')" prop="postalcode">
                    <el-input v-model="formData.postalcode" maxlength="50" :placeholder="t('common.pleaseenter')" />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.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('member.subinstitution.manage.edit.remark')"
                    prop="remark">
                    <el-input type="textarea" v-model="formData.remark" maxlength="200" :rows="3"
                        :placeholder="t('common.pleaseenter')" />
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('member.subinstitution.manage.edit.subtitle') }}</legend>
                <el-form-item :label="t('member.subinstitution.manage.edit.logincode')" prop="logincode">
                    <span v-if="record">{{ formData.logincode }}</span>
                    <el-input v-model="formData.logincode" maxlength="50" :placeholder="t('common.pleaseenter')"
                        v-else />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.username')" prop="username">
                    <span v-if="record">{{ formData.username }}</span>
                    <el-input v-model="formData.username" maxlength="50" :placeholder="t('common.pleaseenter')"
                        v-else />
                </el-form-item>
                <el-form-item :label="t('member.subinstitution.manage.edit.smpassword')" prop="smpassword"
                    v-if="!record">
                    <span>123456</span>
                </el-form-item>
            </fieldset>
            <fieldset class="g-fieldset el-form--horizontal">
                <legend class="g-fieldset__legend">{{ t('common.annex') }}</legend>
                <el-form-item :label="t('common.annex1')" prop="attachment1">
                    <app-upload v-model="uploadFiles.attachment1" :file-types="['image', 'pdf']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
                <el-form-item :label="t('common.annex2')" prop="attachment2">
                    <app-upload v-model="uploadFiles.attachment2" :file-types="['image', 'pdf']"
                        :type-message="t('common.tips21')" :max-size="uploadConfig.maxFileSize" />
                </el-form-item>
            </fieldset>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit(2)">{{ t('operation.save') }}</el-button>
            <template v-if="record && [3, 4].includes(record.usertype)">
                <!-- 变更提交审核 -->
                <el-button type="primary" @click="onSubmit(4)" v-if="record.accountstatus === 4">
                    {{ t('operation.submitaduit') }}
                </el-button>
                <!-- 新增提交审核 -->
                <el-button type="primary" @click="onSubmit(record.modifystatus, 2)" v-if="record.accountstatus === 5">
                    {{ t('operation.submitaduit') }}
                </el-button>
            </template>
        </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 { useEnum } from '@/hooks/enum'
import { useRequest } from '@/hooks/request'
import { organSonViewson, organSonAdd, organSonSave, organSonEdit } from '@/services/api/member'
import { 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 AppSelectInstitution from '@pc/components/modules/select-institution/index.vue'
import { i18n } from '@/stores'

const props = defineProps({
    selectedParent: {
        type: Object as PropType<Member.AreaAndAllChildsRsp>
    },
    record: {
        type: Object as PropType<Member.OrganSonRsp>
    }
})

const usertype2Enum = useEnum('usertype2') // 机构类型
const userinfotypeEnum = useEnum('userinfotype') // 所有者类型

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

const parentuseridRef = ref() // 上级机构组件实例
const refereeuseridRef = ref() // 推荐人组件实例

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 formData = ref<Partial<Member.OrganSonUpdateReq>>({
    parentuserid: props.selectedParent?.userid,
    userinfotype: UserInfoType.Company,
    sex: Gender.Male,
    usertype: 3
})

const { loading, run } = useRequest(organSonViewson, {
    manual: true,
    onSuccess: ((res) => {
        const { logincode, username, oldResult: { userAccountDetailVo, userinfoDetailVo } } = res.data
        formData.value = {
            accountname: userAccountDetailVo.accountName,
            accountstatus: userAccountDetailVo.accountStatus,
            address: userinfoDetailVo.address,
            biznature: userinfoDetailVo.bizNature,
            cardnum: decryptAES(userinfoDetailVo.cardNum),
            cardtypeid: userinfoDetailVo.cardTypeId,
            cityid: userinfoDetailVo.cityid,
            company: userinfoDetailVo.company,
            contactname: userinfoDetailVo.contactName,
            customername: userinfoDetailVo.customerName,
            districtid: userinfoDetailVo.districtid,
            countryid: userinfoDetailVo.countryid,
            email: userinfoDetailVo.email,
            legalpersonname: userinfoDetailVo.legalPersonName,
            logincode: logincode,
            mobile: userinfoDetailVo.mobile,
            modifystatus: userAccountDetailVo.modifyStatus,
            parentuserid: userAccountDetailVo.parentuserid,
            postalcode: userinfoDetailVo.postalCode,
            provinceid: userinfoDetailVo.provinceid,
            qq: userinfoDetailVo.qq,
            refereeuserid: userAccountDetailVo.refereeuserid,
            remark: userinfoDetailVo.remark,
            sex: userinfoDetailVo.sex,
            telphone: userinfoDetailVo.telPhone,
            userid: userAccountDetailVo.userId,
            userinfotype: userinfoDetailVo.userinfoType,
            username: username,
            usertype: userAccountDetailVo.usertype,
            wechat: userinfoDetailVo.wechat
        }
        uploadFiles.cardfrontphotourl = parseFilePaths(userinfoDetailVo.cardBackPhotoUrl)
        uploadFiles.cardbackphotourl = parseFilePaths(userinfoDetailVo.cardFrontPhotoUrl)
        uploadFiles.legalcardfrontphotourl = parseFilePaths(userinfoDetailVo.legalCardFrontPhotoUrl)
        uploadFiles.legalcardbackphotourl = parseFilePaths(userinfoDetailVo.legalCardBackPhotoUrl)
        uploadFiles.attachment1 = parseFilePaths(userinfoDetailVo.attachment1)
        uploadFiles.attachment2 = parseFilePaths(userinfoDetailVo.attachment2)

        parentuseridRef.value?.onReset(userAccountDetailVo.parentuserid)
        refereeuseridRef.value.onReset(userAccountDetailVo.refereeuserid)
    }),
    onError: (err) => {
        ElMessage.error(err)
    }
})

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

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

const onSubmit = (modifystatus: number, accountstatus?: number) => {
    const rawData = { ...formData.value }
    rawData.cardfrontphotourl = extractFilePaths(uploadFiles.cardfrontphotourl)
    rawData.cardbackphotourl = extractFilePaths(uploadFiles.cardbackphotourl)
    rawData.legalcardfrontphotourl = extractFilePaths(uploadFiles.legalcardfrontphotourl)
    rawData.legalcardbackphotourl = extractFilePaths(uploadFiles.legalcardbackphotourl)
    rawData.attachment1 = extractFilePaths(uploadFiles.attachment1)
    rawData.attachment2 = extractFilePaths(uploadFiles.attachment2)

    formRef.value?.validate((valid) => {
        if (valid) {
            loading.value = true
            if (props.record) {
                rawData.modifystatus = modifystatus
                if (rawData.modifystatus === 4) {
                    // 修改审核
                    organSonEdit({
                        data: rawData
                    }).then(() => {
                        ElMessage.success(t('common.tips7'))
                        onCancel(true)
                    }).catch((err) => {
                        ElMessage.error(t('common.tips8') + err)
                    }).finally(() => {
                        loading.value = false
                    })
                } else {
                    if (accountstatus) {
                        // 新增审核
                        rawData.accountstatus = accountstatus
                    }
                    // 保存
                    organSonSave({
                        data: rawData
                    }).then(() => {
                        ElMessage.success(t('common.tips3'))
                        onCancel(true)
                    }).catch((err) => {
                        ElMessage.error(t('common.tips4') + err)
                    }).finally(() => {
                        loading.value = false
                    })
                }
            } else {
                // 新增
                organSonAdd({
                    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, modifystatus } = props.record ?? {}
    if (userid) {
        run({
            areaid: userid,
            modifystatus
        })
    }
})
</script>