<template>
    <view class="page-itemOne">
        <u-row justify="space-between" customStyle="margin-bottom: 10px">
            <u-col span="3">
                <div class="page-itemOne-title">图片资料</div>
            </u-col>
            <u-col span="3.5">
                <u-button size="small" @click="copyAllImages"
                    style="border-radius: 20rpx;border-color: #007AFF;color: #007AFF;">保存全部图片</u-button>
            </u-col>
        </u-row>

        

        <!-- 聊天记录卡片 -->
        <view class="card_wrap">
            <view class="card-title">
                <text @click="chatRecordOrCallRecord = 'chatRecords'">聊天记录</text>
                <text style="margin: 0 10rpx;">|</text>
                <text @click="chatRecordOrCallRecord = 'callRecords'">通话记录</text>
            </view>
            <!-- 聊天记录卡片 -->
            <view class="image-upload-container" v-if="chatRecordOrCallRecord === 'chatRecords'">
                <view class="image-list">
                    <view class="image-item" v-for="(item, index) in chatRecordsUploadList"
                        :key="'chatRecords-' + index">
                        <pic-comp @needPreviewPic='previewImageChat' :src="item.fileUrl"></pic-comp>
                        <view class="delete-btn" @click="deleteImage(item)">×</view>
                    </view>
                    <view class="upload-btn" @click="uploadImage('chatRecords', currentReceipt.id)">
                        <u-icon name="plus" size="40" color="#999"></u-icon>
                    </view>
                </view>
            </view>
            <!-- 通话录音卡片 -->
            <view class="image-upload-container" v-if="chatRecordOrCallRecord === 'callRecords'">
                <view>

                    <sound-recorder v-for="item in soundRecordList" :key="item.fileName" :data="item"
                        @handleDelectThisSoundRecord='handleDelectThisSoundRecord'></sound-recorder>
                    <!-- <view class="add-btn" @click="addCallRecord">添加通话记录</view> -->

                </view>

            </view>
        </view>

        <!-- 实物图卡片 -->
        <view class="card_wrap">
            <view class="card-title">实物图</view>
            <view class="image-upload-container">
                <view class="image-list">
                    <view class="image-item" v-for="(item, index) in trueUploadList" :key="'truePic-' + index">
                        <pic-comp @needPreviewPic='previewImageTrue' :src="item.fileUrl"></pic-comp>
                        <view class="delete-btn" @click="deleteImage(item)">×</view>
                    </view>
                    <view class="upload-btn" @click="uploadImage('truePic', currentReceipt.id)">
                        <u-icon name="plus" size="40" color="#999"></u-icon>
                    </view>
                </view>
            </view>
        </view>
        

        <!-- 基本信息卡片 -->
        <view class="info-card">
            <view class="info-card-title">基本信息</view>
            <u-row class="info-row">
                <u-col span="6">
                    <view class="info-label">发单人</view>
                    <view class="info-value">{{ orderDetail.createNickName || '未填写' }}</view>
                </u-col>
                <u-col span="6">
                    <view class="info-label">型号</view>
                    <view class="info-value">{{ orderDetail.model || '未填写' }}</view>
                </u-col>
            </u-row>
            <u-row class="info-row">
                <u-col span="6">
                    <view class="info-label">上门时间</view>
                    <view class="info-value">{{ orderDetail.visitTime || '未填写' }}</view>
                </u-col>
                <u-col span="6">
                    <view class="info-label">地址</view>
                    <view class="info-value">{{ orderDetail.address || '未填写' }}</view>
                </u-col>
            </u-row>
        </view>

        <!-- 联系方式卡片 -->
        <view class="connect">
            <view class="connect-card phone-card" @click="handlePhoneClick">
                <u-icon name="phone" size="40" color="#07C160" style="margin-bottom: 10rpx;"></u-icon>
                <view class="connect-title">电话</view>
                <!-- 小红点 -->
                <view v-if="orderDetail.phone" class="red-dot"></view>
            </view>
            <view class="connect-card wechat-card" @click="handleWechatClick">
                <u-icon name="chat" size="40" color="#07C160" style="margin-bottom: 10rpx;"></u-icon>
                <view class="connect-title">微信</view>
                <!-- 小红点 -->
                <view v-if="orderDetail.wechat" class="red-dot"></view>
            </view>
        </view>

        <view class="space-block">

        </view>

        <u-button class='next-btn' @click="handleNextClick" type="primary" size="middle"
            style="border-radius: 20rpx;">下一步</u-button>

    </view>
