<template>
	<uni-navbar-lite :showLeft="true" title="区域巡查"></uni-navbar-lite>
    <scroll-view class="container" scroll-y="true">
        <view class="info-card">
            <view class="info-item">
                <text class="info-label">地点名称</text>
                <text class="info-value">{{ deviceInfo.locationName ?? '' }}</text>
            </view>
            <!-- <view class="info-item">
                <text class="info-label">设备编号</text>
                <text class="info-value">{{ deviceInfo.machineryCode ?? '' }}</text>
            </view> -->
        </view>

        <!-- 检查项目概览 -->
        <view class="section">
            <view class="section-header">
                <text class="section-title">检查项目</text>
            </view>
            <view class="subjects-container">
                <view class="subjects-tags">
                    <text 
                        v-for="(subject, index) in subjectsList" 
                        :key="index" 
                        class="subject-tag"
                    >
                        {{ subject }}
                    </text>
                </view>
            </view>
        </view>

        <!-- 媒体上传区域 -->
        <view class="section">
            <view class="section-header">
                <text class="section-title">检查记录</text>
            </view>
            <view class="check-item-media">
                <!-- 图片上传区域 -->
                <view class="media-section">
                    <text class="media-title">上传图片</text>
                    <view class="upload-wrapper" v-if="currentOpType != 'view'">
                        <UploadImage
                            :limit="6"
                            :modelValue="photos"
                            businessType="deviceCheck"
                            @update:modelValue="(value: UTSArray<UploadResponse>) => updatePhotos(value)"
                        />
                    </view>
					<view class="image-container" v-else>
					    <image
					        v-for="(attachment, index) in attachmentList"
					        :key="index"
					        :src="attachment"
					        :alt="'附件图片' + (index + 1)"
					        class="attachment-image"
					        @click="previewImage(attachment)"
					    />
					</view>
                </view>
                
                <!-- 视频上传区域 -->
                <view class="media-section">
                    <text class="media-title">上传视频</text>
                    <view class="upload-wrapper" v-if="currentOpType != 'view'">
                        <UploadVideo
                            :limit="3"
                            :modelValue="videos"
                            businessType="deviceCheck"
                            @update:modelValue="(value: UTSArray<VideoItem>) => updateVideos(value)"
                        />
                    </view>
					<view class="image-container" v-else>
					    <video
					        v-for="(attachment, index) in videoList"
					        :key="index"
					        :src="attachment"
					        :alt="'附件视频' + (index + 1)"
					        class="attachment-image"
							:controls="true" 
					    />
					</view>
                </view>
            </view>
        </view>

 <!-- 状态选择 -->
        <view class="section">
            <view class="section-header">
                <text class="section-title">检查状态</text>
            </view>
            <view class="status-selector" @click="showStatusPicker" v-if="currentOpType!='view'">
                <view class="picker-display" >
                    <text v-if="deviceInfo.status != null" class="selected-value">{{ getStatusText(deviceInfo.status) }}</text>
                    <text v-else class="placeholder">请选择检查状态</text>
                    <text class="arrow">▼</text>
                </view>
            </view>
			<view v-else>
				<text v-if="deviceInfo.status != null" class="selected-value">{{ getStatusText(deviceInfo.status) }}</text>
			</view>
        </view>
        <!-- 备注 -->
        <view class="section">
            <view class="section-header">
                <text class="section-title">备注</text>
            </view>
            <view class="remark-container" v-if="currentOpType != 'view'">
                <textarea class="remark-textarea" v-model="deviceInfo.remark" placeholder="请输入备注信息" maxlength="500"></textarea>
            </view>
			<view v-else>
				<text class="section-title">{{deviceInfo.remark}}</text>
			</view>
        </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions" v-if="currentOpType != 'view'">
        <button class="action-btn submit-btn" @click="submitPatrol">完成巡查</button>
    </view>
</template>

