<template>
    <div class="user-index" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <div class="user-header">
            <el-input class="search" v-model="input" placeholder="搜索">
                <template #prefix>
                    <el-icon><search /></el-icon>
                </template>
            </el-input>
            <div class="button" @click="handleAddClient">
                <img src="@/assets/img/mine/firend-icon.png" alt="" />
                新增客户
            </div>
        </div>
        <div class="list">
            <div class="map-container" ref="mapContainer"></div>

            <collapse v-model="activeNames" class="collapse-list">
                <collapse-item :name="index" v-for="(item, index) in dataList" :key="index" :is-link="false">
                    <template #title>
                        <el-icon class="icon"><CaretRight /></el-icon>
                        {{ item.name }}
                        <span class="span">{{ item.children?.length || 0 }}</span>
                    </template>
                    <template #value>
                        <div @click.stop="hadnleManage(item)" class="text">管理</div>
                    </template>
                    <farm-info-card
                        v-for="ele in item.children"
                        :key="ele.agriculturalStoreId"
                        class="list-item"
                        :data="{
                            ...ele,
                            farmName: ele.name,
                            userType: ele.userType || '托管客户',
                            variety: ele.speciesName,
                            address: ele.address,
                            maxWidth: '90px',
                            customRight: 'tag-right',
                        }"
                        @click="handleItemClick(ele)"
                    >
                        <template #right>
                            <el-popover title="" :popper-style="'min-width: 110px;'" :width="110" placement="left-start" trigger="click">
                                <div class="tag-list">
                                    <div class="tag-item">全托管</div>
                                    <div class="tag-item">飞防托管</div>
                                    <div class="tag-item">营养托管</div>
                                    <div class="tag-item active">优质客户</div>
                                </div>
                                <template #reference>
                                    <div class="title-tag add-tag">标记为</div>
                                </template>
                            </el-popover>
                        </template>
                        <template #footerData>
                            <div class="footer-data">
                                <div class="footer-l">
                                    <div class="farm-info-footer-item">
                                        <div class="farm-info-footer-item-label">农事服务</div>
                                        <div class="farm-info-footer-item-value">10<span class="unit">次</span></div>
                                    </div>
                                    <div class="farm-info-footer-item">
                                        <div class="farm-info-footer-item-label">总收益</div>
                                        <div class="farm-info-footer-item-value">1450<span class="unit">元</span></div>
                                    </div>
                                </div>
                                <div class="footer-action" @click.stop="handleDetail('plan', ele.id, ele.agriculturalStoreId)">农事规划</div>
                            </div>
                        </template>
                    </farm-info-card>
                </collapse-item>
            </collapse>
        </div>
        <div class="footer">
            <div class="btn" @click="showPopup">新建分组</div>
        </div>
    </div>
    <!-- 添加分组弹窗 -->
    <add-popup :show="showGroupPopup"></add-popup>
    <fn-share-sheet class="share-sheet" v-model:show="showShare" @select="onSelect" :options="[{ name: '微信', icon: 'wechat' }]" />
</template>

<script setup>
import { Collapse, CollapseItem } from "vant";
import { ref, onMounted, computed, nextTick, onActivated } from "vue";
import wx from "weixin-js-sdk";
import { useRouter } from "vue-router";
import addPopup from "./components/addPopup.vue";
import FarmInfoCard from "@/components/pageComponents/FarmInfoCard.vue";
import { useStore } from "vuex";
import FnShareSheet from "@/components/pageComponents/FnShareSheet.vue";
import IndexMap from "../farm_manage/map/index";

const router = useRouter();
const store = useStore();
const tabBarHeight = computed(() => store.state.home.tabBarHeight);

const indexMap = new IndexMap();
const mapContainer = ref(null);

onMounted(() => {
    const point = store.state.home.miniUserLocationPoint;
    nextTick(() => {
        indexMap.initMap(point, mapContainer.value, true);
    });
});

onActivated(() => {
    getUserList();
});

const activeNames = ref([1]);
const dataList = ref([
    {
        name: "Vip客户",
        isGroup: 0,
        children: [],
    },
    {
        name: "农场客户",
        isGroup: 1,
        children: [],
    },
]);
const getUserList = async () => {
    const { data } = await VE_API.farm.userFarmSelectOption({ agriculturalQuery: true });
    if (data.length) {
        // 地图使用筛选后的数据
        const wktArr = ["POINT (113.10930176274309 22.574540836684672)", "POINT (113.407189 23.032344)"]
        data.map((item, index) => {
            item.point = wktArr[Math.floor(Math.random() * wktArr.length)]
        });
        indexMap.initData(data, 'name');
        // 清空现有的子项
        dataList.value[0].children = [];
        dataList.value[1].children = data || [];
        getLatestBroadcast();
    }
};

const getLatestBroadcast = () => {
    VE_API.user.getLatestBroadcast({sourceTypes:[0,1]}).then(({ data }) => {
        if (data && typeof data === 'object') {
            // 遍历广播数据，key 是 farmId（字符串格式）
            Object.keys(data).forEach(farmIdStr => {
                const farmId = Number(farmIdStr);
                const broadcasts = data[farmIdStr] || [];
                
                // 在农场列表中找到对应的农场
                const farmItem = dataList.value[1].children.find(item => item.id === farmId || item.farmId === farmId);
                
                if (farmItem && broadcasts.length > 0) {
                    // 将广播数据合并到农场项中
                    farmItem.broadcasts = broadcasts;
                }
            });
        }
    });
};

