<template>
    <div class="fly-photo">
        <div class="tabs">
            <div class="tab-item" :class="{ active: activeTab === 0 }" @click="handleTab(0)">照片</div>
            <div class="tab-item" :class="{ active: activeTab === 1 }" @click="handleTab(1)">视频</div>
        </div>
        <div class="select-group">
            <!-- <el-date-picker
                class="date-picker"
                v-model="dateTime"
                @change="changeDate"
                size="large"
                type="date"
                format="YYYY年MM月DD日"
                value-format="YYYY-MM-DD"
                :style="{ width: activeTab ? '100%' : 'calc(100% - 145px)' }"
            /> -->
            <el-date-picker
                class="date-picker"
                v-model="dateTime"
                @change="changeDate"
                size="large"
                type="date"
                popper-class="pic-time-picker"
                format="YYYY年MM月DD日"
                value-format="YYYY-MM-DD"
                :style="{ width: activeTab ? '100%' : 'calc(100% - 145px)' }"
            >
                <template #default="cell">
                    <div class="cell" :class="{ current: cell.isCurrent }">
                        <span class="text">{{ cell.text }}</span>
                        <span v-if="isHoliday(cell)" class="holiday" />
                    </div>
                </template>
            </el-date-picker>
            <el-select v-if="activeTab === 0" @change="changeArea" class="select" v-model="areaValue" size="large">
                <el-option v-for="item in areaOptions" :key="item.value" :label="item.name" :value="item.id" />
            </el-select>
        </div>
        <div class="photo-list" v-show="activeTab === 0" v-loading="loadingImgs" element-loading-background="rgba(0, 0, 0, 0.3)">
            <div
                class="photo-item"
                v-for="(item, index) in imageList"
                :class="{ 'm-l-10': index % 2 !== 0 }"
                :key="index"
            >
                <album-carousel-item
                    lbum-carousel-item
                    :key="index"
                    :name="item.code"
                    :farmId="curFarmId"
                    :images="[item]"
                    :lock="false"
                ></album-carousel-item>
            </div>
            <div class="no-photo" v-show="loadingImgs === false && !imageList.length">暂无数据</div>
        </div>
        <div class="pagination-wrap" v-show="activeTab === 0">
            <el-pagination
                background
                :page-size="pageSize"
                :pagerCount="5"
                v-model:current-page="currentPage"
                @current-change="geImgaeList"
                layout="prev, pager, next"
                :total="totalVal"
            />
        </div>
        <div class="video-list" v-show="activeTab === 1">
            <div class="video-item" v-for="(item, index) in videoList" :key="item.id">
                <video ref="myVideo" class="mp4" loop muted :controls="item.isPlay">
                    <source :src="item.url" type="video/mp4" />
                </video>
                <img
                    v-show="!item.isPlay"
                    class="play"
                    @click="handlePlay(index)"
                    src="@/assets/images/home/play.png"
                    alt=""
                />
            </div>
        </div>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import albumCarouselItem from "../../album_compoents/albumCarouselItem.vue";
import config from "@/api/config";
import eventBus from "@/api/eventBus";
const resize = "?imageView/1/w/240/h/240";

const activeTab = ref(0);
const handleTab = (index) => {
    activeTab.value = index;
    changeDate();
};

const curFarmId = ref(sessionStorage.getItem("farmId"))

function handleChangeGarden(id) {
    curFarmId.value = id
    console.log('curFarmId', id);
    getBlueRegionList()
}

function getCurrentMonth() {
    const now = new Date();
    const formattedDate = now.toISOString().slice(0, 10);
    return formattedDate;
}

const dateTime = ref(getCurrentMonth());
const changeDate = () => {
    if (activeTab.value) {
        getVideoList();
    } else {
        currentPage.value = 1
        geImgaeList();
    }
};

const isHoliday = ({ dayjs }) => {
    return allImgsDates.value.includes(dayjs.format("YYYY-MM-DD"));
};

const allImgsDates = ref([]);
function getDates() {
    VE_API.image.fetchGardenImgsDate({ farmId: curFarmId.value, regionId: areaValue.value }).then(({ data }) => {
        allImgsDates.value = data;
        dateTime.value = data[0];
        geImgaeList();
    });
}

const areaValue = ref(null); // 默认区域ID

const areaOptions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示20条数据
const totalVal = ref(0);

const loadingImgs = ref(false)
const imageList = ref([]);
const geImgaeList = () => {
    loadingImgs.value = true
    VE_API.image
        .fetchGardenImgs({
            date: dateTime.value,
            organId: curFarmId.value,
            areaId: areaValue.value,
            limit: pageSize.value,
            page: currentPage.value,
        }, {Global: false})
        .then((res) => {
            imageList.value = res.data;
            totalVal.value = res.count;
            loadingImgs.value = false
        });
};

function changeArea() {
    currentPage.value = 1; // 重置页码
    getDates();
}