</template>
<script>
import picComp from './picComp.vue'
import imgUploadAndDownLoad from '../mixin/imgUploadAndDownLoad.js'
import soundRecorder from '@/components/soundRecorder/soundRecorder.vue'

export default {
    mixins: [imgUploadAndDownLoad],
    props: {
        orderDetail: {
            type: Object,
            default: () => { },
        },
        orderId: {
            type: String,
            default: '',
        },
        currentReceipt: {
            type: Object,
            default: () => { },
        },
    },
    components: {
        picComp, soundRecorder
    },
    data() {
        return {
            //展示的图片列表
            trueUploadList: [],
            chatRecordsUploadList: [],
            // 待绑定的图片列表
            bindList: [],
            chatRecordOrCallRecord: 'chatRecords',
            soundRecordList: [],//录音记录
        }
    },
    watch: {
        // 监听 props 变化，触发请求
        orderDetail: {
            handler(newVal) {
                if (newVal) {
                    console.log('orderDetail 变化了', newVal);
                }
            }
        },
        currentReceipt: {
            handler(newVal) {
                console.log('currentReceipt 变化了', newVal);
                if (newVal) {
                    //刷新图片列表
                    setTimeout(() => {
                        this.getList('2', '1', newVal.id, this.orderDetail.itemBrand);
                        this.getList('2', '2', newVal.id, this.orderDetail.itemBrand);
                        this.getCallRecords();
                    }, 100)

                }
            }
        },
    },

    methods: {

        // 电话卡片点击事件
        handlePhoneClick() {
            console.log('电话卡片被点击', '电话号码:', this.orderDetail.phone)
            if (this.orderDetail.phone) {
                uni.makePhoneCall({
                    phoneNumber: this.orderDetail.phone,
                    success: () => {
                        this.$store.commit("call/SET_FORM", {
                            clueId: this.orderDetail.clueId,
                            type: "3",
                            callee: this.orderDetail.phone,
                        });
                        console.log('this.currentReceipt333', this.$store.state.call.form.callee)
                    },
                });
                //先暂时复制电话号码
                // uni.setClipboardData({
                //     data: this.orderDetail.phone,
                //     success: () => {
                //         uni.showToast({
                //             title: '电话号码已复制',
                //             icon: 'none'
                //         })
                //     }
                // })
            } else {
                uni.showToast({
                    title: '该订单暂时没有电话号码',
                    icon: 'none'
                })
            }
        },
        // 微信卡片点击事件
        handleWechatClick() {
            console.log('微信卡片被点击', '微信号:', this.orderDetail.wechat)
            if (this.orderDetail.wechat) {
                //复制微信号
                uni.setClipboardData({
                    data: this.orderDetail.wechat,
                    success: () => {
                        uni.showToast({
                            title: '微信号已复制',
                            icon: 'none'
                        })
                    }
                })
            } else {
                uni.showToast({
                    title: '该订单暂时没有微信号',
                    icon: 'none'
                })
            }
        },
        // 下一步
        handleNextClick() {
            // 校验表单
            // if (!this.form.truePic.length) {
            //     uni.showToast({
            //         title: '请上传实物图',
            //         icon: 'none'
            //     })
            //     return
            // }
            // if (!this.form.chatRecords.length) {
            //     uni.showToast({
            //         title: '请上传聊天记录',
            //         icon: 'none'
            //     })
            //     return
            // }
            this.$emit('handleNextClick', {
                nowPage: 'formOne',
                form: this.form,
            })
        },

        //一键复制
        copyAllImages() {
            // 合并所有图片
            const allImages = [...this.trueUploadList];
            //取出所有图的url
            const allUrls = allImages.map(item => item.fileUrl);
            if (allUrls.length > 0) {
                // 显示保存图片确认弹窗
                uni.showModal({
                    title: '保存图片',
                    content: `是否将 ${allUrls.length} 张图片保存到本地相册？`,
                    confirmText: '保存',
                    // cancelText: '仅复制链接',
                    success: (res) => {
                        if (res.confirm) {
                            // 用户选择保存图片
                            this.saveImagesToLocal(allUrls);
                        } else if (res.cancel) {
                            // 用户选择仅复制链接
                            this.copyImageUrls(allUrls);
                        }
                    }
                })
            } else {
                uni.showToast({
                    title: '没有图片可保存',
                    icon: 'none'
                })
            }
        },

        // 保存图片到本地相册
        async saveImagesToLocal(imageUrls) {
            try {
                uni.showLoading({
                    title: '正在保存图片...',
                    mask: true
                });

                const savedImages = [];
                const failedImages = [];

                // 逐个保存图片
                for (let i = 0; i < imageUrls.length; i++) {
                    const url = imageUrls[i];
                    try {
                        await this.saveSingleImage(url);
                        savedImages.push(url);
                    } catch (error) {
                        console.error(`保存图片失败: ${url}`, error);
                        failedImages.push(url);
                    }

                    // 更新进度
                    uni.showLoading({
                        title: `正在保存图片... (${i + 1}/${imageUrls.length})`,
                        mask: true
                    });
                }

                uni.hideLoading();

                // 显示结果
                let message = `成功保存 ${savedImages.length} 张图片`;
                if (failedImages.length > 0) {
                    message += `，${failedImages.length} 张保存失败`;
                }

                uni.showToast({
                    title: message,
                    icon: 'none',
                    duration: 3000
                });

                // 如果有失败的图片，也复制链接作为备选
                if (failedImages.length > 0) {
                    const allUrls = [...savedImages, ...failedImages];
                    this.copyImageUrls(allUrls);
                }

            } catch (error) {
                uni.hideLoading();
                console.error('保存图片过程中发生错误:', error);
                uni.showToast({
                    title: '保存图片失败',
                    icon: 'error'
                });
            }
        },

        // 保存单张图片
        saveSingleImage(url) {
            return new Promise((resolve, reject) => {
                // 先下载图片
                uni.downloadFile({
                    url: url,
                    success: (res) => {
                        if (res.statusCode === 200) {
                            // 保存到相册
                            uni.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: () => {
                                    console.log('图片保存成功:', url);
                                    resolve();
                                },
                                fail: (err) => {
                                    console.error('保存到相册失败:', err);
                                    // 如果是权限问题，尝试请求权限
                                    if (err.errMsg.includes('auth denied')) {
                                        uni.showModal({
                                            title: '权限不足',
                                            content: '需要访问相册权限来保存图片，是否去设置？',
                                            success: (modalRes) => {
                                                if (modalRes.confirm) {
                                                    // 打开设置页面
                                                    uni.openSetting({
                                                        success: (settingRes) => {
                                                            console.log('设置页面结果:', settingRes);
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                    reject(err);
                                }
                            });
                        } else {
                            reject(new Error('下载失败'));
                        }
                    },
                    fail: (err) => {
                        console.error('下载图片失败:', err);
                        reject(err);
                    }
                });
            });
        },

        // 复制图片链接
        copyImageUrls(urls) {
            uni.setClipboardData({
                data: JSON.stringify(urls),
                success: () => {
                    uni.showToast({
                        title: '图片链接已复制',
                        icon: 'none'
                    })
                }
            })
        },
        // 预览真实图片
        previewImageTrue(src) {
            const urlList = this.trueUploadList.map(item => item.fileUrl);

            uni.previewImage({
                urls: urlList,
                current: src
            })
        },
        previewImageChat(src) {
            const urlList = this.chatRecordsUploadList.map(item => item.fileUrl);

            uni.previewImage({
                urls: urlList,
                current: src
            })
        },
        //获取通话记录
        async getCallRecords() {
            console.log('这里是参数', this.currentReceipt.clueId);
            const { data } = await uni.$u.api.getCallClueFileByClueId({ clueId: this.currentReceipt.clueId });
            // const { data } = await uni.$u.api.getCallClueFileByClueId({ clueId: '1998278069905854466' });
            console.log('通话记录:', data);
            this.soundRecordList = data;
        },
        //删除录音
        handleDelectThisSoundRecord({ id }) {
            console.log('当前需要删除的录音的id是', id)
            uni.showModal({
                title: '提示',
                content: '是否确定删除?',
                confirmColor: '#6cc040',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            await uni.$u.api.deleteClueFile([id])
                            uni.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 2000
                            })
                            this.getData()
                        } catch (error) {
                            uni.showToast({
                                title: '删除失败',
                                icon: 'error',
                                duration: 2000
                            })
                        }
                    }
                }
            })
        },
    },

}
</script>
<style scoped lang="scss">
// 导入公共样式
@import './common.scss';

// 主样式
.page-itemOne {
    @extend .page-container;
}

.page-itemOne-title {
    @include font-styles($size: title, $weight: bold, $color: primary);
}

.page-itemOne-form {
    @include font-styles($size: tiny, $weight: semi-bold, $color: secondary);
    text-wrap: nowrap;
}

.image-upload-container {
    padding: map-get($sizes, padding-sm) map-get($sizes, padding);
}

.image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.image-item {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    box-sizing: border-box;
}

.delete-btn {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 40rpx;
    height: 40rpx;
    background-color: #ff4d4f;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    @include font-styles($size: tiny, $weight: bold);
    z-index: 10;
}

.upload-btn {
    width: 200rpx;
    height: 200rpx;
    border: 8rpx dashed #ddd;
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f9f9f9;
    box-sizing: border-box;
}

/* 基本信息卡片样式 */
.info-card {
    @include card;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    padding: map-get($sizes, padding-sm) map-get($sizes, padding);

    &:hover {
        @include shadow(2);
    }
}

.info-card-title {
    @include font-styles($size: title, $weight: bold, $color: primary);
    margin-bottom: 25rpx;
    padding-bottom: 15rpx;
    border-bottom: 1rpx solid map-get($colors, border);
}

.info-row {
    margin-bottom: 20rpx;
}

.info-label {
    @include font-styles($size: tiny, $weight: regular, $color: tertiary);
    margin-bottom: 8rpx;
}

.info-value {
    @include font-styles($size: small, $weight: regular, $color: secondary, $line-height: small);
    word-break: break-all;
}

/* 联系方式卡片样式 */
.connect {
    display: flex;
    justify-content: space-between;
    margin: 20rpx 0;
    gap: 20rpx;
}

.connect-card {
    flex: 1;
    @include card;
    padding: 10rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
    position: relative;

    &:hover {
        @include shadow(2);
    }
}

.connect-title {
    @include font-styles($size: tiny, $weight: regular, $color: tertiary);
    margin-bottom: 8rpx;
}

.connect-value {
    @include font-styles($size: small, $weight: medium, $color: secondary);
}

/* 小红点样式 */
.red-dot {
    position: absolute;
    top: 15rpx;
    right: 15rpx;
    width: 25rpx;
    height: 25rpx;
    background-color: #ff4d4f;
    border-radius: 50%;
    box-shadow: 0 0 4rpx rgba(255, 77, 79, 0.3);
}



.next-btn {
    position: fixed;
    bottom: 10rpx;
    left: 2.5%;
    width: 95%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    @include font-styles($size: medium, $weight: bold, $color: #fff);
    border-radius: 0rpx 0rpx 20rpx 20rpx;
}

.space-block {
    height: 80rpx;
}
</style>