<template>
    <view class="anomaly-container">
        <!-- 内容区域 -->
        <scroll-view scroll-y class="anomaly-scroll">

            <!-- 异常类型 -->
            <view class="ano-card">
                <view class="ano-section-title">
                    <view class="ano-title-bar"></view>
                    <text class="ano-title-text">异常类型</text>
                </view>
                <view class="ano-type-row" @click="openTypeSheet">
                    <text class="ano-type-val" :class="{ 'placeholder': !selectedType }">
                        {{ selectedType || '请选择异常类型' }}
                    </text>
                    <image class="ano-right-arrow" src="/static/icons/right_arrow_orange.svg"></image>
                </view>
            </view>

            <!-- 异常描述 -->
            <view class="ano-card">
                <view class="ano-section-title">
                    <view class="ano-title-bar"></view>
                    <text class="ano-title-text">异常描述</text>
                </view>
                <textarea
                    class="ano-textarea"
                    v-model="anomalyDesc"
                    placeholder="请详细描述现场异常情况..."
                    placeholder-style="color:#ccc; font-size:28rpx;"
                    maxlength="500"
                ></textarea>
            </view>

            <!-- 现场照片 -->
            <view class="ano-card">
                <view class="ano-section-title">
                    <view class="ano-title-bar"></view>
                    <text class="ano-title-text">现场照片 (必填，最多6张)</text>
                </view>
                <view class="ano-photo-grid">
                    <!-- 已上传图片 -->
                    <view class="ano-photo-item" v-for="(img, idx) in photoList" :key="idx">
                        <image class="ano-photo-preview" :src="img.url || img.localPath || img" mode="aspectFill"></image>
                        <view class="ano-photo-del" @click="removePhoto(idx)">×</view>
                    </view>
                    <!-- 添加按钮 -->
                    <view class="ano-photo-add" @click="choosePhoto" v-if="photoList.length < 6">
                        <image class="ano-add-icon" src="/static/icons/camera_grey.svg"></image>
                        <text class="ano-add-text">上传</text>
                    </view>
                </view>
            </view>

            <!-- 底部留空供按钮 -->
            <view style="height: 160rpx;"></view>
        </scroll-view>

        <!-- 底部提交按钮 -->
        <view class="ano-footer">
            <button class="ano-submit-btn" @click="submitAnomaly">提交上报</button>
        </view>

        <!-- 异常类型选择器 -->
        <view class="ano-sheet-mask" v-if="showTypeSheet" @click="closeTypeSheet">
            <view class="ano-sheet" @click.stop>
                <text class="ano-sheet-title">选择异常类型</text>
                <scroll-view scroll-y class="ano-sheet-list">
                    <view
                        class="ano-sheet-item"
                        v-for="(type, idx) in anomalyTypes"
                        :key="idx"
                        @click="selectType(type)"
                    >
                        <text :class="['ano-sheet-item-text', { 'selected': selectedTypeValue === type.value }]">{{ type.label }}</text>
                        <image
                            v-if="selectedTypeValue === type.value"
                            class="ano-check-icon"
                            src="/static/icons/right_arrow_orange.svg"
                        ></image>
                    </view>
                </scroll-view>
                <view class="ano-sheet-cancel" @click="closeTypeSheet">取消</view>
            </view>
        </view>
    </view>
</template>

<script>
import { getDictDataByType } from '@/api/system/dict'
import { uploadFile } from '@/api/fulfiller/app'
import { uploadAnamaly } from '@/api/fulfiller/anamaly'

