<template>
    <view class="container">
        <!-- 医药代表备案 -->
        <view class="upload-section">
            <text class="section-title">医药代表备案信息</text>

            <view class="form-item">
                <input
                    class="record-input"
                    v-model="recordNumber"
                    placeholder="请输入备案号"
                />
            </view>

            <view class="image-grid">
                <view
                    class="image-box"
                    v-for="(item, index) in medicalFiles"
                    :key="'medical'+index"
                    @click="replaceImage('medicalFiles', index)"
                >
                    <image :src="item" class="preview-image" mode="aspectFill" />
                    <view class="delete-btn" @click.stop="removeImage('medicalFiles', index)">×</view>
                    <view class="replace-mask">点击替换</view>
                </view>
                <view
                    class="image-box"
                    v-if="medicalFiles.length < 4"
                    @click="uploadMedical"
                >
                    <view class="upload-placeholder">
                        <text>上传备案证书</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 其他资格证书 -->
        <view class="upload-section">
            <text class="section-title">其他资格证书</text>
            <view class="image-grid">
                <view
                    class="image-box"
                    v-for="(item, index) in otherFiles"
                    :key="'other'+index"
                    @click="replaceImage('otherFiles', index)"
                >
                    <image :src="item" class="preview-image" mode="aspectFill" />
                    <view class="delete-btn" @click.stop="removeImage('otherFiles', index)">×</view>
                    <view class="replace-mask">点击替换</view>
                </view>
                <view
                    class="image-box"
                    v-if="otherFiles.length < 4"
                    @click="uploadOther"
                >
                    <view class="upload-placeholder">
                        <text>上传其他证书</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 底部按钮 -->
        <view class="action-buttons">
            <button class="btn secondary" @click="handleBack">返回</button>
            <button class="btn primary" @click="handleSubmit">保存</button>
        </view>
    </view>
</template>

<script>
import { authApi } from "@/api/auth";
const baseURL = "http://127.0.0.1:9981";

export default {
    data() {
        return {
            recordNumber: '',
            medicalFiles: [],
            otherFiles: [],
            originalData: null,
            currentUploadType: null, // 新增：记录当前上传类型
            currentReplaceIndex: null // 新增：记录要替换的索引
        };
    },
    onLoad(options) {
        if (options.payload) {
            try {
                const payload = JSON.parse(decodeURIComponent(options.payload));
                if (payload.certificateInfo) {
                    this.originalData = payload.certificateInfo;
                    this.recordNumber = this.originalData.recordNumber || '';
                    this.medicalFiles = (this.originalData.medicalFiles || []).map(url =>
                        url.startsWith('http') ? url : `${baseURL}${url}`
                    );
                    this.otherFiles = (this.originalData.otherFiles || []).map(url =>
                        url.startsWith('http') ? url : `${baseURL}${url}`
                    );
                }
            } catch (e) {
                console.error('参数解析失败', e);
            }
        }
    },
    methods: {
        validate() {
            if (!this.recordNumber.trim()) {
                uni.showToast({ title: '备案号不能为空', icon: 'none' });
                return false;
            }
            if (this.medicalFiles.length < 1) {
                uni.showToast({ title: '请上传至少一个备案证书', icon: 'none' });
                return false;
            }
            return true;
        },

        // 替换图片
        replaceImage(type, index) {
            this.currentUploadType = type;
            this.currentReplaceIndex = index;
            this.chooseImage(1);
        },

        uploadMedical() {
            this.currentUploadType = 'medicalFiles';
            this.chooseImage(4 - this.medicalFiles.length);
        },

        uploadOther() {
            this.currentUploadType = 'otherFiles';
            this.chooseImage(4 - this.otherFiles.length);
        },

        async chooseImage(maxCount = 1) {
            try {
                const res = await uni.chooseImage({
                    count: maxCount,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera']
                });

                const uploadResults = await Promise.all(
                    res.tempFilePaths.map(file => this.uploadFile(file))
                );

                const successUrls = uploadResults
                    .filter(r => r.success)
                    .map(r => r.url);

                if (successUrls.length > 0) {
                    console.log('替换模式')

                    // 替换模式
                    if (this.currentReplaceIndex !== null) {
                        this[this.currentUploadType].splice(
                            this.currentReplaceIndex,
                            1,
                            ...successUrls
                        );
                        this.currentReplaceIndex = null;
                    }
                    // 新增模式
                    else {
                        this[this.currentUploadType] = [
                            ...this[this.currentUploadType],
                            ...successUrls
                        ];


                        console.log('currentUploadType',this.currentUploadType)
                        console.log('this[this.currentUploadType]',this[this.currentUploadType])
                    }
                }
            } catch (error) {
                console.log('取消选择或上传失败', error);
            } finally {
                this.currentUploadType = null;
            }
        },

        uploadFile(filePath) {
            return new Promise((resolve) => {
                uni.showLoading({ title: '上传中...', mask: true });
                uni.uploadFile({
                    url: authApi.fileUpload(),
                    filePath,
                    name: 'file',
                    success: (res) => {
                        if (res.statusCode === 200) {
                            const data = JSON.parse(res.data);
                            resolve({ success: true, url: data.data });
                        } else {
                            resolve({ success: false });
                        }
                    },
                    fail: () => resolve({ success: false }),
                    complete: () => uni.hideLoading()
                });
            });
        },

        removeImage(type, index) {
            this[type].splice(index, 1);
        },

        async handleSubmit() {
            if (!this.validate()) return;

            // 确保使用最新数据
            const submitData = {
                ...(this.originalData || {}),
                recordNumber: this.recordNumber,
                medicalFiles: this.medicalFiles,
                otherFiles: this.otherFiles,
            };

            console.log('submitData',submitData)

            try {
                const res = await authApi.checkCertificateApi(submitData);
                if (res.code === 0) {
                    uni.showToast({ title: '保存成功' });
                    setTimeout(() => uni.navigateBack(), 1500);
                } else {
                    uni.showToast({ title: res.msg || '操作失败', icon: 'none' });
                }
            } catch (error) {
                uni.showToast({ title: '请求失败，请重试', icon: 'none' });
            }
        },

        handleBack() {
            uni.navigateBack();
        }
    }
};
</script>

<style lang="scss" scoped>
/* 完全复用身份证上传样式 */
.container {
  padding: 32rpx;
  background: #fff;
  min-height: 100vh;
}

.upload-section {
  margin-bottom: 48rpx;

  .section-title {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
    font-weight: 500;
  }
}

.form-item {
  margin: 0 0 24rpx;

  .record-input {
    //width: 100%;
    height: 80rpx;
    border: 1rpx solid #eee;
    border-radius: 8rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    color: #333;

    &::placeholder {
      color: #999;
    }
  }
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
}

.image-box {
  aspect-ratio: 3/2;
  background: #f5f5f5;
  border-radius: 12rpx;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
  }

  .upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #999;
    font-size: 28rpx;
  }
}

.action-buttons {
  position: fixed;
  bottom: 48rpx;
  left: 32rpx;
  right: 32rpx;
  display: flex;
  gap: 24rpx;

  .btn {
    flex: 1;
    height: 96rpx;
    line-height: 96rpx;
    border-radius: 48rpx;
    font-size: 32rpx;

    &.secondary {
      background: #f5f5f5;
      color: #666;
    }

    &.primary {
      background: #007aff;
      color: #fff;
    }
  }
}
</style>
