<template>
    <view class="establish-acceptor-container">
        <form class="acceptor-form" @submit.prevent="submitForm">
            <!-- 必需字段 -->
            <view class="form-section">
                <!-- <view class="form-item">
          <label class="form-label required">商户号</label>
          <input 
            type="number" 
            class="form-input" 
            v-model="formData.mchId" 
            placeholder="请输入商户号" 
            required
          >
        </view> -->

                <view class="form-item">
                    <label class="form-label required">分账接收方名称</label>
                    <input type="text" class="form-input" v-model="formData.receiverName" placeholder="请输入分账接收方名称"
                        required>
                </view>

                <view class="form-item">
                    <label class="form-label required">联系手机号</label>
                    <input type="tel" class="form-input" v-model="formData.contactMobile" placeholder="请输入联系手机号"
                        required>
                </view>
            </view>

            <view class="form-section">
                <view class="form-item">
                    <label class="form-label">营业执照号码</label>
                    <input type="text" class="form-input" v-model="formData.licenseNo" placeholder="请输入营业执照号码">
                </view>

                <view class="form-item">
                    <label class="form-label">营业执照名称</label>
                    <input type="text" class="form-input" v-model="formData.licenseName" placeholder="请输入营业执照名称">
                </view>

                <view class="form-item">
                    <label class="form-label">法人姓名</label>
                    <input type="text" class="form-input" v-model="formData.legalPersonName" placeholder="请输入法人姓名">
                </view>

                <view class="form-item">
                    <label class="form-label">法人证件号</label>
                    <input type="text" class="form-input" v-model="formData.legalPersonCertificateNo"
                        placeholder="请输入法人证件号">
                </view>
            </view>

            <view class="form-section">
                <view class="form-item">
                    <label class="form-label required">收款账户卡号</label>
                    <input type="text" class="form-input" v-model="formData.acctNo" placeholder="请输入收款账户卡号" required>
                </view>

                <view class="form-item">
                    <label class="form-label required">收款账户名称</label>
                    <input type="text" class="form-input" v-model="formData.acctName" placeholder="请输入收款账户名称" required>
                </view>

                <view class="form-item">
                    <label class="form-label required">收款账户类型</label>
                    <view class="popup-select" @click="showAccountTypePopup = true">
                        <span class="selected-value">{{ selectedAccountType || '请选择账户类型' }}</span>
                        <uni-icons type="down" size="16"></uni-icons>
                    </view>
                    <!-- 账户类型弹窗 -->
                    <view class="popup" v-if="showAccountTypePopup">
                        <view class="popup-content">
                            <view class="popup-title">选择账户类型</view>
                            <view class="popup-list">
                                <view class="popup-item" v-for="type in accountTypeOptions" :key="type.value"
                                    @click="selectAccountType(type)">
                                    {{ type.label }}
                                </view>
                            </view>
                            <view class="popup-footer">
                                <button class="popup-cancel-btn" @click="showAccountTypePopup = false">取消</button>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="form-item">
                    <label class="form-label required">收款账户证件号</label>
                    <input type="text" class="form-input" v-model="formData.acctCertificateNo" placeholder="请输入收款账户证件号"
                        required>
                </view>

                <view class="form-item">
                    <label class="form-label required">收款账户开户行号</label>
                    <input type="text" class="form-input" v-model="formData.acctOpenBankCode" placeholder="请输入开户行号"
                        required>
                </view>

                <view class="form-item">
                    <label class="form-label required">收款账户开户行名称</label>
                    <input type="text" class="form-input" v-model="formData.acctOpenBankName" placeholder="请输入开户行名称"
                        required>
                </view>

                <view class="form-item">
                    <label class="form-label required">收款账户清算行行号</label>
                    <input type="text" class="form-input" v-model="formData.acctClearBankCode" placeholder="请输入清算行行号"
                        required>
                </view>
            </view>

            <view class="form-section">
                <h3 class="section-title">附件上传（可选）</h3>

                <view class="attachment-section">
                    <view class="attachment-item" v-for="(attachment, index) in formData.attachList" :key="index">
                        <view class="form-item">
                            <label class="form-label">附件类型</label>
                            <view class="popup-select" @click="showAttachTypePopup = index">
                                <span class="selected-value">{{ getAttachTypeLabel(attachment.attachType) || '请选择附件类型'
                                    }}</span>
                                <uni-icons type="down" size="16"></uni-icons>
                            </view>
                        </view>
                        <view class="form-item">
                            <label class="form-label">附件名称</label>
                            <input type="text" class="form-input" v-model="attachment.attachName" placeholder="请输入附件名称">
                        </view>
                        <button class="upload-btn" @click="uploadFile(index)">上传文件</button>
                        <view v-if="attachment.attachStorePath" class="file-info">
                            <span>{{ attachment.attachName || '已上传文件' }}</span>
                            <button class="delete-btn" @click="removeAttachment(index)">删除</button>
                        </view>
                    </view>

                    <button class="add-attachment-btn" @click="addAttachment">添加附件</button>
                </view>
            </view>

            <view class="form-section submit-section">
                <button type="submit" class="submit-btn" @click="submitForm">提交申请</button>
            </view>
        </form>

        <!-- 附件类型弹窗 -->
        <view class="popup" v-if="showAttachTypePopup >= 0">
            <view class="popup-content">
                <view class="popup-title">选择附件类型</view>
                <view class="popup-list">
                    <view class="popup-item" v-for="type in attachTypeOptions" :key="type.value"
                        @click="selectAttachType(showAttachTypePopup, type)">
                        {{ type.label }}
                    </view>
                </view>
                <view class="popup-footer">
                    <button class="popup-cancel-btn" @click="showAttachTypePopup = -1">取消</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { picUrl, menuButtonInfo, request, NavgateTo, RequsetUrl } from "../../../utils";