const input = ref("");
//新建分组
const showGroupPopup = ref(false);
const showPopup = () => {
    showGroupPopup.value = !showGroupPopup.value;
};

// 新增客户
const handleAddClient = () => {
    router.push("/create_farm?type=client&from=user");
};

// 管理
const hadnleManage = (value) => {
    router.push(`/user_manage?name=${value.name}&total=${value.children.length}&isGroup=${value.isGroup}`);
};

const showShare = ref(false);
const onSelect = () => {
    const query = {
        agriculturalStoreId: shareData.value.agriculturalStoreId,
        farmId: shareData.value.id,
        speciesName: shareData.value.speciesName,
        containerId: shareData.value.containerId,
    };
    wx.miniProgram.navigateTo({
        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=shareFarm`,
    });
};

const shareData = ref({});
// 在线沟通
const handleChat = (data) => {
    if(data.receiveUserId){
        router.push(`/chat_frame?userId=${data.receiveUserId}&farmId=${data.id}`);
    }else{
        showShare.value = true;
        shareData.value = data;
    }
};

// 处理列表项点击
const handleItemClick = (data) => {
    router.push(`/farm_details?farmId=${data.id}&agriculturalStoreId=${data.agriculturalStoreId}&receiveUserId=${data.receiveUserId}`);
};

const handleDetail = (path, farmId, agriculturalStoreId) => {
    router.push(`/${path}?farmId=${farmId}&agriculturalStoreId=${agriculturalStoreId}`);
};
</script>

<style lang="scss" scoped>
.user-index {
    width: 100%;
    height: 100vh;
    box-sizing: border-box;
    padding: 10px 12px;
    background: #f5f7fb;
    .user-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .search {
            width: 90px;
            margin-right: 10px;
            --el-input-placeholder-color: rgba(0, 0, 0, 0.5);
            ::v-deep {
                .el-input__wrapper {
                    box-shadow: none;
                    border: 1px solid rgba(0, 0, 0, 0.5);
                    background: transparent;
                    border-radius: 20px;
                }
                .el-input__prefix,
                .el-input__inner {
                    color: #000;
                }
            }
        }
        .button {
            width: calc(100% - 100px);
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 8px;
            border-radius: 20px;
            img {
                width: 20px;
                height: 17px;
                margin-right: 6px;
            }
        }
    }
    .list {
        width: 100%;
        margin-top: 12px;
        height: calc(100% - 90px);
        overflow: auto;
        
        .map-container {
            width: 100%;
            height: 162px;
            clip-path: inset(0px round 8px);
            margin-bottom: 10px;
        }
        .collapse-list {
            // height: 100%;
        }
        .text {
            color: #7c7c7c;
        }
        ::v-deep {
            .van-collapse-item__content {
                padding: 0;
                background: #F5F7FB;
            }
            .van-cell {
                border-radius: 5px 5px 0 0;
                justify-content: space-between;
                .van-cell__value {
                    flex: none;
                }
                .van-cell__title {
                    display: flex;
                    align-items: center;
                    .icon {
                        margin-right: 3px;
                        color: #bfbfbf;
                        font-size: 16px;
                    }
                    .span {
                        color: rgba(0, 0, 0, 0.4);
                        margin-left: 10px;
                    }
                }
            }
            .van-collapse-item__title--expanded {
                .van-cell__title {
                    .icon {
                        transform: rotate(90deg);
                    }
                }
            }
            .van-collapse-item + .van-collapse-item {
                margin-top: 12px;
            }
        }
        .list-item {
            margin-top: 10px;
        }

        .add-tag {
            font-size: 12px;
            color: #2199f8;
            line-height: 24px;
        }
        
        .footer-data {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-top: 12px;
            .footer-l {
                display: flex;
                gap: 8px;
                flex: 1;
                .farm-info-footer-item {
                    display: flex;
                    align-items: baseline;
                    border: 0.4px solid rgba(215, 215, 215, 0.5);
                    padding: 8px 5px 5px;
                    box-sizing: border-box;
                    .farm-info-footer-item-label {
                        font-size: 12px;
                        color: rgba(32, 32, 32, 0.4);
                        margin-bottom: 4px;
                    }
                    .farm-info-footer-item-value {
                        font-size: 16px;
                        color: #202020;
                        padding-left: 2px;
                        .unit {
                            font-size: 12px;
                            padding-left: 2px;
                            color: rgba(32, 32, 32, 0.4);
                        }
                    }
                }
            }
            .footer-action {
                border: 0.5px solid #888B8D;
                border-radius: 20px;
                padding: 5px 12px;
                font-size: 12px;
                color: #888B8D;
                white-space: nowrap;
                cursor: pointer;
                flex-shrink: 0;
            }
        }
    }
    .footer {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 12px;
        .btn {
            font-size: 12px;
            color: #7f7f7f;
            padding: 5px 45px;
            background: rgba(201, 201, 201, 0.27);
            border-radius: 20px;
        }
    }
}


.tag-list {
    font-size: 14px;
    .tag-item + .tag-item {
        margin-top: 6px;
    }
    .tag-item {
        padding: 2px 8px;
        text-align: center;
        &.active {
            color: #2199f8;
            background: rgba(33, 153, 248, 0.16);
            border-radius: 4px;
        }
    }
}
</style>
