<template>
    <div class="header">
        <Header :color="'black'"/>
    </div>

    <div class="root">
        <MapContainer @update="Update" @err="Err" v-if="status === 1 && data != null" :radius="data.radius"
            :position="data.position" :address="data.address" />
        <div class="container" v-else></div>

        <div class="content">
            <div class="item">
                <el-result icon="success" title="您在打卡范围内" sub-title="现在可进行打卡操作"
                    v-if="status === 1 && distance <= data.radius">
                    <template #extra>
                        <el-button type="success" @click="addRecords">立即打卡</el-button>
                    </template>
                </el-result>

                <el-result icon="warning" title="您不在打卡范围内" :sub-title="'距打卡点' + distance + '米'"
                    v-else-if="status === 1 && distance > data.radius">
                    <template #extra>
                        <el-button type="warning" @click="$router.go(0)">重新定位</el-button>
                    </template>
                </el-result>

                <el-result icon="success" title="打卡成功" :sub-title="subTitle" v-else-if="status === 2">
                    <template #extra>
                        <el-button type="success" @click="$router.push('/')">返回首页</el-button>
                    </template>
                </el-result>

                <div class="err" v-else>
                    <el-result icon="error" :title="Title ? Title : '当前无法进行打卡操作'" :sub-title="subTitle">
                        <template #extra>
                            <el-button type="danger" @click="onload">重新尝试</el-button>
                        </template>
                    </el-result>
                </div>
            </div>

            <div class="item" v-if="data">
                <p class="title">项目详情</p>

                <div class="info">
                    <div class="key">项目编号：</div>
                    <div class="value">{{ data.id }}</div>
                </div>

                <div class="info">
                    <div class="key">项目名称：</div>
                    <div class="value">{{ data.name }}</div>
                </div>

                <div class="info">
                    <div class="key">创建时间：</div>
                    <div class="value">{{ stramptoTime(data.createTime) }}</div>
                </div>

                <div class="info">
                    <div class="key">打卡星期：</div>
                    <div class="value">{{ getWeekday(data.day_of_week) }}</div>
                </div>

                <div class="info">
                    <div class="key">每周循环：</div>
                    <div class="value">{{ data.loopy ? '是' : '否' }}</div>
                </div>

                <div class="info">
                    <div class="key">打卡地点：</div>
                    <div class="value">{{ data.address }}</div>
                </div>

                <div class="info">
                    <div class="key">打卡时间：</div>
                    <div class="value">
                        {{ data.begintime }}~{{ data.endtime }}
                    </div>
                </div>

                <div class="info users">
                    <div class="key">发起人：</div>
                    <div class="value2">
                        <div class="useritem">
                            <el-avatar :size="23" :src="userInfo[data.createUser].avatar" />
                            {{ userInfo[data.createUser] !=
                            undefined ? userInfo[data.createUser].username : `用户${data.createUser.slice(0, 4)}` }}
                        </div>
                    </div>
                </div>

                <div class="info users">
                    <div class="key">管理员：</div>
                    <div class="value2">
                        <div v-if="data.admin && data.admin.length === 0">无</div>
                        <div class="useritem" v-for="(item, index) in data.admin">
                            <el-avatar :size="23" :src="userInfo[item].avatar" />
                            {{ userInfo[item] !=
                            undefined ? userInfo[item].username : `用户${item.slice(0, 4)}` }}
                        </div>
                    </div>
                </div>

                <div class="info users">
                    <div class="key">参与人：</div>
                    <div class="value2">
                        <div class="useritem join" v-for="(item, index) in data.user">
                            <el-avatar :size="23" :src="userInfo[item].avatar" />
                            {{ userInfo[item] !=
                            undefined ? userInfo[item].username : `用户${item.slice(0, 4)}` }}
                        </div>
                    </div>
                </div>
                <div class="info users">
                    <div class="key">未打卡：</div>
                    <div class="value2">
                        <div v-if="noRecord.length === 0">无</div>
                        <div class="useritem fail" v-for="(item, index) in noRecord">
                            <el-avatar :size="23" :src="userInfo[item].avatar" />
                            {{ userInfo[item] !=
                            undefined ? userInfo[item].username : `用户${item.slice(0, 4)}` }}
                        </div>
                    </div>
                </div>
                <div class="info users">
                    <div class="key">已打卡：</div>
                    <div class="value2">
                        <div v-if="thisWeekRecords.length ===0">无
                        </div>
                        <div class="useritem success" v-for="(item, index) in thisWeekRecords">
                            <el-avatar :size="23" :src="userInfo[item.uuid].avatar" />
                            {{ userInfo[item.uuid] !=
                            undefined ? userInfo[item.uuid].username : `用户${item.uuid.slice(0, 4)}` }}
                        </div>
                    </div>
                </div>
            </div>

            <div class="item" v-if="data">
                <p class="title">打卡记录</p>
                <el-timeline>
                    <el-timeline-item type="success" :timestamp="stramptoTime(data.createTime)">
                        打卡项目已创建
                    </el-timeline-item>
                    <el-timeline-item type="danger" v-if="(showAll ? records : thisWeekRecords).length == 0">
                        暂时没有打卡记录
                    </el-timeline-item>
                    <el-timeline-item type="success" v-for="(item, index) in showAll ? records : thisWeekRecords"
                        :timestamp="stramptoTime(item.time)">
                        {{ userInfo[item.uuid] !==
                        undefined ? userInfo[item.uuid].username : `用户${item.uuid.slice(0, 4)}` }}已打卡{{ item.commit ?
                        ('(' + item.commit + ')')
                        : '' }}
                    </el-timeline-item>
                </el-timeline>

                <div v-if="data.loopy === 1">
                    <div class="hint" v-if="!showAll">当前显示本周期记录 | <span @click="showAll = true">查看全部</span></div>
                    <div class="hint" v-else>当前显示全部记录 | <span @click="showAll = false">查看当前周期</span></div>
                </div>
            </div>
        </div>
    </div>

    <el-backtop :right="70" :bottom="70"/>
    <Footer />
