<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">分账商户内部商户号</label>
                    <input type="text" class="form-input" v-model="formData.merInnerNo" placeholder="请输入分账商户内部商户号">
                </view>

                <view class="form-item">
                    <label class="form-label">分账商户银联商户号</label>
                    <input type="text" class="form-input" v-model="formData.merCupNo" placeholder="请输入分账商户银联商户号">
                </view>

                <view class="form-item">
                    <label class="form-label required">分账接收方编号</label>
                    <input type="text" class="form-input" v-model="formData.receiverNo" placeholder="请输入分账接收方编号"
                        required>
                </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.entrustFileName" placeholder="请输入合作协议附件名称"
                        required>
                </view>
                <button class="upload-btn" @click="uploadEntrustFile">上传合作协议</button>
                <view v-if="formData.entrustFilePath" class="file-info">
                    <span>{{ formData.entrustFileName || '已上传文件' }}</span>
                    <button class="delete-btn" @click="removeEntrustFile">删除</button>
                </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.attachments" :key="index">
                        <view class="form-item">
                            <label class="form-label">附件类型</label>
                            <view class="popup-select" @click="showAttachTypePopup = index">
                                <span>{{ getAttachTypeLabel(attachment.attachType) || '请选择附件类型' }}</span>
                            </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 {
            // 弹窗控制
            showAttachTypePopup: -1,

            // 附件类型选项
            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: {
                // 可选字段
                merInnerNo: '',
                merCupNo: '',
                // 必需字段
                receiverNo: '',
                entrustFileName: '',
                entrustFilePath: '',
                // 可选附件列表
                attachments: [{
                    attachType: '',
                    attachName: '',
                    attachStorePath: ''
                }]
            }
        };
    },
    methods: {
        // 添加附件
        addAttachment() {
            this.formData.attachments.push({
                attachType: '',
                attachName: '',
                attachStorePath: ''
            });
        },

        // 选择附件类型
        selectAttachType(index, type) {
            this.formData.attachments[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.attachments.splice(index, 1);
        },

        // 上传合作协议文件
        uploadEntrustFile() {
            // 调用 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 (!this.formData.entrustFileName) {
                        this.formData.entrustFileName = tempFile.name;
                    }

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

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

                            // 更新附件信息
                            this.formData.entrustFilePath = 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'
                    });
                }
            });
        },

        // 删除合作协议文件
        removeEntrustFile() {
            this.formData.entrustFileName = '';
            this.formData.entrustFilePath = '';
        },

        // 上传其他附件
        uploadFile(index) {
            const attachment = this.formData.attachments[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.receiverNo) {
                uni.showToast({ title: '请输入分账接收方编号', icon: 'none' });
                return false;
            }

            if (!formData.entrustFileName) {
                uni.showToast({ title: '请输入合作协议附件名称', icon: 'none' });
                return false;
            }

            if (!formData.entrustFilePath) {
                uni.showToast({ title: '请上传合作协议附件', icon: 'none' });
                return false;
            }

            return true;
        },

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

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

            // 准备请求参数
            const submitData = {
                merInnerNo: this.formData.merInnerNo, // 分账商户内部商户号（可选）
                merCupNo: this.formData.merCupNo, // 分账商户银联商户号（可选）
                receiverNo: this.formData.receiverNo, // 分账接收方编号（必需）
                entrustFileName: this.formData.entrustFileName, // 合作协议附件名称（必需）
                entrustFilePath: this.formData.entrustFilePath, // 合作协议附件路径（必需）
                attachments: [] // 分账关系绑定申请附件（可选）
            };

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

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

            // 调用applyBind接口提交数据
            request(apiArr.applyBind, "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 = {
                merInnerNo: '',
                merCupNo: '',
                receiverNo: '',
                entrustFileName: '',
                entrustFilePath: '',
                attachments: []
            };
        }
    }
}
</script>

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