<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.number="formData.mch_id" placeholder="请输入商户号"
                        required>
                </view> -->

                <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="number" class="form-input" v-model="formData.contactMobile" placeholder="请输入联系手机号"
                        required>
                </view>

                <view class="form-item">
                    <label class="form-label">电子分账协议号</label>
                    <input type="text" class="form-input" v-model="formData.eleContractNo" placeholder="请输入电子分账协议号（可选）">
                </view>
            </view>

            <!-- 附件上传 -->
            <view class="form-section">
                <h3 class="section-title">附件上传（可选）</h3>
                <view class="attachment-section">
                    <view class="attachment-item" v-for="(file, index) in formData.fileData" :key="index">
                        <view class="form-item">
                            <label class="form-label">附件类型</label>
                            <view class="popup-select" @click="showFileAttachTypePopup = index">
                                <span>{{ getAttachTypeLabel(file.attType) || '请选择附件类型' }}</span>
                            </view>
                        </view>
                        <button class="upload-btn" @click="uploadFile(index)">上传文件</button>
                        <view v-if="file.attFileId" class="file-info">
                            <span>{{ file.attachName || '已上传文件' }}</span>
                            <button class="delete-btn" @click="removeFile(index)">删除</button>
                        </view>
                    </view>
                    <button class="add-attachment-btn" @click="addFile">添加附件</button>
                </view>
            </view>

            <!-- 提交按钮 -->
            <view class="form-section submit-section">
                <button type="button" class="submit-btn1" @click="ecQuery">结果查询</button>
                <button type="submit" class="submit-btn" @click="submitForm">提交申请</button>
            </view>
        </form>

        <!-- 文件附件类型弹窗 -->
        <view class="popup" v-if="showFileAttachTypePopup >= 0">
            <view class="popup-content">
                <view class="popup-title">选择附件类型</view>
                <view class="popup-list">
                    <view class="popup-item" v-for="type in fileAttachTypeOptions" :key="type.value"
                        @click="selectFileAttachType(showFileAttachTypePopup, type)">
                        {{ type.label }}
                    </view>
                </view>
                <view class="popup-footer">
                    <button class="popup-cancel-btn" @click="showFileAttachTypePopup = -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 {
            // 表单数据
            formData: {
                mch_id: uni.getStorageSync('mchId'), // 商户号（必需）
                merInnerNo: '', // 拉卡拉内部商户号（可选）
                merCupNo: '', // 银联商户号（可选）
                contactMobile: '', // 联系手机号（必需）
                eleContractNo: '', // 电子分账协议号（可选）
                fileData: [
                    {
                        attType: '',
                        attFileId: '',
                        attachName: ''
                    }
                ] // 文件数据（可选）
            },

            // 弹窗控制
            showFileAttachTypePopup: -1,

            // 文件附件类型选项（示例数据，实际应从API获取）
            fileAttachTypeOptions: [
                { value: 'BUSINESS_LICENSE', label: '营业执照' },
                { value: 'ID_CARD_FRONT', label: '身份证正面' },
                { value: 'ID_CARD_BACK', label: '身份证反面' },
                { value: 'BANK_CARD', label: '银行卡' },
                { value: 'CONTRACT', label: '合同文件' },
                { value: 'OTHER', label: '其他' }
            ]
        };
    },

    methods: {
        // 添加附件
        addFile() {
            this.formData.fileData.push({
                attType: '',
                attFileId: '',
                attachName: ''
            });
        },

        // 选择文件附件类型
        selectFileAttachType(index, type) {
            this.formData.fileData[index].attType = type.value;
            this.showFileAttachTypePopup = -1;
        },

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

        // 删除附件
        removeFile(index) {
            this.formData.fileData.splice(index, 1);
        },

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

            // 检查是否选择了附件类型
            if (!fileData.attType) {
                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);

                    // 设置文件名
                    fileData.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: fileData.attType // 附件类型
                        },
                        header: {
                            Authorization: uni.getStorageSync("ctoken") // 添加认证信息
                        },
                        success: (uploadRes) => {
                            // 解析响应数据
                            const res = JSON.parse(uploadRes.data);

                            // 更新附件信息
                            fileData.attFileId = res.data.respData.attFileId;
                            fileData.attachName = tempFile.name; // 文件名

                            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.mch_id) {
                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;
            }

            return true;
        },
        
        ecQuery() {
            // const storeValue = uni.getStorageSync('storeValue');
            // if (!storeValue || !storeValue.contractId) {
            //     uni.showToast({
            //         title: '请先提交申请',
            //         icon: 'none'
            //     });
            //     return;
            // }
            // const params = {
            //     contractId: storeValue.contractId
            // }
            request(apiArr.queryLedgerMer, "POST", {}).then(res => {
                if (res.respData.splitStatus === 'VALID') {
                    uni.showToast({
                        title: '审核通过',
                        icon: 'success'
                    });
                } else if (res.respData.contractStatus === 'INVALID') {
                    uni.showToast({
                        title: '审核未通过',
                        icon: 'none'
                    });
                }
            })
        },

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

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

            // 准备请求参数
            const submitData = {
                mch_id: this.formData.mch_id,
                merInnerNo: this.formData.merInnerNo,
                merCupNo: this.formData.merCupNo,
                contactMobile: this.formData.contactMobile,
                eleContractNo: this.formData.eleContractNo,
                attachments: []
            };

            // 只添加有attFileId的文件到attachments
            const validFiles = this.formData.fileData.filter(file => file.attFileId);
            if (validFiles.length > 0) {
                submitData.attachments = validFiles.map(file => ({
                    attachType: file.attType,
                    attachName: file.attachName,
                    attachStorePath: file.attFileId
                }));
            }

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

            request(apiArr.applyLedgerMer, "POST", submitData).then(res => {
                uni.hideLoading();
                uni.showToast({
                    title: '提交成功',
                    icon: 'success'
                });
                uni.setStorageSync('storeValue', { fz_apply_id: res.resp_data.ec_apply_id });
            }).catch(error => {
                uni.hideLoading();
                console.error('提交失败:', error);
                uni.showToast({
                    title: '提交失败',
                    icon: 'none'
                });
            });
        }
    }
}
</script>

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