<script setup lang="uts">
import { ref, computed} from 'vue'
import UploadImage from '../../components/upload-image/upload-image.uvue'
import UploadVideo from '../../components/upload-video/upload-video.uvue'
import type { UploadResponse } from '../../types/workbench'
import type { VideoItem } from '../../types/workbench'
import type { SysDictData } from '../../types/dict'
import { getDetailInfo, batchEditTaskDetail } from '../../api/task/detail.uts'
import { getDictDataByType } from '../../api/dict/index'
import { getBaseUrl } from '../../utils/request'

// 使用独立的类型定义，避免与device-check重复
type AreaPatrolTaskInfo = {
    detailId: Number | null
    taskId: Number | null
    machineryRecordId: Number | null
    machineryId: Number | null
    machineryTypeName: string | null
    machineryCode: string | null
    machineryName: string | null
    subjectId: Number | null
    subjectCode: string | null
    subjectName: string | null
    locationRecordId: Number | null
    locationId: Number | null
    locationName: string | null
    locationCode: string | null
    sourceType: string | null
    orderNum: Number | null
    status: string | null
    taskStatus: string | null
    imagesUrl: string | null
    videosUrl: string | null
    resultValue: string | null
    resultDesc: string | null
    remark: string | null
    attr1: string | null
    attr2: string | null
    attr3: Number | null
    attr4: Number | null
}

// 设备信息
const deviceInfo = ref<AreaPatrolTaskInfo>({
    detailId: null,
    taskId: null,
    machineryRecordId: null,
    machineryId: null,
    machineryTypeName: null,
    machineryCode: null,
    machineryName: null,
    subjectId: null,
    subjectCode: null,
    subjectName: null,
    locationRecordId: null,
    locationId: null,
    locationName: null,
    locationCode: null,
    sourceType: null,
    orderNum: null,
    status: null,
    taskStatus: null,
    imagesUrl: null,
    videosUrl: null,
    resultValue: null,
    resultDesc: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null
})

// 当前任务明细ID
const currentDetailId = ref<string>('')
const currentOpType = ref<string>('')

// 媒体文件
const photos = ref<UploadResponse[]>([])
const videos = ref<VideoItem[]>([])

// 字典数据
const subjectStatusDictList = ref<SysDictData[]>([])
const dictLoaded = ref<boolean>(false)

// 状态选项
type StatusOption = {
    label: string
    value: string
}

const statusOptions = ref<StatusOption[]>([])

// 获取检查项状态字典列表
const loadSubjectStatusDictList = async (): Promise<void> => {
    try {
        const result = await getDictDataByType('mes_subject_status')
        const resultObj = result as UTSJSONObject

        if (resultObj['code'] == 200) {
            const data = resultObj['data'] as any[]
            const dictData: SysDictData[] = []

            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    const item = data[i] as UTSJSONObject
                    const dictItem: SysDictData = {
                        dictValue: item['dictValue'] as string | null,
                        dictLabel: item['dictLabel'] as string | null,
                        dictCode: null,
                        dictSort: null,
                        dictType: null,
                        cssClass: null,
                        listClass: null,
                        isDefault: null,
                        status: null,
                        default: null,
                        createTime: null,
                        remark: null
                    }
                    dictData.push(dictItem)
                }
            }

            subjectStatusDictList.value = dictData
            dictLoaded.value = true
            
            // 更新状态选项
            const newOptions: StatusOption[] = []
            for (let i = 0; i < dictData.length; i++) {
                const dict = dictData[i]
                if (dict.dictValue != null && dict.dictLabel != null) {
                    newOptions.push({
                        label: dict.dictLabel,
                        value: dict.dictValue
                    })
                }
            }
            statusOptions.value = newOptions
        }
    } catch (e: any) {
        console.error('获取检查项状态字典失败:', e.message)
        dictLoaded.value = true
    }
}

