<template>
    <a-modal :visible="visible" :title="editMode ? $t('customer.editCustomer') : $t('customer.addCustomer')"
        :loading="loading" @ok="handleSubmit" @cancel="handleCancel" :width="720">
        <a-tabs>
            <a-tab-pane key="1" :title="$t('customer.basicInfo')">
                <a-form :model="formData" :rules="rules" ref="formRef" :label-col-props="{ span: 6 }"
                    :wrapper-col-props="{ span: 18 }">
                    <a-divider>{{ $t('customer.basicInfoSection') }}</a-divider>
                    <a-form-item field="customerInfo.customerCode" :label="$t('customer.customerCode')" required>
                        <a-input v-model="formData.customerInfo.customerCode"
                            :placeholder="$t('customer.enterCustomerCode')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.name" :label="$t('customer.customerName')" required>
                        <a-input v-model="formData.customerInfo.name" :placeholder="$t('customer.enterCustomerName')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="userInfo.username" :label="$t('customer.accountNumber')" required>
                        <a-input v-model="formData.userInfo.username" :placeholder="$t('customer.enterAccountNumber')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="userInfo.password" :label="$t('customer.password')" required>
                        <a-input-password v-model="formData.userInfo.password"
                            :placeholder="$t('customer.enterPassword')" :max-length="60" show-word-limit />
                        <a-button type="primary" @click="generatePassword">{{ $t('customer.generatePassword')
                            }}</a-button>
                    </a-form-item>
                    <a-form-item field="customerInfo.remark" :label="$t('customer.remark')">
                        <a-input v-model="formData.customerInfo.remark" :placeholder="$t('customer.enterRemark')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.exTime" :label="$t('customer.validPeriod')" required>
                        <a-date-picker v-model="formData.customerInfo.exTime"
                            :placeholder="$t('customer.selectValidPeriod')" value-format="YYYY-MM-DD" />
                    </a-form-item>
                    <a-form-item field="userInfo.state" :label="$t('customer.statusName')" required>
                        <a-radio-group v-model="formData.userInfo.state">
                            <a-radio value="1">{{ $t('customer.status.normal') }}</a-radio>
                            <a-radio value="2">{{ $t('customer.status.disabled') }}</a-radio>
                            <a-radio value="3">{{ $t('customer.status.pending') }}</a-radio>
                            <a-radio value="4">{{ $t('customer.status.suspended') }}</a-radio>
                        </a-radio-group>
                    </a-form-item>

                    <a-divider>{{ $t('customer.smsInfoSection') }}</a-divider>
                    <a-form-item field="customerInfo.smsSubCode" :label="$t('customer.smsSubCode')">
                        <a-input v-model="formData.customerInfo.smsSubCode"
                            :placeholder="$t('customer.enterSmsSubCode')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.smsName" :label="$t('customer.smsName')">
                        <a-input v-model="formData.customerInfo.smsName" :placeholder="$t('customer.enterSmsName')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.loginSmsTemplate" :label="$t('customer.loginSmsTemplate')">
                        <a-input v-model="formData.customerInfo.loginSmsTemplate"
                            :placeholder="$t('customer.enterLoginSmsTemplate')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.alarmSmsTemplate" :label="$t('customer.alarmSmsTemplate')">
                        <a-input v-model="formData.customerInfo.alarmSmsTemplate"
                            :placeholder="$t('customer.enterAlarmSmsTemplate')" :max-length="60" show-word-limit />
                    </a-form-item>
                </a-form>
            </a-tab-pane>
            <a-tab-pane key="2" :title="$t('customer.accountManagement')">
                <a-form :model="formData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
                    <a-form-item field="customerProperty.amount" :label="$t('customer.accountBalance')">
                        <a-input-number v-model="formData.customerProperty.amount" :min="0" :precision="2" :step="100"
                            :suffix="$t('customer.currency')" />
                    </a-form-item>
                    <a-form-item field="customerProperty.rechargeLimit" :label="$t('customer.rechargeLimit')">
                        <a-input-number v-model="formData.customerProperty.rechargeLimit" :min="0" :precision="2"
                            :step="1" :suffix="$t('customer.currencyPerTime')" />
                    </a-form-item>
                    <a-form-item field="customerProperty.lineOfCredit" :label="$t('customer.creditLimit')">
                        <a-input-number v-model="formData.customerProperty.lineOfCredit" :min="0" :precision="2"
                            :step="100" :suffix="$t('customer.currency')" />
                    </a-form-item>
                    <a-form-item field="customerProperty.smsUnitPrice" :label="$t('customer.mobileSmsPrice')">
                        <a-input-number v-model="formData.customerProperty.smsUnitPrice" :min="0" :precision="2"
                            :step="0.1" :suffix="$t('customer.currencyPerMessage')" />
                    </a-form-item>
                    <a-form-item field="customerProperty.iotSmsUnitPrice" :label="$t('customer.iotSmsPrice')">
                        <a-input-number v-model="formData.customerProperty.iotSmsUnitPrice" :min="0" :precision="2"
                            :step="0.1" :suffix="$t('customer.currencyPerMessage')" />
                    </a-form-item>
                    <a-form-item field="customerProperty.paymentMethod" :label="$t('customer.paymentMethodName')"
                        required>
                        <a-radio-group v-model="formData.customerProperty.paymentMethod">
                            <a-radio value="prepaid">{{ $t('customer.paymentMethod.prepaid') }}</a-radio>
                            <a-radio value="postpaid">{{ $t('customer.paymentMethod.postpaid') }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </a-tab-pane>
            <a-tab-pane key="3" :title="$t('customer.customerData')">
                <a-form :model="formData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
                    <a-divider>{{ $t('customer.basicInfoSection') }}</a-divider>
                    <a-form-item field="customerInfo.platformName" :label="$t('customer.platformName')" required>
                        <a-input v-model="formData.customerInfo.platformName"
                            :placeholder="$t('customer.enterPlatformName')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.companyName" :label="$t('customer.companyName')">
                        <a-input v-model="formData.customerInfo.companyName"
                            :placeholder="$t('customer.enterCompanyName')" :max-length="60" show-word-limit />
                    </a-form-item>

                    <a-form-item field="customerInfo.servicePhone" :label="$t('customer.servicePhone')">
                        <a-input v-model="formData.customerInfo.servicePhone"
                            :placeholder="$t('customer.enterServicePhone')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.domain" :label="$t('customer.domain')">
                        <a-input v-model="formData.customerInfo.domain" :placeholder="$t('customer.enterDomain')"
                            :max-length="60" show-word-limit />
                    </a-form-item>

                    <a-form-item field="customerInfo.homepageLicenseCode" :label="$t('customer.homepageLicenseCode')">
                        <a-input v-model="formData.customerInfo.homepageLicenseCode"
                            :placeholder="$t('customer.enterHomepageLicenseCode')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.companyAddress" :label="$t('customer.companyAddress')">
                        <a-textarea v-model="formData.customerInfo.companyAddress"
                            :placeholder="$t('customer.enterCompanyAddress')" :max-length="200" show-word-limit />
                    </a-form-item>

                    <a-divider>{{ $t('customer.contactPerson') }}</a-divider>
                    <a-form-item field="customerInfo.contactName" :label="$t('customer.contactName')">
                        <a-input v-model="formData.customerInfo.contactName"
                            :placeholder="$t('customer.enterContactName')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.phone" :label="$t('customer.contactPhone')">
                        <a-input v-model="formData.customerInfo.phone" :placeholder="$t('customer.enterContactPhone')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.email" :label="$t('customer.contactEmail')">
                        <a-input v-model="formData.customerInfo.email" :placeholder="$t('customer.enterContactEmail')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.qq" :label="$t('customer.contactQQ')">
                        <a-input v-model="formData.customerInfo.qq" :placeholder="$t('customer.enterContactQQ')"
                            :max-length="60" show-word-limit />
                    </a-form-item>

                    <a-divider>{{ $t('customer.deliveryInfo') }}</a-divider>
                    <a-form-item field="customerInfo.deliveryAddress" :label="$t('customer.deliveryAddress')">
                        <a-textarea v-model="formData.customerInfo.deliveryAddress"
                            :placeholder="$t('customer.enterDeliveryAddress')" :max-length="200" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.deliveryPhone" :label="$t('customer.deliveryPhone')">
                        <a-input v-model="formData.customerInfo.deliveryPhone"
                            :placeholder="$t('customer.enterDeliveryPhone')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInfo.deliveryName" :label="$t('customer.deliveryName')">
                        <a-input v-model="formData.customerInfo.deliveryName"
                            :placeholder="$t('customer.enterDeliveryName')" :max-length="60" show-word-limit />
                    </a-form-item>
                </a-form>
            </a-tab-pane>
            <a-tab-pane key="4" :title="$t('customer.interfaceParams')">
                <a-form :model="formData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
                    <a-divider>{{ $t('customer.basicInfoSection') }}</a-divider>
                    <a-form-item field="customerInterfaceParams.smsStatusReportUrl"
                        :label="$t('customer.smsStatusReportUrl')">
                        <a-input v-model="formData.customerInterfaceParams.smsStatusReportUrl"
                            :placeholder="$t('customer.enterSmsStatusReportUrl')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInterfaceParams.reportIp" :label="$t('customer.reportIp')">
                        <a-input v-model="formData.customerInterfaceParams.reportIp"
                            :placeholder="$t('customer.enterReportIp')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInterfaceParams.deliveryPriority"
                        :label="$t('customer.deliveryPriorityName')">
                        <a-select v-model="formData.customerInterfaceParams.deliveryPriority"
                            :placeholder="$t('customer.selectDeliveryPriority')">
                            <a-option value="high">{{ $t('customer.deliveryPriority.high') }}</a-option>
                            <a-option value="medium">{{ $t('customer.deliveryPriority.medium') }}</a-option>
                            <a-option value="low">{{ $t('customer.deliveryPriority.low') }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item field="customerInterfaceParams.dataReportUrl" :label="$t('customer.dataReportUrl')">
                        <a-input v-model="formData.customerInterfaceParams.dataReportUrl"
                            :placeholder="$t('customer.enterDataReportUrl')" :max-length="60" show-word-limit />
                    </a-form-item>
                </a-form>
            </a-tab-pane>
            <a-tab-pane key="5" :title="$t('customer.billingInfo')">
                <a-form :model="formData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
                    <a-form-item field="customerInvoice.invoiceTitle" :label="$t('customer.invoiceTitle')">
                        <a-input v-model="formData.customerInvoice.invoiceTitle"
                            :placeholder="$t('customer.enterInvoiceTitle')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.taxRegistrationNumber"
                        :label="$t('customer.taxRegistrationNumber')">
                        <a-input v-model="formData.customerInvoice.taxRegistrationNumber"
                            :placeholder="$t('customer.enterTaxRegistrationNumber')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.registeredAddress" :label="$t('customer.registeredAddress')">
                        <a-input v-model="formData.customerInvoice.registeredAddress"
                            :placeholder="$t('customer.enterRegisteredAddress')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.registeredPhone" :label="$t('customer.registeredPhone')">
                        <a-input v-model="formData.customerInvoice.registeredPhone"
                            :placeholder="$t('customer.enterRegisteredPhone')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.bankName" :label="$t('customer.bankName')">
                        <a-input v-model="formData.customerInvoice.bankName" :placeholder="$t('customer.enterBankName')"
                            :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.bankAccountName" :label="$t('customer.bankAccountName')">
                        <a-input v-model="formData.customerInvoice.bankAccountName"
                            :placeholder="$t('customer.enterBankAccountName')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.bankAccountNumber" :label="$t('customer.bankAccountNumber')">
                        <a-input v-model="formData.customerInvoice.bankAccountNumber"
                            :placeholder="$t('customer.enterBankAccountNumber')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.taxIdentificationNumber"
                        :label="$t('customer.taxIdentificationNumber')">
                        <a-input v-model="formData.customerInvoice.taxIdentificationNumber"
                            :placeholder="$t('customer.enterTaxIdentificationNumber')" :max-length="60"
                            show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.invoiceRecipient" :label="$t('customer.invoiceRecipient')">
                        <a-input v-model="formData.customerInvoice.invoiceRecipient"
                            :placeholder="$t('customer.enterInvoiceRecipient')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.recipientPhone" :label="$t('customer.recipientPhone')">
                        <a-input v-model="formData.customerInvoice.recipientPhone"
                            :placeholder="$t('customer.enterRecipientPhone')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.invoiceAddress" :label="$t('customer.invoiceAddress')">
                        <a-input v-model="formData.customerInvoice.invoiceAddress"
                            :placeholder="$t('customer.enterInvoiceAddress')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.invoiceEmail" :label="$t('customer.invoiceEmail')">
                        <a-input v-model="formData.customerInvoice.invoiceEmail"
                            :placeholder="$t('customer.enterInvoiceEmail')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerInvoice.businessLicenseFile"
                        :label="$t('customer.businessLicenseFile')">
                        <a-upload :show-file-list="false"
                            :custom-request="(option) => handleUpload(option, 'business_license')">
                            <template #upload-button>
                                <a-button>{{ $t('customer.uploadFile') }}</a-button>
                            </template>
                        </a-upload>
                    </a-form-item>
                    <a-form-item field="customerInvoice.taxRegistrationFile"
                        :label="$t('customer.taxRegistrationFile')">
                        <a-upload :show-file-list="false"
                            :custom-request="(option) => handleUpload(option, 'tax_registration')">
                            <template #upload-button>
                                <a-button>{{ $t('customer.uploadFile') }}</a-button>
                            </template>
                        </a-upload>
                    </a-form-item>
                    <a-form-item field="customerInvoice.generalTaxpayerFile"
                        :label="$t('customer.generalTaxpayerFile')">
                        <a-upload :show-file-list="false"
                            :custom-request="(option) => handleUpload(option, 'general_taxpayer')">
                            <template #upload-button>
                                <a-button>{{ $t('customer.uploadFile') }}</a-button>
                            </template>
                        </a-upload>
                    </a-form-item>
                </a-form>
            </a-tab-pane>
            <a-tab-pane key="6" :title="$t('customer.purchaseQuality')">
                <a-form :model="formData" :label-col-props="{ span: 8 }" :wrapper-col-props="{ span: 16 }">
                    <template v-for="(field, index) in imageUploadFields" :key="field">
                        <a-form-item :field="field" :label="$t(`customer.${field}`)">
                            <a-upload action="/" :file-list="formData[field] ? [formData[field]] : []"
                                :show-file-list="false" @change="(_, file) => handleFileUpload(field, file)"
                                @progress="(file) => handleFileProgress(field, file)">
                                <template #upload-button>
                                    <div :class="`arco-upload-list-item${formData[field] && formData[field].status === 'error' ? ' arco-upload-list-item-error' : ''
                                        }`">
                                        <div class="arco-upload-list-picture custom-upload-avatar"
                                            v-if="formData[field] && formData[field].url">
                                            <img :src="formData[field].url" />
                                            <div class="arco-upload-list-picture-mask">
                                                <icon-edit />
                                            </div>
                                            <a-progress
                                                v-if="formData[field].status === 'uploading' && formData[field].percent < 100"
                                                :percent="formData[field].percent" type="circle" size="mini" :style="{
                                                    position: 'absolute',
                                                    left: '50%',
                                                    top: '50%',
                                                    transform: 'translateX(-50%) translateY(-50%)',
                                                }" />
                                        </div>
                                        <div class="arco-upload-picture-card" v-else>
                                            <div class="arco-upload-picture-card-text">
                                                <icon-plus />
                                                <div style="margin-top: 10px; font-weight: 600">{{
                                                    $t('customer.uploadFile') }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </a-upload>
                            <div class="upload-description">
                                {{ $t('customer.imageUploadDescription') }}
                            </div>
                        </a-form-item>
                    </template>

                    <a-form-item field="customerCardQualification.obtainMethod" :label="$t('customer.obtainMethod')">
                        <a-upload action="/" :file-list="formData.customerCardQualification.obtainMethod"
                            @change="handleObtainMethodUpload" multiple>
                            <template #upload-button>
                                <a-button>{{ $t('customer.uploadFile') }}</a-button>
                            </template>
                        </a-upload>
                        <div class="upload-description">
                            {{ $t('customer.obtainMethodDescription') }}
                        </div>
                    </a-form-item>

                    <a-form-item field="customerCardQualification.telephoneApplicationForm"
                        :label="$t('customer.telephoneApplicationForm')">
                        <a-upload action="/" :file-list="formData.customerCardQualification.telephoneApplicationForm"
                            @change="handleTelephoneApplicationFormUpload" multiple>
                            <template #upload-button>
                                <a-button>{{ $t('customer.uploadFile') }}</a-button>
                            </template>
                        </a-upload>
                        <div class="upload-description">
                            {{ $t('customer.telephoneApplicationFormDescription') }}
                        </div>
                    </a-form-item>

                    <a-form-item field="customerCardQualification.otherDocuments"
                        :label="$t('customer.otherDocuments')">
                        <a-upload action="/" :file-list="formData.customerCardQualification.otherDocuments"
                            @change="handleOtherDocumentsUpload" multiple>
                            <template #upload-button>
                                <a-button>{{ $t('customer.uploadFile') }}</a-button>
                            </template>
                        </a-upload>
                        <div class="upload-description">
                            {{ $t('customer.otherDocumentsDescription') }}
                        </div>
                    </a-form-item>
                </a-form>
            </a-tab-pane>
            <a-tab-pane key="7" :title="$t('customer.warningNumbers')">
                <a-form :model="formData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
                    <a-form-item field="customerWarningParameter.accountBalanceWarning"
                        :label="$t('customer.accountBalanceWarning')">
                        <a-input-number v-model="formData.customerWarningParameter.accountBalanceWarning" :min="0"
                            :precision="2" :step="100" :style="{ width: '100%' }" />
                    </a-form-item>
                    <a-form-item field="customerWarningParameter.reachWarning" :label="$t('customer.reachWarning')">
                        <a-input-number v-model="formData.customerWarningParameter.reachWarning" :min="0" :max="100"
                            :precision="0" :step="1" :style="{ width: '100%' }">
                            <template #append>%</template>
                        </a-input-number>
                    </a-form-item>
                    <a-form-item field="customerWarningParameter.stopSending" :label="$t('customer.stopSending')">
                        <a-space>
                            <a-input-number v-model="formData.customerWarningParameter.stopSending" :min="0" :max="100"
                                :precision="0" :step="1" :style="{ width: '100px' }">
                                <template #append>%</template>
                            </a-input-number>
                            <a-radio-group v-model="formData.customerWarningParameter.stopSendingAction">
                                <a-radio value="noRecovery">{{ $t('customer.noRecovery') }}</a-radio>
                                <a-radio value="manualRecovery">{{ $t('customer.manualRecovery') }}</a-radio>
                                <a-radio value="autoRecovery">{{ $t('customer.autoRecovery') }}</a-radio>
                            </a-radio-group>
                        </a-space>
                    </a-form-item>
                    <a-form-item field="customerWarningParameter.networkDisconnection"
                        :label="$t('customer.networkDisconnection')">
                        <a-space>
                            <a-input-number v-model="formData.customerWarningParameter.networkDisconnection" :min="0"
                                :max="100" :precision="0" :step="1" :style="{ width: '100px' }">
                                <template #append>%</template>
                            </a-input-number>
                            <a-radio-group v-model="formData.customerWarningParameter.networkDisconnectionAction">
                                <a-radio value="noRecovery">{{ $t('customer.noRecovery') }}</a-radio>
                                <a-radio value="manualRecovery">{{ $t('customer.manualRecovery') }}</a-radio>
                                <a-radio value="autoRecovery">{{ $t('customer.autoRecovery') }}</a-radio>
                            </a-radio-group>
                        </a-space>
                    </a-form-item>
                    <a-form-item field="customerWarningParameter.warningPhones" :label="$t('customer.warningPhones')">
                        <a-input v-model="formData.customerWarningParameter.warningPhones"
                            :placeholder="$t('customer.enterWarningPhones')" :max-length="60" show-word-limit />
                    </a-form-item>
                    <a-form-item field="customerWarningParameter.warningEmails" :label="$t('customer.warningEmails')">
                        <a-input v-model="formData.customerWarningParameter.warningEmails"
                            :placeholder="$t('customer.enterWarningEmails')" :max-length="60" show-word-limit />
                    </a-form-item>
                </a-form>
            </a-tab-pane>
        </a-tabs>
    </a-modal>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useI18n } from 'vue-i18n';
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon';
import dayjs from 'dayjs';
import { useSystemStore } from '@/store/modules/systemStore'

const { t } = useI18n();
const systemStore = useSystemStore()

const props = defineProps({
    visible: Boolean,
    editMode: Boolean,
    editData: Object,
    loading: Boolean,
});

watch(
    () => props.editData,
    (newVal) => {
        if (newVal && props.editMode) {
            // 深拷贝编辑数据
            const editDataCopy = JSON.parse(JSON.stringify(newVal));

            // 处理日期格式
            if (editDataCopy.customerInfo?.exTime) {
                editDataCopy.customerInfo.exTime = dayjs(editDataCopy.customerInfo.exTime).format('YYYY-MM-DD');
            }

            // 使用 Object.assign 更新每个子对象
            Object.keys(formData).forEach(key => {
                if (editDataCopy[key]) {
                    Object.assign(formData[key], editDataCopy[key]);
                }
            });
        }
    },
    { deep: true, immediate: true }
);

const emit = defineEmits(['update:visible', 'submit']);

const formRef = ref(null);
const formData = reactive({
    userInfo: {
        username: '',
        password: '',
        state: '1',
        name: '',
        id: null
    },
    customerInfo: {
        customerCode: '',
        name: '',
        platformName: '',
        companyName: '',
        servicePhone: '',
        phone: '',
        email: '',
        domain: '',
        smsName: '',
        exTime: null,
        remark: '',
        homepageLicenseCode: '',
        companyAddress: '',
        contactName: '',
        qq: '',
        deliveryAddress: '',
        deliveryPhone: '',
        deliveryName: '',
        smsSubCode: '',
    },
    customerProperty: {
        amount: 0,
        rechargeLimit: 0,
        lineOfCredit: 0,
        smsUnitPrice: 0,
        iotSmsUnitPrice: 0,
        paymentMethod: 'prepaid',
    },
    customerInvoice: {
        invoiceTitle: '',
        taxRegistrationNumber: '',
        registeredAddress: '',
        registeredPhone: '',
        bankName: '',
        bankAccountName: '',
        bankAccountNumber: '',
        taxIdentificationNumber: '',
        invoiceRecipient: '',
        recipientPhone: '',
        invoiceAddress: '',
        invoiceEmail: '',
        businessLicenseNumber: '',
        taxRegistrationFile: '',
        businessLicenseFile: '',
        generalTaxpayerFile: '',
    },
    customerCardQualification: {
        blImg: null,
        legalPersonIdCardImgUp: null,
        legalPersonIdCardImgDown: null,
        iotImg: null,
        contractImg: null,
        commitmentImg: null,
        customerForm: null,
        getCustomerText: '',
        phoneForm: null,
        otherFile: null,
    },
    customerWarningParameter: {
        accountBalanceWarning: 0,
        reachWarning: 0,
        stopSending: 0,
        stopSendingAction: 'noRecovery',
        networkDisconnection: 0,
        networkDisconnectionAction: 'noRecovery',
        warningPhones: '',
        warningEmails: '',
    },
    customerInterfaceParams: {
        smsStatusReportUrl: '',
        reportIp: '',
        deliveryPriority: '',
        dataReportUrl: '',
    },
});

const rules = {
    'userInfo.username': [{ required: true, message: t('customer.accountNumberRequired') }],
    'userInfo.password': [{ required: true, message: t('customer.passwordRequired') }],
    'customerInfo.customerCode': [{ required: true, message: t('customer.customerCodeRequired') }],
    'customerInfo.name': [{ required: true, message: t('customer.customerNameRequired') }],
    'customerInfo.exTime': [{ required: true, message: t('customer.validPeriodRequired') }],
    'userInfo.state': [{ required: true, message: t('customer.statusRequired') }],
    'customerInfo.platformName': [{ required: true, message: t('customer.platformNameRequired') }],
    'customerInfo.servicePhone': [{ required: true, message: t('customer.servicePhoneRequired') }],
};

const handleSubmit = () => {
    formRef.value.validate((errors) => {
        if (!errors) {
            // 处理文件字段
            const processedInvoice = {
                ...formData.customerInvoice,
                // 将数组转换为字符串或null
                taxRegistrationFile: formData.customerInvoice.taxRegistrationFile?.length ?
                    formData.customerInvoice.taxRegistrationFile[0]?.url || null : null,
                businessLicenseFile: formData.customerInvoice.businessLicenseFile?.length ?
                    formData.customerInvoice.businessLicenseFile[0]?.url || null : null,
                generalTaxpayerFile: formData.customerInvoice.generalTaxpayerFile?.length ?
                    formData.customerInvoice.generalTaxpayerFile[0]?.url || null : null,
            };
            const submitData = {
                userInfo: {
                    ...formData.userInfo,
                    // 设置userInfo.name为customerInfo.name
                    name: formData.customerInfo.name,
                    id: props.editMode ? props.editData.userInfo.id : undefined,
                },

                customerInfo: {
                    ...formData.customerInfo,
                    exTime: formData.customerInfo.exTime ?
                        dayjs(formData.customerInfo.exTime).format('YYYY-MM-DD') :
                        null
                },
                customerProperty: formData.customerProperty,
                customerInvoice: processedInvoice,
                customerCardQualification: formData.customerCardQualification,
                customerWarningParameter: formData.customerWarningParameter,
                customerInterfaceParams: formData.customerInterfaceParams,
            };

            emit('submit', submitData);
            emit('update:visible', false);
        }
    });
};

const handleCancel = () => {
    emit('update:visible', false);
};

const handleUpload = async (option, directory) => {
    const { file } = option.fileItem;
    const timestamp = Date.now(); // Get the current timestamp
    const fileName = `${directory}/${timestamp}_${file.name}`;
    const key = `customer_uploads/${fileName}`; // Base directory for customer uploads

    const client = await systemStore.getSTSClient();
    const resClient = await client.putObject({
        key: key,
        body: file
    });

    if (resClient.statusCode === 200) {
        console.log('File uploaded successfully to', key);
        formData.customerInvoice[directory + 'File'] = { url: key, name: file.name };
    }
};

const generatePassword = () => {
    formData.userInfo.password = Math.random().toString(36).slice(-8);
    Message.success(t('customer.passwordGenerated'));
};

// 文件上传的处理函数
const handleBusinessLicenseUpload = (fileList) => {
    formData.customerInvoice.businessLicenseFile = fileList;
};

const handleTaxRegistrationUpload = (fileList) => {
    formData.customerInvoice.taxRegistrationFile = fileList;
};

const handleGeneralTaxpayerUpload = (fileList) => {
    formData.customerInvoice.generalTaxpayerFile = fileList;
};

// 文件上传的 action，需要根据实际的后端 API 进行设置
const uploadAction = 'url';

const imageUploadFields = [
    'customerInvoice.businessLicenseFile',
    'customerCardQualification.legalPersonIdCardFrontFile',
    'customerCardQualification.legalPersonIdCardBackFile',
    'customerCardQualification.equipmentPurchaseFile',
    'customerCardQualification.businessContractFile',
    'customerCardQualification.informationSecurityFile',
    'customerCardQualification.customerInformationFile',
];

const handleFileUpload = (field, file) => {
    formData.customerCardQualification[field] = {
        ...file,
        url: URL.createObjectURL(file.file),
    };
};

const handleFileProgress = (field, file) => {
    formData.customerCardQualification[field] = file;
};

const handleObtainMethodUpload = (fileList) => {
    formData.customerCardQualification.obtainMethod = fileList;
};

const handleTelephoneApplicationFormUpload = (fileList) => {
    formData.customerCardQualification.telephoneApplicationForm = fileList;
};

const handleOtherDocumentsUpload = (fileList) => {
    formData.customerCardQualification.otherDocuments = fileList;
};


</script>

<style scoped>
.upload-description {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
}
</style>
