<template>
    <!-- 照片统计一级页面 -->
    <view class="comprehensive-query" :style="{ paddingTop: safeAreaInsets?.top + 44 + 'px' }">
        <NavBarModal :navBarTitle="`照片统计`" />

        <!-- 筛选框 -->
        <view class="filter-box">
            <up-input placeholder="输入标题" v-model="outerKeyWord" clearable>
                <template #prefix>
                    <up-icon name="search" size="24" @tap="onSearchPhoto" />
                </template>

                <template #suffix>
                    <text class="search-text" @tap="onHandleSeniorSearch">高级筛选</text>
                </template>
            </up-input>
        </view>

        <view class="photo-container">
            <PhotoTotal :totalCount="imgCount?.totalNum" @HandleViewImgTotal="HandleViewImgTotal" />
            <PhotoClass
                :imgCount="imgCount"
                @handleGetImgListByImgType="handleGetImgListByImgType"
            />
            <PhotoRecent
                :imgList="imgList"
                @handleMyCollect="handleMyCollect"
                @handleLastUpload="handleLastUpload"
                @handleGetImgList="handleGetImgList"
            />
        </view>

        <view class="loading-text">
            {{ finish ? '没有更多数据了~' : '正在加载...' }}
        </view>
    </view>

    <up-back-top :scroll-top="scrollTop"></up-back-top>

    <!-- 高级筛选框 -->
    <up-popup
        mode="right"
        safeAreaInsetTop
        :show="rightPopupShow"
        @close="rightPopupShow = !rightPopupShow"
    >
        <view class="senior-popup">
            <up-list>
                <view class="senior-title">
                    <up-icon name="pushpin-fill" color="#333" size="24" />
                    <text>高级筛选</text>
                </view>

                <up-form
                    labelWidth="100"
                    labelAlign="center"
                    labelPosition="left"
                    ref="searchFormRef"
                    style="padding-right: 20rpx"
                    :style="{ paddingBottom: safeAreaInsets?.top + 50 + 'px' }"
                >
                    <TitleTipModal :TitleTip="`通用信息查询`" />
                    <up-form-item label="搜索查询">
                        <up-input placeholder="请输入" v-model="innerKeyWord" clearable />
                    </up-form-item>
                    <up-form-item prop="startTime" label="开始日期">
                        <up-input placeholder="请选择" v-model="queryParams.startTime" readonly>
                            <template #prefix>
                                <up-icon name="calendar" size="16" @tap="onSelectDate(1)" />
                            </template>
                        </up-input>
                    </up-form-item>
                    <up-form-item prop="endTime" label="结束日期">
                        <up-input placeholder="请选择" v-model="queryParams.endTime" readonly>
                            <template #prefix>
                                <up-icon size="16" name="calendar" @tap="onSelectDate(2)" />
                            </template>
                        </up-input>
                    </up-form-item>
                    <up-form-item prop="proName" label="工程">
                        <up-input
                            readonly
                            clearable
                            placeholder="请选择工程名称"
                            v-model="queryParams.proName"
                        >
                            <template #suffix>
                                <up-icon name="arrow-down" size="16" @tap="onSelectProject" />
                            </template>
                        </up-input>
                    </up-form-item>
                    <up-form-item prop="majorName" label="专业">
                        <up-input
                            readonly
                            clearable
                            placeholder="请选择专业"
                            v-model="queryParams.majorName"
                        >
                            <template #suffix>
                                <up-icon name="arrow-down" size="16" @tap="onSelectMajor" />
                            </template>
                        </up-input>
                    </up-form-item>
                    <up-form-item prop="gxName" label="工序">
                        <up-input
                            readonly
                            clearable
                            placeholder="请选择工序"
                            v-model="queryParams.gxName"
                        >
                            <template #suffix>
                                <up-icon name="arrow-down" size="16" @tap="onSelectProcedure" />
                            </template>
                        </up-input>
                    </up-form-item>
                    <TitleTipModal :TitleTip="`安全违章照片`" />
                    <up-form-item prop="projectName" label="类型">
                        <up-checkbox-group placement="row" v-model="queryParams.photoType_1">
                            <up-checkbox label="违章照片" name="1" />
                            <up-checkbox label="整改照片" name="2" />
                        </up-checkbox-group>
                    </up-form-item>
                    <up-form-item prop="vioPlace" label="违章地点">
                        <up-input placeholder="请输入" v-model="queryParams.vioPlace" />
                    </up-form-item>
                    <up-form-item prop="vioDesc" label="违章描述">
                        <up-input placeholder="请输入" v-model="queryParams.vioDesc" />
                    </up-form-item>
                    <up-form-item prop="rectDesc" label="整改说明">
                        <up-input placeholder="请输入" v-model="queryParams.rectDesc" />
                    </up-form-item>
                    <TitleTipModal :TitleTip="`质量检查照片`" />
                    <up-form-item prop="projectName" label="类型">
                        <up-checkbox-group placement="row" v-model="queryParams.photoType_2">
                            <up-checkbox label="缺陷照片" name="3" />
                            <up-checkbox label="整改照片" name="4" />
                        </up-checkbox-group>
                    </up-form-item>
                    <up-form-item prop="projectName" label="检查地点">
                        <up-input placeholder="请输入" v-model="queryParams.checkPlace2" />
                    </up-form-item>
                    <up-form-item prop="projectName" label="检查描述">
                        <up-input placeholder="请输入" v-model="queryParams.checkDesc2" />
                    </up-form-item>
                    <up-form-item prop="projectName" label="整改说明">
                        <up-input placeholder="请输入" v-model="queryParams.rectDesc2" />
                    </up-form-item>
                    <TitleTipModal :TitleTip="`安全措施落实照片`" />
                    <up-form-item prop="projectName" label="检查地点">
                        <up-input placeholder="请输入" v-model="queryParams.checkDesc3" />
                    </up-form-item>
                    <up-form-item prop="projectName" label="检查描述">
                        <up-input placeholder="请输入" v-model="queryParams.rectDesc3" />
                    </up-form-item>
                    <TitleTipModal :TitleTip="`协调照片`" />
                    <up-form-item prop="projectName" label="类型">
                        <up-checkbox-group placement="row" v-model="queryParams.photoType_3">
                            <up-checkbox label="建设前" name="6" />
                            <up-checkbox label="建设中" name="7" />
                            <up-checkbox label="恢复后" name="8" />
                        </up-checkbox-group>
                    </up-form-item>
                    <up-form-item prop="buildPlace" label="建设地点">
                        <up-input placeholder="请输入" v-model="queryParams.buildPlace" />
                    </up-form-item>
                    <TitleTipModal :TitleTip="`重要事项及宣传照片`" />
                    <up-form-item prop="title" label="标题">
                        <up-input v-model="queryParams.title" placeholder="请输入" />
                    </up-form-item>
                </up-form>
            </up-list>

            <!-- 按钮组 -->
            <view class="btns">
                <view>
                    <view>
                        <up-button
                            size="small"
                            type="primary"
                            icon="search"
                            text="查询"
                            @tap="onHandleSearch"
                        />
                    </view>
                    <view style="margin-left: 18rpx">
                        <up-button size="small" icon="reload" text="重置" @tap="onHandleReset" />
                    </view>
                </view>
            </view>
        </view>
    </up-popup>

    <!-- 年月日选择器 -->
    <up-datetime-picker
        mode="date"
        :show="dateShow"
        v-model="dateValue"
        :formatter="formatter"
        @confirm="onConfirmDate"
        @cancel="dateShow = !dateShow"
    />

    <!-- 工程选择器 -->
    <up-picker
        keyName="name"
        :show="projectShow"
        :columns="projectList"
        @confirm="onConfirmProject"
        @cancel="projectShow = !projectShow"
    />
    <!-- 专业选择器 -->
    <up-picker
        keyName="name"
        :show="majorShow"
        :columns="majorList"
        @confirm="onConfirmMajor"
        @cancel="majorShow = !majorShow"
    />
    <!-- 工序选择器 -->
    <up-picker
        keyName="name"
        :show="procedureShow"
        :columns="procedureList"
        @confirm="onConfirmProcedure"
        @cancel="procedureShow = !procedureShow"
    />