import { apiArr } from "../../../api/contract";
export default {
    data() {
        return {
            // 弹窗控制
            showAccountTypePopup: false,
            showAttachTypePopup: -1,

            // 账户类型选项
            accountTypeOptions: [
                { value: '57', label: '对公' },
                { value: '58', label: '对私' }
            ],

            // 附件类型选项
            attachTypeOptions: [
                { value: 'FR_ID_CARD_FRONT', label: '法人身份证正面' },
                { value: 'FR_ID_CARD_BEHIND', label: '法人身份证反面' },
                { value: 'ID_CARD_FRONT', label: '结算人身份证正面' },
                { value: 'ID_CARD_BEHIND', label: '结算人身份证反面' },
                { value: 'BANK_CARD', label: '银行卡' },
                { value: 'BUSINESS_LICENCE', label: '营业执照' },
                { value: 'MERCHANT_PHOTO', label: '商户门头照' },
                { value: 'SHOPINNER', label: '商铺内部照片' },
                { value: 'XY', label: '线下纸质协议' },
                { value: 'NETWORK_XY', label: '电子协议' },
                { value: 'HT', label: '租赁合同' },
                { value: 'COOPERATION_QUALIFICATION_PROOF', label: '合作资质证明' },
                { value: 'FOOD_QUALIFICATION_PROOF', label: '食品经营相关资质' },
                { value: 'NO_LEGAL_PERSON_SETT_AUTH_LETTER', label: '非法人结算授权书' },
                { value: 'SPLIT_ENTRUST_FILE', label: '结算授权委托书' },
                { value: 'RENTAL_AGREEMENT', label: '集市方与场地方间的租赁协议' },
                { value: 'SPLIT_COOPERATION_FILE', label: '集市方与摊主间的合作协议' },
                { value: 'OTHERS', label: '其他' }
            ],

            formData: {
                // 必需字段
                mchId: '',
                receiverName: '',
                contactMobile: '',
                acctNo: '',
                acctName: '',
                acctTypeCode: '',
                acctCertificateNo: '',
                acctOpenBankCode: '',
                acctOpenBankName: '',
                acctClearBankCode: '',
                // 可选字段
                licenseNo: '',
                licenseName: '',
                legalPersonName: '',
                legalPersonCertificateNo: '',
                // 附件列表（初始添加一个空附件）
                attachList: [{
                    attachType: '',
                    attachName: '',
                    attachStorePath: ''
                }]
            }
        }
    },
    computed: {
        // 获取选中的账户类型标签
        selectedAccountType() {
            if (!this.formData.acctTypeCode) return '';
            const option = this.accountTypeOptions.find(type => type.value === this.formData.acctTypeCode);
            return option ? option.label : '';
        }
    },
    methods: {
        // 添加附件
        addAttachment() {
            this.formData.attachList.push({
                attachType: '',
                attachName: '',
                attachStorePath: ''
            });
        },

        // 选择账户类型
        selectAccountType(type) {
            this.formData.acctTypeCode = type.value;
            this.showAccountTypePopup = false;
        },

        // 选择附件类型
        selectAttachType(index, type) {
            this.formData.attachList[index].attachType = type.value;
            this.showAttachTypePopup = -1;
        },

        // 获取附件类型标签
        getAttachTypeLabel(typeValue) {
            if (!typeValue) return '';
            const option = this.attachTypeOptions.find(type => type.value === typeValue);
            return option ? option.label : '';
        },

        // 删除附件
        removeAttachment(index) {
            this.formData.attachList.splice(index, 1);
            // 如果列表为空，添加一个空附件以保持界面显示
            if (this.formData.attachList.length === 0) {
                this.formData.attachList.push({
                    attachType: '',
                    attachName: '',
                    attachStorePath: ''
                });
            }
        },

        // 上传文件
        uploadFile(index) {
            const attachment = this.formData.attachList[index];

            // 检查是否选择了附件类型
            if (!attachment.attachType) {
                uni.showToast({
                    title: '请先选择附件类型',
                    icon: 'none'
                });
                return;
            }

            // 调用 uni.chooseMessageFile API 选择文件（支持所有文件类型）
            uni.chooseMessageFile({
                count: 1,
                type: 'file',
                extension: ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'], // 支持的文件类型
                success: (res) => {
                    const tempFile = res.tempFiles[0];
                    console.log("选择的文件:", tempFile);

                    // 如果用户没有填写附件名称，使用选择的文件名
                    if (!attachment.attachName) {
                        attachment.attachName = tempFile.name;
                    }

                    // 显示上传中提示
                    uni.showLoading({
                        title: '上传中',
                        mask: true
                    });

                    // 直接使用uni.uploadFile上传文件
                    uni.uploadFile({
                        url: RequsetUrl + apiArr.upload, // 完整的上传接口URL
                        filePath: tempFile.path, // 文件路径
                        name: 'file', // 文件对应的key，根据后端要求设置
                        formData: {
                            attType: attachment.attachType // 其他表单参数
                        },
                        header: {
                            Authorization: uni.getStorageSync("ctoken") // 添加认证信息
                        },
                        success: (uploadRes) => {
                            // 解析响应数据
                            const res = JSON.parse(uploadRes.data);

                            // 更新附件信息
                            attachment.attachStorePath = res.data.respData.attFileId;

                            uni.showToast({
                                title: '上传成功',
                                icon: 'success'
                            });
                        },
                        fail: (error) => {
                            console.error('文件上传失败:', error);
                            uni.showToast({
                                title: '上传失败',
                                icon: 'none'
                            });
                        },
                        complete: () => {
                            uni.hideLoading(); // 隐藏加载提示
                        }
                    });
                },
                fail: (err) => {
                    console.error('选择文件失败:', err);
                    uni.showToast({
                        title: '选择文件失败',
                        icon: 'none'
                    });
                }
            });
        },

        // 表单验证
        validateForm() {
            const { formData } = this;

            // 验证必需字段
            //   if (!formData.mchId) {
            //     uni.showToast({ title: '请输入商户号', icon: 'none' });
            //     return false;
            //   }

            if (!formData.receiverName) {
                uni.showToast({ title: '请输入分账接收方名称', icon: 'none' });
                return false;
            }

            if (!formData.contactMobile) {
                uni.showToast({ title: '请输入联系手机号', icon: 'none' });
                return false;
            } else if (!/^1[3-9]\d{9}$/.test(formData.contactMobile)) {
                uni.showToast({ title: '请输入正确的手机号格式', icon: 'none' });
                return false;
            }

            if (!formData.acctNo) {
                uni.showToast({ title: '请输入收款账户卡号', icon: 'none' });
                return false;
            }

            if (!formData.acctName) {
                uni.showToast({ title: '请输入收款账户名称', icon: 'none' });
                return false;
            }

            if (!formData.acctTypeCode) {
                uni.showToast({ title: '请选择收款账户类型', icon: 'none' });
                return false;
            }

            if (!formData.acctCertificateNo) {
                uni.showToast({ title: '请输入收款账户证件号', icon: 'none' });
                return false;
            }

            if (!formData.acctOpenBankCode) {
                uni.showToast({ title: '请输入收款账户开户行号', icon: 'none' });
                return false;
            }

            if (!formData.acctOpenBankName) {
                uni.showToast({ title: '请输入收款账户开户行名称', icon: 'none' });
                return false;
            }

            if (!formData.acctClearBankCode) {
                uni.showToast({ title: '请输入收款账户清算行行号', icon: 'none' });
                return false;
            }

            return true;
        },

        // 表单提交逻辑
        submitForm() {
            // 验证表单
            if (!this.validateForm()) {
                return;
            }

            uni.showLoading({
                title: '提交中...',
                mask: true
            });

            // 准备请求参数
            const submitData = {
                mchId: '000', // 商户号（必需）
                receiverName: this.formData.receiverName, // 分账接收方名称（必需）
                contactMobile: this.formData.contactMobile, // 联系手机号（必需）
                licenseNo: this.formData.licenseNo, // 营业执照号码（可选）
                licenseName: this.formData.licenseName, // 营业执照名称（可选）
                legalPersonName: this.formData.legalPersonName, // 法人姓名（可选）
                legalPersonCertificateNo: this.formData.legalPersonCertificateNo, // 法人证件号（可选）
                acctNo: this.formData.acctNo, // 收款账户卡号（必需）
                acctName: this.formData.acctName, // 收款账户名称（必需）
                acctTypeCode: this.formData.acctTypeCode, // 收款账户类型（必需）
                acctCertificateNo: this.formData.acctCertificateNo, // 收款账户证件号（必需）
                acctOpenBankCode: this.formData.acctOpenBankCode, // 收款账户开户行号（必需）
                acctOpenBankName: this.formData.acctOpenBankName, // 收款账户开户行名称（必需）
                acctClearBankCode: this.formData.acctClearBankCode // 收款账户清算行行号（必需）
            };

            // 只添加有attachStorePath的附件到attachList
            const validAttachments = this.formData.attachList.filter(attach => attach.attachStorePath);
            if (validAttachments.length > 0) {
                submitData.attachList = validAttachments.map(attach => ({
                    attachType: attach.attachType,
                    attachName: attach.attachName,
                    attachStorePath: attach.attachStorePath
                }));
            }

            console.log('提交的数据:', submitData);

            request(apiArr.applyLedgerReceiver, "POST", submitData).then(res => {
                uni.hideLoading();

                if (res && res.cmdRetCode === 'SUCCESS') {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success'
                    });

                    setTimeout(() => {
                        uni.navigateBack();
                    }, 1500);
                } else {
                    uni.showToast({
                        title: res?.retMsg || '提交失败',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                uni.hideLoading();
                console.error('提交失败:', error);
                uni.showToast({
                    title: '提交失败',
                    icon: 'none'
                });
            });
        },

        // 重置表单
        resetForm() {
            this.formData = {
                // mchId: '',
                receiverName: '',
                contactMobile: '',
                acctNo: '',
                acctName: '',
                acctTypeCode: '',
                acctCertificateNo: '',
                acctOpenBankCode: '',
                acctOpenBankName: '',
                acctClearBankCode: '',
                licenseNo: '',
                licenseName: '',
                legalPersonName: '',
                legalPersonCertificateNo: '',
                attachList: []
            };
        }
    }
}
</script>

<style>
@import url("./index.css");
</style>