// 获取状态文本
const getStatusText = (status: string | null): string => {
    if (status == null || status.length == 0) return ''
    if (dictLoaded.value != true) {
        return status
    }
    const dictItem = subjectStatusDictList.value.find((dict: SysDictData) => dict.dictValue == status)
    return dictItem != null && dictItem.dictLabel != null ? dictItem.dictLabel : status
}

// 显示状态选择器
const showStatusPicker = (): void => {
    // 显示选择器
    uni.showActionSheet({
        itemList: statusOptions.value.map(option => option.label),
        success: (res) => {
            if (res.tapIndex >= 0 && res.tapIndex < statusOptions.value.length) {
                const selectedOption = statusOptions.value[res.tapIndex]
                deviceInfo.value.status = selectedOption.value
            }
        }
    })
}

// 计算检查项目显示列表
const subjectsList = computed((): string[] => {
    if (deviceInfo.value.subjectName == null || deviceInfo.value.subjectName.length == 0) return ['暂无检查项目']
    return deviceInfo.value.subjectName.split(',').map(item => item.trim()).filter(item => item.length > 0)
})

// 更新图片
const updatePhotos = (value: UTSArray<UploadResponse>): void => {
    photos.value = value as UploadResponse[];
    // 同步更新imagesUrl字段
    if (value.length > 0) {
        const fileNames: string[] = [];
        for (let i = 0; i < value.length; i++) {
            fileNames.push(value[i].fileName);
        }
        deviceInfo.value.imagesUrl = fileNames.join(','); 
    } else {
        deviceInfo.value.imagesUrl = null;
    }
};

// 更新视频
const updateVideos = (value: UTSArray<VideoItem>): void => {
    videos.value = value as VideoItem[];
    // 同步更新videosUrl字段
    if (value.length > 0) {
        const fileNames: string[] = [];
        for (let i = 0; i < value.length; i++) {
            fileNames.push(value[i].fileName);
        }
        deviceInfo.value.videosUrl = fileNames.join(','); 
    } else {
        deviceInfo.value.videosUrl = null;
    }
}; 

// 加载设备检查任务明细数据
const loadDeviceDetail = async (): Promise<void> => {
    if (currentDetailId.value == null || currentDetailId.value.length == 0) {
        uni.showToast({
            title: '缺少任务明细ID参数',
            icon: 'none'
        })
        return
    }
    
    try {
        uni.showLoading({
            title: '加载中...'
        })
        
        const result = await getDetailInfo(currentDetailId.value)
        const resultObj = result as UTSJSONObject
        const code = resultObj['code'] as number
        
        if (code == 200) {
            const data = resultObj['data'] as UTSJSONObject
            
            // 转换设备信息
            const newDeviceInfo: AreaPatrolTaskInfo = {
                detailId: data['detailId'] != null ? (data['detailId'] as Number) : null,
                taskId: data['taskId'] != null ? (data['taskId'] as Number) : null,
                machineryRecordId: data['machineryRecordId'] != null ? (data['machineryRecordId'] as Number) : null,
                machineryId: data['machineryId'] != null ? (data['machineryId'] as Number) : null,
                machineryTypeName: data['machineryTypeName'] as string | null,
                machineryCode: data['machineryCode'] as string | null,
                machineryName: data['machineryName'] as string | null,
                subjectId: data['subjectId'] != null ? (data['subjectId'] as Number) : null,
                subjectCode: data['subjectCode'] as string | null,
                subjectName: data['subjectName'] as string | null,
                locationRecordId: data['locationRecordId'] != null ? (data['locationRecordId'] as Number) : null,
                locationId: data['locationId'] != null ? (data['locationId'] as Number) : null,
                locationName: data['locationName'] as string | null,
                locationCode: data['locationCode'] as string | null,
                sourceType: data['sourceType'] as string | null,
                orderNum: data['orderNum'] != null ? (data['orderNum'] as Number) : null,
                status: data['status'] as string | null,
                taskStatus: data['taskStatus'] as string | null,
                imagesUrl: data['imagesUrl'] as string | null,
                videosUrl: data['videosUrl'] as string | null,
                resultValue: data['resultValue'] as string | null,
                resultDesc: data['resultDesc'] as string | null,
                remark: data['remark'] as string | null,
                attr1: data['attr1'] as string | null,
                attr2: data['attr2'] as string | null,
                attr3: data['attr3'] != null ? (data['attr3'] as Number) : null,
                attr4: data['attr4'] != null ? (data['attr4'] as Number) : null
            }
            deviceInfo.value = newDeviceInfo
            
            uni.hideLoading()
        } else {
            const msg = resultObj['msg'] as string | null
            uni.hideLoading()
            uni.showToast({
                title: msg ?? '加载失败',
                icon: 'none'
            })
        }
    } catch (e: any) {
        uni.hideLoading()
        uni.showToast({
            title: e.message ?? '加载失败',
            icon: 'none'
        })
        console.error('加载设备检查任务明细失败:', e)
    }
}