const videoList = ref([]);
const getVideoList = () => {
    VE_API.image.videoList({ date: dateTime.value }).then((res) => {
        videoList.value = res.data || [];
    });
};

const myVideo = ref(null);
const currentPlaying = ref(null);
const handlePlay = (index) => {
    myVideo.value[index].play();
    videoList.value[index].isPlay = true;
};

onMounted(() => {
    eventBus.off('garden:organId', handleChangeGarden)
    eventBus.on('garden:organId', handleChangeGarden)
    
    getBlueRegionList();
});

function getBlueRegionList() {
    VE_API.image.fetchRegionList({ farmId: curFarmId.value }).then(({ data }) => {
        areaOptions.value = data;
        areaValue.value = data[0].id;
        getDates();
    });
}

// 提取前6位并转换为日期格式
function formatDatePart(originalStr) {
    // 提取前6位数字
    const datePart = originalStr.substring(0, 6);

    // 解析为日期格式
    const year = "20" + datePart.substring(0, 2); // 前两位是年份，加上20前缀
    const month = datePart.substring(2, 4); // 中间两位是月份
    const day = datePart.substring(4, 6); // 最后两位是日

    // 组合成YYYY-MM-DD格式
    const formattedDate = `${year}-${month}-${day}`;
    // 返回新字符串（不改变原字符串）
    return formattedDate;
}
</script>

<style lang="scss" scoped>
.fly-photo {
    width: calc(100% - 54px - 10px);
    height: 100%;
    padding: 8px 8px 8px 0;
    box-sizing: border-box;
    .tabs {
        width: 100%;
        display: flex;
        .tab-item {
            font-size: 16px;
            padding: 8px;
            cursor: pointer;
            text-align: center;
            border-radius: 5px;
            flex: 1;
            background: rgba(255, 255, 255, 0.07);
            &.active {
                background-color: #ffd489;
                color: #000;
            }
        }
        .tab-item + .tab-item {
            margin-left: 5px;
        }
    }
    .select-group {
        display: flex;
        margin: 10px 0;
        .select {
            width: 140px;
            margin-left: 5px;
        }
        ::v-deep {
            .el-select__wrapper {
                background: rgba(255, 255, 255, 0.07);
                box-shadow: none;
            }
            .el-select__placeholder,
            .el-select__caret,
            .el-input__prefix {
                color: #fff;
                text-align: center;
            }
            .el-input__wrapper {
                background: #323232;
                box-shadow: none;
            }
            .el-input__inner {
                color: #fff;
            }
        }
    }
    .photo-list {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        overflow: auto;
        width: 100%;
        height: calc(100% - 100px - 42px);
        .photo-item {
            width: calc(50% - 5px);
            margin-bottom: 10px;
            .img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 4px;
            }
            ::v-deep {
                .carousel-item .tag-box.leftTop {
                    display: none;
                }
                .carousel-item img {
                    border-radius: 4px;
                }
            }
        }
        .m-l-10 {
            margin-left: 10px;
        }
        .no-photo {
            color: #fff;
            width: 100%;
            text-align: center;
            padding-top: 20px;
        }
    }
    .pagination-wrap {
        padding-top: 10px;
        ::v-deep {
            .el-pagination {
                justify-content: center;
            }
            .el-pagination.is-background .el-pager li {
                background: #424242;
                color: rgba(255, 255, 255, 0.7);
            }
            .el-pagination.is-background .el-pager li.is-active {
                background: #FFD489;
                color: #000;
            }
            .el-pagination.is-background .btn-prev:disabled {
                background: #424242;
                color: rgba(255, 255, 255, 0.4);
            }
            .el-pagination button {
                background: #424242;
                color: rgba(255, 255, 255, 0.7);
                &:hover {
                    color: rgba(255, 255, 255, 1);
                }
            }
        }
    }
    .video-list {
        width: 100%;
        height: calc(100% - 100px);
        overflow: auto;
        .video-item {
            width: 100%;
            height: 172px;
            position: relative;
            .mp4 {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 5px;
            }
            .play {
                width: 62px;
                height: 62px;
                position: absolute;
                left: calc(50% - 31px);
                top: calc(50% - 31px);
                cursor: pointer;
            }
        }
        .video-item + .video-item {
            margin-top: 10px;
        }
    }
}
</style>

<style lang="less">
.pic-time-picker {
    .cell {
        height: 30px;
        padding: 3px 0;
        box-sizing: border-box;
    }

    .cell .text {
        width: 24px;
        height: 24px;
        display: block;
        margin: 0 auto;
        line-height: 24px;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 50%;
    }

    .cell.current .text {
        background: #409eff;
        color: #fff;
    }
    .available.today {
        .cell .text {
            color: #409eff;
        }
        .cell.current .text {
            color: #fff;
        }
    }

    .cell .holiday {
        position: absolute;
        width: 6px;
        height: 6px;
        background: #2199f8;
        border-radius: 50%;
        bottom: 0px;
        left: 50%;
        transform: translateX(-50%);
    }
}
</style>