</template>

<script setup>
import Header from '../../components/Header.vue';
import Footer from '../../components/Footer.vue';
import { App } from '../../app/app';
import { ServerAPI } from '../../app/lib/ServerAPI';
const MapContainer = defineAsyncComponent(() => import('./components/MapContainer.vue'));
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

let status = ref(0);
let Title = ref('');
let subTitle = ref('');
let distance = ref();

let data = ref();
let userInfo = ref({});
let records = ref([]);
let thisWeekRecords = ref([]);
let showAll = ref(false);
let noRecord = ref([]);

function Update(data) {
    distance.value = data;
}

function Err(data) {
    status.value = 0;
    Title.value = '定位时发生错误';
    subTitle.value = data;
}

const stramptoTime = function (time) {
    if (time < 10)
        return 'NaN';
    return new Date(+time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

function onload() {
    document.documentElement.scrollTop = 0;
    const id = route.params.id;
    if (!App.hasUser()) {
        ElMessage.error('登录已过期，请重新登录');
        return router.push('/login');
    }

    const loading = ElLoading.service({
        lock: true,
        text: '正在加载中，请稍候'
    })

    ServerAPI.GetAttendanceItemDetail(App.user.uuid, App.user.session, id, (r) => {
        if (!r || r.code != 0 || r.data.length === 0) {
            Title.value = '获取考勤数据失败，请稍后再试';
            loading.close();
            return ElMessage.error('获取考勤数据失败！' + (r.msg ? r.msg : ''))
        }
        data.value = r.data;
        userInfo.value = r.userInfo;
        records.value = r.records;
        thisWeekRecords.value = filterRecords();
        noRecord.value = r.data.user.filter(uuid =>
            !thisWeekRecords.value.some(record => record.uuid === uuid)
        );
        loading.close();

        if (!r.data.user.includes(App.user.uuid)) {
            return Title.value = '您不在考勤名单内';
        }

        if (records.value.length !== 0 && hasRecord(data.value, records.value)) {
            subTitle.value = `打卡时间：${stramptoTime(Number(thisWeekRecords.value.find(record => record.uuid === App.user.uuid).time))}`;
            return status.value = 2;
        }

        const isWithinTime = isWithinAttendanceTime(data.value);
        if (!isWithinTime) {
            Title.value = '不在考勤时间范围内';
            return subTitle.value = `考勤时间：${getWeekday(data.value.day_of_week)} ${data.value.begintime}~${data.value.endtime}`;
        }

        // if (window.innerWidth > 768 || ) {
        //     return Title.value = '请使用手机端企业微信进行打卡操作';
        // }

        status.value = 1
    })
}
onload();

function isWithinAttendanceTime(attendanceTimes) {
    const now = new Date();
    const dayOfWeek = now.getDay();
    const nowTime = now.getTime();

    function timeToTodayTimestamp(timeStr) {
        const [hours, minutes, seconds] = timeStr.split(':').map(Number);
        const todayWithTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, seconds);
        return todayWithTime.getTime();
    }

    const { createTime, day_of_week, begintime, endtime, loopy } = attendanceTimes
    if (dayOfWeek === day_of_week && (loopy || (Number(createTime) + 604800000 - nowTime > 0)) && timeToTodayTimestamp(begintime) <= nowTime && timeToTodayTimestamp(endtime) >= nowTime) {
        return true;
    }
    return false
}

function addRecords() {
    if (distance.value > data.value.radius) {
        return ElMessage.error('不在打卡范围内！');
    }

    ServerAPI.AddAttendanceRecord(App.user.uuid, App.user.session, route.params.id, (r) => {
        if (r && r.code === 0) {
            ElMessage.success('打卡成功！');
            onload();
        } else {
            ElMessage.error('打卡失败！' + (r.msg ? r.msg : ''));
        }
    })
}

function filterRecords() {
    const { day_of_week, begintime, loopy } = data.value;
    if (!loopy) {
        return records.value;
    }
    const now = new Date();
    const nowTime = now.getTime();

    const begin = getTimestamp(day_of_week, begintime);
    if (nowTime >= begin) {
        return records.value.filter(item => item.time >= begin);
    }
    return records.value.filter(item => item.time >= begin - 604800000);
}

function getTimestamp(day_of_week, begintime) {
    const now = new Date();
    const dayOfWeek = now.getDay();
    // 计算今天与目标星期几的差值
    // 目标星期几应当是从0到6的范围，0是星期日，6是星期六
    const daysUntilTarget = (day_of_week - dayOfWeek + 7) % 7;
    // 计算目标日期
    const targetDate = new Date(now);
    targetDate.setDate(now.getDate() + daysUntilTarget);
    const [hours, minutes, seconds] = begintime.split(':').map(Number);
    targetDate.setHours(hours, minutes, seconds, 0);
    return targetDate.getTime();
}

function hasRecord(attendanceData, records) {
    const { day_of_week, begintime, loopy } = attendanceData;
    if (!loopy) {
        return records.some(record => record.uuid === App.user.uuid);
    }
    const now = new Date();
    const nowTime = now.getTime();

    const begin = getTimestamp(day_of_week, begintime);
    if (nowTime >= begin) {
        return records.some(record => record.time >= begin && record.uuid === App.user.uuid);
    }

    return records.some(record => record.time >= begin - 604800000 && record.uuid === App.user.uuid);
}

function getWeekday(day_of_week) {
    switch (day_of_week) {
        case 0:
            return '星期日'
        case 1:
            return '星期一'
        case 2:
            return '星期二'
        case 3:
            return '星期三'
        case 4:
            return '星期四'
        case 5:
            return '星期五'
        case 6:
            return '星期六'

        default:
            return '未知星期'
    }
}

</script>

<style scoped>
.header {
    position: fixed;
    z-index: 999;
    width: 100%;
}

.container {
    position: sticky;
    height: 80px;
}

.root {
    display: flex;
    flex-direction: column;
    min-height: 70vh;
    gap: 20px;
}

.content {
    flex: 1;
    width: 70%;
    margin: 0 auto;
    background-color: #eee;
}

.content .title {
    font-size: 1.2em;
    text-align: center;
}

.content .item {
    padding: 8px 20px 20px 20px;
    background-color: #fff;
    border-radius: 10px;
    margin-bottom: 10px;
    color: #337ecc;
    animation: fadeIn 0.6s ease-in-out forwards;
}

.content .item .info {
    display: flex;
    font-size: 14px;
    margin-top: 4px;
}

.content .item .info .key {
    width: 70px;
}

.content .item .info .value {
    color: #777;
    flex: 1;
}

.content .item .value2 {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.content .item .useritem {
    display: flex;
    align-items: center;
    background-color: #d9ecff;
    color: #337ecc;
    padding: 5px;
    border-radius: 10px;
    transform: translateY(-7px);
}

.content .item .join {
    background-color: #faecd8;
    color: #b88230;
}

.content .item .success {
    background-color: #e1f3d8;
    color: #529b2e
}

.content .item .fail {
    background-color: #fde2e2;
    color: #c45656
}

.content .item .users {
    margin-top: 10px;
}

.hint {
    color: #888;
    font-size: 0.8em;
    text-align: center
}

.err {
    display: flex;
    align-items: center;
    justify-content: center;
}

.el-timeline {
    margin-top: 20px;
}

@media only screen and (max-width: 768px) {
    .content {
        width: 90%;
        margin-top: -10px;
    }

    .container {
        height: 60px
    }

    .el-timeline {
        margin-left: -35px;
    }
}
</style>