// 提交巡查
const submitPatrol = (): void => {
    // 校验是否至少上传了图片或视频
    const hasMedia = (photos.value.length > 0) || (videos.value.length > 0);
    
    if (!hasMedia) {
        uni.showToast({
            title: '请至少上传一张图片或一个视频',
            icon: 'none'
        });
        return;
    }
    
    // 提交巡查结果
    const deviceNameStr = (deviceInfo.value.machineryName != null && deviceInfo.value.machineryName.length > 0) ? deviceInfo.value.machineryName : '';
    uni.showModal({
        title: '确认提交',
        //content: `确定提交区域巡查结果？\n设备：${deviceNameStr}`,
        success: (res) => {
            if (res.confirm) {
                // 构造提交数据
                const submitData: UTSJSONObject = {
                    'detailId': deviceInfo.value.detailId,
                    'taskId': deviceInfo.value.taskId,
                    'machineryRecordId': deviceInfo.value.machineryRecordId,
                    'machineryId': deviceInfo.value.machineryId,
                    'machineryTypeName': deviceInfo.value.machineryTypeName,
                    'machineryCode': deviceInfo.value.machineryCode,
                    'machineryName': deviceInfo.value.machineryName,
                    'subjectId': deviceInfo.value.subjectId,
                    'subjectCode': deviceInfo.value.subjectCode,
                    'subjectName': deviceInfo.value.subjectName,
                    'locationRecordId': deviceInfo.value.locationRecordId,
                    'locationId': deviceInfo.value.locationId,
                    'locationName': deviceInfo.value.locationName,
                    'locationCode': deviceInfo.value.locationCode,
                    'sourceType': deviceInfo.value.sourceType,
                    'orderNum': deviceInfo.value.orderNum,
                    //'status': deviceInfo.value.status,
					'status': deviceInfo.value.status != null ? deviceInfo.value.status : 'NORMAL',
                    'taskStatus': deviceInfo.value.taskStatus,
                    'imagesUrl': deviceInfo.value.imagesUrl,
                    'videosUrl': deviceInfo.value.videosUrl,
                    'resultValue': deviceInfo.value.resultValue,
                    'resultDesc': deviceInfo.value.resultDesc,
                    'remark': deviceInfo.value.remark,
                    'attr1': deviceInfo.value.attr1,
                    'attr2': deviceInfo.value.attr2,
                    'attr3': deviceInfo.value.attr3,
                    'attr4': deviceInfo.value.attr4
                } as UTSJSONObject;

                // 调用批量编辑接口
                uni.showLoading({
                    title: '提交中...'
                });

                batchEditTaskDetail(submitData)
                    .then((result: any) => {
                        const resultObj = result as UTSJSONObject;
                        const code = resultObj['code'] as number;
                        
                        uni.hideLoading();
                        
                        if (code == 200) {
                            uni.showToast({
                                title: '巡查提交成功！',
                                icon: 'success'
                            });

                            // 设置标记，通知上一个页面需要刷新数据
                            uni.setStorageSync('needRefresh', true);
                            // 返回上一页
                            setTimeout(() => {
                                uni.navigateBack();
                            }, 1500);
                        } else {
                            uni.hideLoading();
                            const msg = resultObj['msg'] as string | null;
                            uni.showToast({
                                title: msg ?? '提交失败',
                                icon: 'none'
                            });
                        }
                    })
                    .catch((error) => {
                        uni.hideLoading();
                        uni.showToast({
                            title: '提交失败',
                            icon: 'none'
                        });
                        console.error('提交巡查结果失败:', error);
                    });
            }
        }
    })
}

    // 计算附件列表
    const attachmentList = computed<string[]>(() => {
        if (deviceInfo.value.imagesUrl != null && deviceInfo.value.imagesUrl != '') {
            // 按逗号分割附件URL字符串，并加上基础URL
            const arr = deviceInfo.value.imagesUrl.split(',')
                .map((url: string) => {
                    const trimmedUrl = url.trim();
                    // 如果是相对路径，加上基础URL
                    if (trimmedUrl.startsWith('/')) {
                        return getBaseUrl() + trimmedUrl;
                    }
                    return trimmedUrl;
                })
                .filter((url: string) => url.length > 0);
            return arr;
        }
        return []
    })
	
	// 计算附件列表
	const videoList = computed<string[]>(() => {
	    if (deviceInfo.value.videosUrl != null && deviceInfo.value.videosUrl != '') {
	        // 按逗号分割附件URL字符串，并加上基础URL
	        const arr = deviceInfo.value.videosUrl.split(',')
	            .map((url: string) => {
	                const trimmedUrl = url.trim();
	                // 如果是相对路径，加上基础URL
	                if (trimmedUrl.startsWith('/')) {
	                    return getBaseUrl() + trimmedUrl;
	                }
	                return trimmedUrl;
	            })
	            .filter((url: string) => url.length > 0);
	        return arr;
	    }
	    return []
	})
	
	// 预览图片
	const previewImage = (url: string) => {
	    if (url == '') return
	
	    // 检查是否为图片文件
	    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
	    const isImage = imageExtensions.some(ext => url.toLowerCase().endsWith(ext))
	
	    if (isImage) {
	        // 如果是图片，使用uni.previewImage预览
	        uni.previewImage({
	            urls: [url],
	            current: 0
	        })
	    } else {
	        // 对于非图片文件，显示提示
	        uni.showToast({
	            title: '不支持预览此文件类型',
	            icon: 'none',
	            duration: 2000
	        })
	    }
	}