</template>

<script setup>
import NavBarModal from '@/components/NavBarModal/index'
import TitleTipModal from '@/components/TitleTipModal/index'
import PhotoTotal from './components/photo-total.vue'
import PhotoClass from './components/photo-class'
import PhotoRecent from './components/photo-recent'
import { useMemberStore } from '@/stores'
import { reactive, ref, computed, onMounted } from 'vue'
import { getProcedureApi } from '@/services/common.js'
import { useCommon } from '@/hooks/useCommon.js'
import { debounce } from 'lodash-es' // 引入防抖函数
import { getClassCountApi, getImgListApi } from '@/services/comprehensiveQuery.js'
import { onLoad, onReachBottom, onPageScroll } from '@dcloudio/uni-app'

const { getProjectList, getMajorList } = useCommon()
const { safeAreaInsets } = uni.getSystemInfoSync()
const memberStore = useMemberStore()
const token = memberStore?.token
const baseURL = import.meta.env.VITE_API_BASE_URL // 获取当前的url地址
const scrollTop = ref(0)
const searchFormRef = ref(null)
const outerKeyWord = ref('')
const innerKeyWord = ref('')
const rightPopupShow = ref(false)
const total = ref(0)
const dateShow = ref(false)
const dateValue = ref(Date.now())
const dateType = ref(1)
const projectShow = ref(false)
const majorShow = ref(false)
const procedureShow = ref(false)

