<template>
    <div class="mine-index">
        <div class="mine-header">
            <div class="user-info-box" @click="handleUserInfoClick">
                <el-avatar
                    class="avatar"
                    :size="54"
                    :src="userInfo?.icon"
                />
                <div class="user-info">
                    <div class="user-name">
                        <span v-if="curRole === 0">{{ userInfo?.nickname }}</span>
                        <span v-else>{{ userInfo?.name }}</span>
                        <span class="score" v-if="curRole !== 0">5.0分</span>
                    </div>
                    <div class="user-day">这是您使用飞鸟管家的第{{ daysSinceCreation }}天</div>
                </div>
            </div>
            <div class="code-icon" v-if="curRole === 1">
                <img src="@/assets/img/mine/code-icon.png" alt="" />
            </div>
            <div class="switch-role-btn" v-if="roles && roles.length > 1" @click="changeToggle">
                <span>切换身份</span>
                <el-icon><Switch /></el-icon>
            </div>
        </div>
        <div class="mine-content">
            <div class="garden-info" v-if="curRole !== 0">
                <div class="item" v-for="(item, index) in gardenInfoItems" :key="index">
                    <span class="num">{{ item.num }}</span>
                    <span>{{ item.label }}</span>
                </div>
            </div>
            <!-- <div class="grid-group">
                <div class="grid-item" v-for="(item, index) in gridItems" :key="index" @click="handleGridClick(item)">
                    <div class="grid-title">
                        <span>{{ item.title }}</span>
                        <el-icon><ArrowRight /></el-icon>
                    </div>
                    <span class="grid-desc">{{ item.desc }}</span>
                </div>
            </div> -->
            <div class="cell-group">
                <div class="cell-item" v-for="(item, index) in cellItems" :key="index" @click="handleCellClick(item)">
                    <span class="item-title">{{ item.title }}</span>
                    <el-icon class="item-arrow"><ArrowRight /></el-icon>
                </div>
            </div>
        </div>
        <!-- 角色切换 -->
        <action-sheet :style="{ bottom: 50 + 'px' }" v-model:show="show" :actions="actions" @select="onSelect" />
    </div>