onLoad((options: any) => {
    const params = options as UTSJSONObject
    const detailId = params['detailId'] as string | null
	const opType = params.get('opType') as string | null
    
	if(opType != null){
		currentOpType.value = opType;
	}
    // 获取传递的任务明细ID
    if (detailId != null && detailId.length > 0) {
        currentDetailId.value = detailId
        // 并行加载字典数据和设备检查任务明细数据
        Promise.all([
            loadSubjectStatusDictList(),
            loadDeviceDetail()
        ]).catch(error => {
            console.error('加载数据失败:', error)
        })
    } else {
        uni.showToast({
            title: '缺少任务明细ID参数',
            icon: 'none'
        })
    }
})
</script>

<style lang="scss">
.container {
    flex: 1;
    background-color: #e8f0f9;
    padding: 20rpx;
    padding-bottom: 120rpx;
}

.info-card {
    background-color: #fff;
    padding: 30rpx;
    border-radius: 16rpx;
    margin: 12rpx 10rpx;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item {
    flex-direction: row;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
        border-bottom: none;
    }

    .info-label {
        width: 240rpx;
        font-size: 28rpx;
        color: #666666;
        white-space: nowrap;
    }

    .info-value {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
        text-align: right;
    }
}

.section {
    background-color: #ffffff;
    padding: 30rpx;
    border-radius: 16rpx;
    margin: 12rpx 10rpx;
}