const projectList = reactive([])
const majorList = reactive([])
const procedureList = reactive([])

// 数量数据源
const imgCount = reactive({
    totalNum: 0, //总照片数
    safetyVioNum: 0, // 安全违章
    safetyMeasNum: 0, // 安全措施落实
    qualityInsNum: 0, // 质量检查
    coordinatedPhotoNum: 0, // 协调照片
    importIssuesAndPublicityNum: 0, // 重要事项及宣传类
})

// 图片列表数据源
const imgList = ref([])

// 定义查询条件
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    queryType: '2', // 类型 1. 我的收藏 2. 最近上传
    searchType: '', // 1.标题查询 2.照片分类查询 3.高级筛选查询
    uploadType: '', // 图片类型
    keyWord: '', // 标题
    proId: '', // 工程
    proName: '', // 工程名称
    majorId: '', // 专业id
    majorName: '', // 专业名称
    gxId: '', // 工序id
    gxName: '', // 工序名称
    startTime: '', // 开始日期
    endTime: '', // 结束日期
    vioPlace: '', // 违章地点
    vioDesc: '', // 违章描述
    rectDesc: '', // 整改说明
    checkPlace2: '', // 检查地点
    checkDesc2: '', // 检查描述
    rectDesc2: '', // 整改说明
    checkDesc3: '', // 检查地点
    rectDesc3: '', // 检查描述
    buildPlace: '', // 建设地点
    title: '',
    photoType: [],
    photoType_1: [],
    photoType_2: [],
    photoType_3: [],
})

// 输入框左侧搜索图标点击
const onSearchPhoto = () => {
    // console.log('onSearchPhoto')
    queryParams.value.uploadType = ''
    queryParams.value.searchType = 1
    queryParams.value.keyWord = outerKeyWord.value
    getImgListData(true)
}

// 高级搜索
const onHandleSeniorSearch = () => {
    rightPopupShow.value = true
}

// 查询
const onHandleSearch = () => {
    queryParams.value.searchType = 3
    queryParams.value.keyWord = innerKeyWord.value
    getImgListData(true)
    rightPopupShow.value = false
    resetForm()
}

// 重置
const onHandleReset = () => {
    // rightPopupShow.value = false
    resetForm()
}

// 滚动触底事件
onReachBottom(
    debounce(() => {
        if (imgList.value.length < total.value) {
            queryParams.value.pageNum++
            getImgListData(false)
        }
    }, 1000),
)

// 监听滚动事件 显示返回顶部小图标
onPageScroll((e) => {
    scrollTop.value = e.scrollTop
})

// 获取照片分类
const getClassCountData = async () => {
    const res = await getClassCountApi({})
    console.log(
        '%c🔍 获取照片分类出参 %c',
        'background: linear-gradient(90deg, #FF6B6B, #4ECDC4); color: white; padding: 5px 10px; border-radius: 5px; font-weight: bold;',
        '',
        res,
    )

    if (res.code === 200) {
        Object.assign(imgCount, res.data)
    } else {
        uni.$u.toast(res.msg)
    }
}
getClassCountData()