</template>
<script setup>
import { onActivated, ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import wx from "weixin-js-sdk";
import { ActionSheet } from "vant";
import { SET_USER_CUR_ROLE } from "@/store/modules/app/type";

const store = useStore();
const router = useRouter();

// 0: 农户, 1: 专家, 2:农资农服
const curRole = ref(Number(localStorage.getItem("SET_USER_CUR_ROLE")));
const roles = ref(JSON.parse(store.state.app.roles));
const userInfo = JSON.parse(localStorage.getItem("localUserInfo") || "{}");

// 计算从创建时间到现在经过的天数
const daysSinceCreation = computed(() => {
    if (!userInfo?.createTime) {
        return 0;
    }
    try {
        // 将创建时间字符串转换为日期对象
        const createDate = new Date(userInfo.createTime);
        // 获取当前日期
        const currentDate = new Date();
        // 将两个日期都设置为当天的 00:00:00，只比较日期部分
        const createDateOnly = new Date(createDate.getFullYear(), createDate.getMonth(), createDate.getDate());
        const currentDateOnly = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
        // 计算日期差（毫秒）
        const timeDiff = currentDateOnly.getTime() - createDateOnly.getTime();
        // 转换为天数
        const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
        // 加1，因为创建当天算作第1天
        return days + 1;
    } catch (error) {
        console.error('计算天数失败:', error);
        return 0;
    }
});

// const roles = ref([0,1,2,3])
const actions = ref([]);

// 网格项数据
const gridItems = ref([]);

const objects = [
    { name: "农户", id: 0, text: "NH" },
    { name: "农资", id: 2, text: "NZ" },
];

onMounted(() => {
    // 仅保留 objects 中存在的角色
    actions.value = objects.filter(obj => roles.value && roles.value.includes(obj.id));
});

const show = ref(false);
// 切换身份角色
const onSelect = async (item) => {
    show.value = false;

    store.dispatch(`app/${SET_USER_CUR_ROLE}`, item.id);
    localStorage.setItem('SET_USER_CUR_ROLE',item.id)
    
    // 保存到 session
    try {
        await VE_API.mine.saveSessionStore({
            val: item.id,
            key: "cur_role"
        });
    } catch (error) {
        console.error('保存角色到 session 失败:', error);
    }
    window.location.reload()
};

onActivated(() => {
    if (curRole.value === 0) {
        gridItems.value = [
            {
                title: "我的农场",
                desc: "查看农场列表",
                path: "/my_farm",
            },
            {
                title: "我的消息",
                desc: "查看未读信息",
                path: "/message",
            },
            {
                title: "农事记录",
                desc: "查看历史农事",
                path: "/farm_records",
            },
        ];
    } else if (curRole.value === 1) {
        gridItems.value = [
            {
                title: "我的主页",
                desc: "查看农场列表",
                path: "/expert_detail",
            },
            {
                title: "我的报价",
                desc: "查看未读信息",
                path: "/message",
            },
            {
                title: "信息化档案",
                desc: "查看历史农事",
                path: "/archives",
            },
        ];
    } else if (curRole.value === 2) {
        gridItems.value = [
            {
                title: "我的主页",
                desc: "查看农场列表",
                path: "/my_farm",
            },
            {
                title: "我的消息",
                desc: "查看未读信息",
                path: "/message",
            },
            {
                title: "信息化档案",
                desc: "查看历史农事",
                path: "/archives",
            },
        ];
    }
});

// 单元格项数据 - 根据角色动态显示
const cellItems = computed(() => {
    if (curRole.value === 0) {
        return [
            {
                title: "我的农场",
                path: "/my_farm",
            },
            {
                title: "认证农资",
                path: "/register?identity=NZ",
            },
            {
                title: "退出登录",
                path: "/logout",
            },
        ];
    } else {
        return [
            {
                title: "系统提醒",
                path: "/message",
            },
            {
                title: "种植方案",
                path: "/plan?farmId=101532&pageType=plant",
            },
            {
                title: "服务记录",
                path: "/service_records",
            },
            {
                title: "报价维护",
                path: "/offer_price",
            },
            {
                title: "服务维护",
                path: "/service_manage",
            },
            {
                title: "团队管理",
                path: "/team_manage",
            },
        ];
    }
});

// 花园信息项数据
const gardenInfoItems = ref([
    { num: '--', label: "服务次数" },
    { num: '--', label: "累计客户" },
    { num: '--', label: "服务果园" },
]);

onActivated(() => {
    if(curRole.value !== 0){
        getStatistics();
    }
})

const getStatistics = () => {
    VE_API.z_agricultural_store.statistics().then(({ data }) => {
        gardenInfoItems.value[0].num = data.serviceCount || '--';
        gardenInfoItems.value[1].num = data.customerCount || '--';
        gardenInfoItems.value[2].num = data.serviceFarmCount || '--';
    });
}

// 处理网格项点击
const handleGridClick = (item) => {
    if (item.path) {
        router.push(item.path);
    }
};

// 处理单元格项点击
const handleCellClick = (item) => {
    if (item.path) {
        if (item.path === "/logout") {
            // 退出登录逻辑
            console.log("退出登录");
            // 这里可以添加退出登录的具体逻辑
        } else {
            router.push(item.path);
        }
    }
};

const changeToggle = () => {
    show.value = true;
};

const handleUserInfoClick = () => {
    wx.miniProgram.navigateTo({
        url: `/pages/subPages/user_info/index?route_path=/mine`,
    });
}
</script>
<style lang="scss" scoped>
.mine-index {
    width: 100%;
    height: 100vh;
    box-sizing: border-box;
    padding: 20px 16px;
    background: url("@/assets/img/mine/mine-bg.png") no-repeat center center / 100% 100%;
    .mine-header {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .user-info-box {
            display: flex;
            align-items: center;
            .avatar {
                border: 1px solid #fff;
                margin-right: 12px;
            }
            .user-info {
                font-size: 20px;
                .user-name {
                    font-weight: 500;
                    display: flex;
                    align-items: center;
                    .score {
                        font-size: 14px;
                        color: #2199f8;
                        margin-left: 6px;
                        font-weight: 500;
                    }
                }
                .user-day {
                    font-size: 12px;
                    color: rgba(0, 0, 0, 0.5);
                }
            }
        }
        .code-icon {
            width: 21px;
            height: 21px;
            img {
                width: 100%;
                height: 100%;
            }
        }
        .switch-role-btn {
            margin-right: -16px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 5px 10px 6px 12px;
            color: #fff;
            background: #2199f8;
            border-radius: 25px 0 0 25px;
            gap: 5px;
            font-size: 13px;
        }
    }
    .mine-content {
        margin-top: 20px;
        .garden-info {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-radius: 8px;
            padding: 6px 0;
            background-color: rgba(255, 255, 255, 0.5);
            margin-bottom: 10px;
            .item {
                display: flex;
                flex: 1;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: #999999;
                font-size: 13px;
                .num {
                    font-size: 16px;
                    color: #000;
                    margin-bottom: 2px;
                }
            }
        }
        .grid-group {
            display: flex;
            align-items: center;
            .grid-item {
                background-color: #fff;
                border-radius: 14px;
                padding: 10px 0 10px 10px;
                color: #000;
                font-size: 16px;
                flex: 1;
                .grid-title {
                    display: flex;
                    align-items: center;
                    font-weight: 500;
                    margin-bottom: 6px;
                    span {
                        margin-right: 1px;
                    }
                }
                .grid-desc {
                    font-size: 12px;
                    color: rgba(0, 0, 0, 0.2);
                }
            }
            .grid-item + .grid-item {
                margin-left: 10px;
            }
        }
        .cell-group {
            .cell-item {
                margin-top: 10px;
                background-color: #fff;
                border-radius: 14px;
                padding: 13px 10px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                color: #000;
                font-size: 16px;
            }
        }
    }
}
</style>