.subjects-container {
    margin-top: 20rpx;
    padding: 20rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    border: 1rpx solid #e0e0e0;
}

.subjects-tags {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 15rpx;
}

.subject-tag {
    padding: 12rpx 20rpx;
    background-color: #ffffff;
    border: 1rpx solid #165dff;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #165dff;
    font-weight: 500;
}

.status-selector {
    margin-top: 20rpx;
}

.picker-display {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    min-height: 40rpx;
    padding: 12rpx 16rpx;
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    background-color: #f8f9fa;
}

.selected-value {
    font-size: 28rpx;
    color: #333333;
}

.placeholder {
    font-size: 28rpx;
    color: #999999;
}

.arrow {
    font-size: 24rpx;
    color: #999999;
    margin-left: 12rpx;
}

.check-item-media {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin: 15rpx 0;
}

.media-section {
	margin-bottom: 15rpx;
	.image-container {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start; // 或 space-around
		// justify-content: space-around; /* 自动分配间距，避免挤压 */
		align-items: center;
		padding: 0 3rpx;
		.attachment-image {
		    width: 280rpx; /* 一行显示两个图片，减去间距的一半 */
		    height: 280rpx;
			// padding: 3rpx;
			margin: 3px;
		}
	}
}

.media-title {
	display: block;
	font-size: 26rpx;
	color: #666;
	margin-bottom: 10rpx;
	font-weight: 500;
}

.upload-wrapper {
	margin-top: 10rpx;
}

.remark-container {
    margin-top: 20rpx;
}

.remark-textarea {
    width: 100%;
    min-height: 120rpx;
    padding: 20rpx;
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    background-color: #fff;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
}

.section-header {
    margin-bottom: 20rpx;
    padding-bottom: 15rpx;
    border-bottom: 1rpx solid #eee;
}

.section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.image {
	&-list {
		flex-direction: row;
		flex-wrap: wrap;
	}

	&-item {
		background-color: #f5f7fa;
		border-radius: 8rpx;
		position: relative;
		width: 160rpx !important;
		height: 160rpx !important;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	width: 160rpx !important;
	height: 160rpx !important;
	border-radius: 8rpx;

	&-delete {
		position: absolute;
		top: 2rpx;
		right: 2rpx;
		width: 44rpx;
		height: 44rpx;
		justify-content: center;
		align-items: center;
	}
}

.delete-icon {
	width: 32rpx;
	height: 32rpx;
}

.upload {
	&-box {
		background-color: #f5f7fa;
		border-radius: 8rpx;
		width: 160rpx !important;
		height: 160rpx !important;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		border: 2rpx dashed #d0d0d0;
		border-radius: 8rpx;
		justify-content: center;
		align-items: center;
	}

	&-icon {
		font-size: 60rpx;
		color: #999999;
		line-height: 60rpx;
		margin-bottom: 10rpx;
	}

	&-text {
		font-size: 24rpx;
		color: #999999;
	}
}

.video {
	&-list {
		flex-direction: row;
		flex-wrap: wrap;
	}

	&-item {
		background-color: #f5f7fa;
		border-radius: 8rpx;
		position: relative;
		width: 160rpx !important;
		height: 160rpx !important;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	width: 160rpx !important;
	height: 160rpx !important;
	border-radius: 8rpx;

	&-delete {
		position: absolute;
		top: 2rpx;
		right: 2rpx;
		width: 44rpx;
		height: 44rpx;
		justify-content: center;
		align-items: center;
	}
}

.bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    flex-direction: row;
    padding: 20rpx 30rpx;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
    flex: 1;
    padding: 12rpx;
    border: none;
    border-radius: 6rpx;
    font-size: 26rpx;
    font-weight: bold;
    margin: 0 10rpx;
    min-width: 120rpx;
}

.submit-btn {
    background-color: #165dff;
    color: #fff;
}
</style>