// 获取照片列表
const getImgListData = async (isTap = false) => {
    try {
        queryParams.value.photoType = [
            ...queryParams.value.photoType_1,
            ...queryParams.value.photoType_2,
            ...queryParams.value.photoType_3,
        ]

        const {
            pageNum,
            pageSize,
            queryType, // 类型 1. 我的收藏 2. 最近上传
            searchType, // 1.标题查询 2.照片分类查询 3.高级筛选查询
            uploadType, // 图片类型
            keyWord, // 标题
            proId, // 工程
            majorId, // 专业id
            gxId, // 工序id
            startTime, // 开始日期
            endTime, // 结束日期
            vioPlace, // 违章地点
            vioDesc, // 违章描述
            rectDesc, // 整改说明
            checkPlace2, // 检查地点
            checkDesc2, // 检查描述
            rectDesc2, // 整改说明
            checkDesc3, // 检查地点
            rectDesc3, // 检查描述
            buildPlace, // 建设地点
            title,
            photoType,
        } = queryParams.value

        const queryParamsNew = {
            pageNum,
            pageSize,
            queryType, // 类型 1. 我的收藏 2. 最近上传
            searchType, // 1.标题查询 2.照片分类查询 3.高级筛选查询
            uploadType, // 图片类型
            keyWord, // 标题
            proId, // 工程
            majorId, // 专业id
            gxId, // 工序id
            startTime, // 开始日期
            endTime, // 结束日期
            vioPlace, // 违章地点
            vioDesc, // 违章描述
            rectDesc, // 整改说明
            checkPlace2, // 检查地点
            checkDesc2, // 检查描述
            rectDesc2, // 整改说明
            checkDesc3, // 检查地点
            rectDesc3, // 检查描述
            buildPlace, // 建设地点
            title,
            photoType,
        }
        console.log(
            '%c🔍 获取照片列表入参 %c',
            'background: linear-gradient(90deg, #FF6B6B, #4ECDC4); color: white; padding: 5px 10px; border-radius: 5px; font-weight: bold;',
            '',
            queryParamsNew,
        )

        const res = await getImgListApi(queryParamsNew)
        // 更新总数
        total.value = res.data.total
        console.log(
            '%c🔍 获取照片列表出参 %c',
            'background: linear-gradient(90deg, #FF6B6B, #4ECDC4); color: white; padding: 5px 10px; border-radius: 5px; font-weight: bold;',
            '',
            res,
        )

        if (res.code === 200) {
            if (isTap) {
                // 点击搜索时，直接替换数据
                imgList.value = res?.data?.list || []
                // 重置页码
                queryParams.value.pageNum = 1
            } else {
                // 下拉加载时，追加数据
                if (res?.data && res?.data?.list?.length > 0) {
                    imgList.value = [...imgList.value, ...res.data.list]
                }
            }

            imgList.value.forEach((e) => {
                e.imgUrl = `${baseURL}/imgTool/files${e.compressFilePath}?token=${token}`
            })
        } else {
            uni.$u.toast(res.msg)
        }
    } catch (error) {
        // 发生错误时重置数据
        if (isTap) {
            imgList.value = []
        }
    }
}
getImgListData()

// 判断数据是否加载完毕
const finish = computed(() => {
    if (total.value === imgList.value.length) return true
})
// 点击我的收藏
const handleMyCollect = () => {
    queryParams.value.queryType = 1
    getImgListData(true)
}
// 点击最近上传
const handleLastUpload = () => {
    queryParams.value.queryType = 2
    getImgListData(true)
}

// 更新列表
const handleGetImgList = () => {
    getImgListData(true)
}

// 根据照片分类进行查询
const handleGetImgListByImgType = (type) => {
    queryParams.value.uploadType = type
    queryParams.value.searchType = 2
    getImgListData(true)
}

// 查看照片总数
const HandleViewImgTotal = () => {
    queryParams.value.uploadType = ''
    queryParams.value.searchType = 2
    getImgListData(true)
}

// 日期格式化
const formatter = (type, value) => {
    if (type === 'year') {
        return `${value}年`
    }
    if (type === 'month') {
        return `${value}月`
    }
    if (type === 'day') {
        return `${value}日`
    }
    return value
}

const onConfirmDate = () => {
    const formatDateValue = formatDate(dateValue.value)
    if (dateType.value === 1) {
        queryParams.value.startTime = formatDateValue
    }
    if (dateType.value === 2) {
        queryParams.value.endTime = formatDateValue
    }

    // 校验时间有效性
    if (queryParams.value.startTime && queryParams.value.endTime) {
        const start = new Date(queryParams.value.startTime)
        const end = new Date(queryParams.value.endTime)

        if (start > end) {
            uni.showToast({
                title: '结束时间不能早于开始时间',
                icon: 'none',
            })
            if (dateType.value === 1) {
                queryParams.value.endTime = formatDateValue
            } else {
                queryParams.value.startTime = formatDateValue
            }

            return // 阻止关闭弹窗
        }
    }
    dateShow.value = false
}