export default {
    data() {
        return {
            orderId: '',
            // 已选异常类型（dictValue）
            selectedTypeValue: '',
            // 已选异常类型标签（dictLabel，用于显示）
            selectedTypeLabel: '',
            // 异常描述
            anomalyDesc: '',
            // 照片列表（含 url 和 ossId）
            photoList: [],
            // 是否显示类型选择器
            showTypeSheet: false,
            // 异常类型字典列表（从后端获取）
            anomalyTypes: []
        };
    },
    onLoad(options) {
        if (options.orderId) {
            this.orderId = options.orderId
        }
        this.loadAnomalyTypes()
    },
    computed: {
        // 当前选中的类型显示文本
        selectedType() {
            return this.selectedTypeLabel || ''
        }
    },
    methods: {
        /**
         * 加载异常类型字典数据
         */
        async loadAnomalyTypes() {
            try {
                const res = await getDictDataByType('flf_anamaly_type')
                if (res.data && Array.isArray(res.data)) {
                    this.anomalyTypes = res.data.map(item => ({
                        label: item.dictLabel,
                        value: item.dictValue,
                        dictCode: item.dictCode
                    }))
                    console.log('异常类型字典:', this.anomalyTypes)
                }
            } catch (err) {
                console.error('获取异常类型字典失败:', err)
                uni.showToast({ title: err.message || err.msg || '获取异常类型失败', icon: 'none' });
            }
        },
        // 打开类型选择器
        openTypeSheet() {
            this.showTypeSheet = true;
        },
        // 关闭类型选择器
        closeTypeSheet() {
            this.showTypeSheet = false;
        },
        // 选择异常类型
        selectType(type) {
            this.selectedTypeValue = type.value;
            this.selectedTypeLabel = type.label;
            this.closeTypeSheet();
        },
        // 选择照片并上传
        choosePhoto() {
            uni.chooseImage({
                count: 6 - this.photoList.length,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: async (res) => {
                    uni.showLoading({ title: '上传中...' });
                    try {
                        for (const filePath of res.tempFilePaths) {
                            const uploadRes = await uploadFile(filePath);
                            if (uploadRes.code === 200) {
                                this.photoList.push({
                                    url: uploadRes.data.url,
                                    ossId: uploadRes.data.ossId,
                                    localPath: filePath
                                });
                            }
                        }
                        uni.hideLoading();
                    } catch (err) {
                        uni.hideLoading();
                        console.error('上传失败:', err);
                        uni.showToast({ title: err.message || err.msg || '上传失败', icon: 'none' });
                    }
                }
            });
        },
        // 删除照片
        removePhoto(idx) {
            this.photoList.splice(idx, 1);
        },
        // 提交上报
        async submitAnomaly() {
            if (!this.selectedTypeValue) {
                uni.showToast({ title: '请选择异常类型', icon: 'none' });
                return;
            }
            if (this.photoList.length === 0) {
                uni.showToast({ title: '请上传现场照片', icon: 'none' });
                return;
            }
            const data = {
                orderId: this.orderId,
                type: this.selectedTypeValue,
                content: this.anomalyDesc,
                photos: this.photoList.map(p => p.ossId)
            }
            try {
                uni.showLoading({ title: '提交中...' });
                await uploadAnamaly(data);
                uni.hideLoading();
                uni.showToast({ title: '上报成功', icon: 'success' });
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            } catch (err) {
                uni.hideLoading();
                console.error('异常上报失败:', err);
                uni.showToast({ title: err.message || err.msg || '提交失败', icon: 'none' });
            }
        }
    }
};
</script>

<style>
/* 页面背景 */
.anomaly-container {
    min-height: 100vh;
    background-color: #F7F8FA;
    display: flex;
    flex-direction: column;
}

.anomaly-scroll {
    flex: 1;
    padding: 20rpx 30rpx 0;
    box-sizing: border-box;
}

/* 内容卡片 */
.ano-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

/* 节标题 */
.ano-section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
}

.ano-title-bar {
    width: 6rpx;
    height: 30rpx;
    background-color: #FF9800;
    border-radius: 3rpx;
    margin-right: 12rpx;
}

.ano-title-text {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
}

/* 异常类型行 */
.ano-type-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10rpx 0;
}

.ano-type-val {
    font-size: 28rpx;
    color: #333;
    flex: 1;
}

.ano-type-val.placeholder {
    color: #ccc;
}

.ano-right-arrow {
    width: 20rpx;
    height: 20rpx;
}

/* 描述文本框 */
.ano-textarea {
    width: 100%;
    min-height: 200rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    background-color: #FAFAFA;
    border-radius: 10rpx;
    padding: 20rpx;
    box-sizing: border-box;
}

/* 照片网格 */
.ano-photo-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
}

.ano-photo-item {
    width: 150rpx;
    height: 150rpx;
    border-radius: 12rpx;
    position: relative;
    overflow: hidden;
}

.ano-photo-preview {
    width: 100%;
    height: 100%;
}

.ano-photo-del {
    position: absolute;
    top: 4rpx;
    right: 4rpx;
    width: 36rpx;
    height: 36rpx;
    line-height: 32rpx;
    text-align: center;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 50%;
    font-size: 28rpx;
}

.ano-photo-add {
    width: 150rpx;
    height: 150rpx;
    border: 2rpx dashed #E0E0E0;
    border-radius: 12rpx;
    background-color: #FAFAFA;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.ano-add-icon {
    width: 50rpx;
    height: 50rpx;
    margin-bottom: 10rpx;
    opacity: 0.5;
}

.ano-add-text {
    font-size: 24rpx;
    color: #999;
}

/* 底部提交 */
.ano-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    padding: 20rpx 40rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
    z-index: 10;
}

.ano-submit-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background: linear-gradient(90deg, #FF9800 0%, #FF5722 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 45rpx;
    border: none;
}

.ano-submit-btn::after {
    border: none;
}

/* 异常类型选择器 */
.ano-sheet-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
    display: flex;
    align-items: flex-end;
}

.ano-sheet {
    width: 100%;
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
}

.ano-sheet-title {
    display: block;
    text-align: center;
    font-size: 28rpx;
    color: #999;
    padding: 30rpx 0 20rpx;
    border-bottom: 1px solid #f5f5f5;
}

.ano-sheet-list {
    max-height: 60vh;
}

.ano-sheet-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 40rpx;
    border-bottom: 1px solid #f9f9f9;
}

.ano-sheet-item-text {
    font-size: 32rpx;
    color: #333;
}

.ano-sheet-item-text.selected {
    color: #FF9800;
    font-weight: bold;
}

.ano-check-icon {
    width: 20rpx;
    height: 20rpx;
}

.ano-sheet-cancel {
    text-align: center;
    font-size: 32rpx;
    color: #999;
    padding: 30rpx 0;
    border-top: 16rpx solid #F7F8FA;
}
</style>