const formatDate = (timestamp) => {
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 打开日期选择器
const onSelectDate = (type) => {
    // type 为类型 1. 开始日期 2. 结束日期
    dateType.value = type
    dateShow.value = true
}
// 选择工程
const onSelectProject = () => {
    projectShow.value = true
}

// 工程选择
const onConfirmProject = (item) => {
    queryParams.value.proName = item.value[0].name
    queryParams.value.proId = item.value[0].id
    projectShow.value = false
}

// 选择专业
const onSelectMajor = () => {
    majorShow.value = true
}

// 专业确定
const onConfirmMajor = (item) => {
    queryParams.value.majorName = item.value[0].name
    queryParams.value.majorId = item.value[0].id
    getProcedureData(item.value[0].id)
    majorShow.value = false
}

// 选择工序
const onSelectProcedure = () => {
    procedureShow.value = true
}

// 工序确定
const onConfirmProcedure = (item) => {
    queryParams.value.gxName = item.value[0].name
    queryParams.value.gxId = item.value[0].id
    procedureShow.value = false
}

// 获取工序
const getProcedureData = async (pid) => {
    console.log(
        '%c🔍 获取工序请求入参 %c',
        'background: linear-gradient(90deg, #FF6B6B, #4ECDC4); color: white; padding: 5px 10px; border-radius: 5px; font-weight: bold;',
        '',
        'pid=' + pid,
    )
    const { data: res } = await getProcedureApi({ pid })
    console.log(
        '%c🔍 获取工序请求出参 %c',
        'background: linear-gradient(90deg, #FF6B6B, #4ECDC4); color: white; padding: 5px 10px; border-radius: 5px; font-weight: bold;',
        '',
        res,
    )
    procedureList.push(res)
}

const resetForm = () => {
    innerKeyWord.value = ''
    Object.assign(queryParams.value, {
        proId: '', // 工程
        proName: '', // 工程名称
        majorId: '', // 专业id
        majorName: '', // 专业名称
        gxId: '', // 工序id
        gxName: '', // 工序名称
        startTime: '', // 开始日期
        endTime: '', // 结束日期
        vioPlace: '', // 违章地点
        vioDesc: '', // 违章描述
        rectDesc: '', // 整改说明
        checkPlace2: '', // 检查地点
        checkDesc2: '', // 检查描述
        rectDesc2: '', // 整改说明
        checkDesc3: '', // 检查地点
        rectDesc3: '', // 检查描述
        buildPlace: '', // 建设地点
        title: '',
        photoType: [],
        photoType_1: [],
        photoType_2: [],
        photoType_3: [],
    })
}

onMounted(async () => {
    projectList.push(await getProjectList())
    majorList.push(await getMajorList())
})
</script>

<style lang="scss" scoped>
.comprehensive-query {
    height: 100%;
    box-sizing: border-box;
    .filter-box {
        padding: 16rpx 0;
        .search-text {
            font-size: 14px;
            letter-spacing: 1rpx;
            color: #4a6fff;
        }

        ::v-deep .u-input {
            width: 85%;
            margin: 0 auto;
            background-color: #f3f4f6;
        }
    }

    .photo-container {
        padding: 0 30rpx;
    }
}

// 高级搜索弹框样式
.senior-popup {
    width: 90vw;
    height: 100vh;
    overflow: hidden;
    .senior-title {
        padding: 24rpx 30rpx;
        display: flex;
        align-items: center;
        background-color: #f5f5f5;

        & text {
            margin-left: 4rpx;
            letter-spacing: 2rpx;
        }
    }

    .btns {
        width: 100%;
        height: 50px;
        padding: 18rpx 0;
        position: absolute;
        bottom: 0;
        right: 0;
        border-top: 1px solid #cac6c6;
        background-color: #fff;
        box-sizing: border-box;

        & view {
            margin-right: 18rpx;
            display: flex;
            justify-content: flex-end;
        }
    }
}
::v-deep .u-checkbox {
    margin-right: 5px;
}

// 加载提示文字
.loading-text {
    text-align: center;
    font-size: 26rpx;
    color: #8c8c8c;
    padding: 32rpx 0;
    letter-spacing: 1rpx;
}
</style>
