<template>
    <z-paging ref="paging" v-model="list" bgColor="#f7f7f7" @query="query" @scroll="onPageScroll">
        <template #top>
            <up-navbar :fixed="true" :bgColor="navBarBgColor">
                <template #left>
                    <view class="d-flex a-c pb-5" id="topup-navbar" :style="{ width: `${bubble.left - 30}px` }">
                        <image class="home_icon mr-20" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/common/home.png" mode="widthFix" />
                        <text class="f-s-40 c-333 f-w-5 w-s-no">中药材种植全链条追溯</text>
                        <view class="flex1"></view>
                    </view>
                </template>
            </up-navbar>
        </template>
        <view class="h-500 w-100%" style="background: linear-gradient(to left, #d2f7d5, #eafad8); position: absolute; top: 0; left: 0; z-index: -1"> </view>
        <template>
            <up-navbar :fixed="false" bgColor="transparent">
                <template #left>
                    <view class="pd-10"></view>
                </template>
            </up-navbar>
            <view class="user-page-header pd-10 d-flex a-c mg-14 p-rtv">
                <view class="user-page-header-avatar mr-20 p-rtv">
                    <up-avatar size="116rpx" :src="avatar || 'https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/common/avatar.png'"></up-avatar>
                </view>
                <view class="flex1 ov-hd mr-40">
                    <view class="p-rtv d-flex a-c mb-6">
                        <view class="flex1 ov-hd f-s-32 c-333 d-flex a-ed">
                            <text class="mr-12 up-line-1 f-w-5">{{ name }}</text>
                            <text class="c-999 f-s-24">{{ setCipByNum(phone ?? null, 3, 4) || '-' }}</text>
                        </view>
                    </view>
                    <view class="f-s-22 mr-10 radius-30 pt-4 pb-4 pl-10 pr-10 c-primary bg-#b7e8bc" style="width: max-content">
                        {{ currentCpyName }}
                    </view>
                </view>
            </view>
        </template>
        <template>
            <view class="p-rtv">
                <view class="pd-10 mg-14">
                    <view class="b-radius pd-6" style="border: 1rpx solid #fff; background: linear-gradient(90deg, #c1f3c5 0%, rgba(193, 243, 197, 0.5) 20%, rgba(255, 255, 255, 0.5) 35%, rgba(255, 255, 255, 0.5) 50%, rgba(232, 255, 234, 0.5) 100%, #e8ffea 100%), linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 30%, rgba(255, 255, 255, 0.3) 80%, transparent 100%)">
                        <view class="b-radius pd-10 p-rtv" style="border: 1rpx solid #baedbf">
                            <image class="w-200" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/typeofBusiness.png" mode="widthFix" style="position: absolute; top: 10rpx; left: 10rpx" />
                            <view v-if="!speciesArray.length" class="pd-20"></view>
                            <view v-if="speciesArray.length" class="d-flex pr-15">
                                <view class="flex1"></view>
                                <view class="f-s-22 c-primary" @click="$u.route({ url: '/plant/species/config/index' })">去修改{{ '>' }}</view>
                            </view>
                            <view v-if="speciesArray.length" class="c-#333 f-s-24 d-flex pl-40 pr-15 pb-15 pt-15">
                                <view class="ov-hd tx-ov w-s-no">{{ speciesArray.join('、') }}</view>
                                <view v-if="speciesArray.length > 4" class="flex1 w-s-no">等{{ speciesArray.length }}个品种 </view>
                            </view>
                            <view v-if="!speciesArray.length" @click="$u.route({ url: '/plant/species/config/index' })" class="c-primary bg-#E3F6E7 f-s-22 mg-at radius-10 w-250 h-50 d-flex a-c j-c"> 暂未配置品种,去配置{{ '>' }}</view>
                            <view v-if="!speciesArray.length" class="pd-7"></view>
                        </view>
                    </view>
                </view>
                <view class="b-radius pt-0 bg-#f7f7f7" style="border: 1rpx solid #fff; border-bottom-color: transparent; margin-top: -40rpx">
                    <up-sticky :offset-top="stickyTop" zIndex="10">
                        <view class="pd-24 p-rtv bg-#f7f7f7">
                            <image src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/basePlotBG.png" class="w-100%" mode="widthFix" style="position: absolute; top: 0; left: 0"></image>
                            <view class="d-flex a-c mb-26 p-rtv">
                                <view class="p-rtv d-flex flex-cln">
                                    <view class="c-333 f-s-32 f-w-5 z-index-1">基地与地块管理</view>
                                    <image class="w-230 h-11" style="margin-top: -10rpx" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/BasePlotManagement.png" mode="widthFix" />
                                </view>
                                <view class="flex1"></view>
                                <view @click="$u.route({ url: '/plant/base/gap-base-info/index' })" class="c-primary f-s-22 z-index-1">GAP基地获评信息管理{{ '>' }}</view>
                            </view>
                            <view class="d-flex a-c p-rtv">
                                <view class="w-220">
                                    <ut-action-sheet v-model="form.queryType" :tabs="typeNums" @change="onRefresh" title="选择原料类型">
                                        <view class="d-flex search-select-item a-c">
                                            <view class="flex1 ov-hd f-s-26 c-333 text-center f-w-5 w-s-no up-line-1">{{ selectDictLabel(typeNums, form?.queryType) || '全部' }} </view>
                                            <up-icon size="24rpx" color="#333" name="arrow-down-fill" class="ml-5"></up-icon>
                                        </view>
                                    </ut-action-sheet>
                                </view>
                                <view class="pl-16 flex1 ov-hd">
                                    <ut-search ref="searchRef" v-model="form.keyword" @search="changeSeach" margin="0" :border="false" placeholder="搜基地名称、编号、地址、负责人" bgColor="#fff" height="86rpx" borderRadius="10rpx"></ut-search>
                                </view>
                            </view>
                        </view>
                    </up-sticky>
                    <view class="pd4-10-24-24-24">
                        <template>
                            <up-swipe-action>
                                <up-swipe-action-item v-for="(item, index) in list" :key="index" :name="item?.id" :options="optionsActionTemp" @click="clickTempSwipe" class="mb-20 b-radius">
                                    <view class="b-radius bg-#fff pd-20 p-rtv" @click.stop="$u.route({ url: '/plant/base/base-detail/index', params: { id: item.id } })">
                                        <view class="c-333 f-s-34 pd-5 f-w-5">{{ item?.baseName }}</view>
                                        <view class="c-ccc f-s-24 pd-5 pt-0">{{ item?.baseCode }}</view>
                                        <view class="d-flex a-c">
                                            <view class="c-333 f-s-28 pd-5">
                                                <text class="c-#666">基地面积：</text>
                                                <text class="f-w-5">{{ item?.gapInfo?.area || '-' }}</text>
                                            </view>
                                            <view class="flex1"></view>
                                            <view class="c-333 f-s-28 pd-5">
                                                <text class="c-#666">建设时间：</text>
                                                <text class="f-w-5">{{ item?.buildDate || '-' }}</text>
                                            </view>
                                        </view>
                                        <view class="c-333 f-s-28 pd-5">
                                            <text class="c-#666">基地地址：</text>
                                            <text class="f-w-5">{{ (item?.gapInfo?.adcodeName || '') + (item?.gapInfo?.address || '') || '-' }}</text>
                                        </view>
                                        <view v-if="item?.plantingVarieties?.length" class="c-333 f-s-28 pd-5 d-flex">
                                            <text class="c-#666 w-s-no">当前在地品种：</text>
                                            <text class="ov-hd tx-ov w-s-no f-w-5">{{ item.plantingVarieties?.map((items) => items.variety).join('、') || '-' }}</text>
                                            <text v-if="item?.plantingVarieties?.length" class="flex1 w-s-no f-w-5">等{{ item.plantingVarieties?.length }}个品种</text>
                                        </view>
                                        <template v-if="item.gapInfo?.basePic">
                                            <view class="pd-10"></view>
                                            <view class="p-rtv">
                                                <image class="w-full h-310" :src="item.gapInfo?.basePic" mode="aspectFill"></image>
                                                <view class="d-flex flex-cln a-ed" style="position: absolute; bottom: 20rpx; right: 0">
                                                    <view class="pd2-10-20 bg-black-op-0.5 c-#ccc f-s-20 mb-10" style="border-radius: 10rpx 0 0 10rpx; width: max-content">{{ item?.contactName }}负责</view>
                                                    <view class="pd2-10-20 bg-black-op-0.5 c-#ccc f-s-20 mb-10" style="border-radius: 10rpx 0 0 10rpx; width: max-content">{{ selectDictLabel(pt_org_type, item?.orgType) }}</view>
                                                    <view class="pd2-10-20 bg-black-op-0.5 c-#ccc f-s-20" style="border-radius: 10rpx 0 0 10rpx; width: max-content">经度：E{{ item?.gapInfo?.lng }} 纬度：N{{ item?.gapInfo?.lat }}</view>
                                                </view>
                                                <view style="position: absolute; top: 20rpx; left: 0">
                                                    <template v-for="(resq, index) in item?.resInfo" :key="index">
                                                        <view class="base-status-gap-1" v-if="resq?.res == '1'">获评{{ resq?.medicineName }}{{ selectDictLabel(pt_base_form, resq?.type) }}基地</view>
                                                        <view class="base-status-gap-2" v-if="resq?.res == '2'">标记{{ resq?.medicineName }}{{ selectDictLabel(pt_base_form, resq?.type) }}基地未通过审核</view>
                                                        <view class="base-status-gap-0" v-if="resq?.res == '0'">标记{{ resq?.medicineName }}{{ selectDictLabel(pt_base_form, resq?.type) }}基地待审核</view>
                                                    </template>
                                                </view>
                                            </view>
                                        </template>
                                        <template v-else>
                                            <view v-if="item?.contactName" class="c-333 f-s-28 pd-5">
                                                <text class="c-#666">负责人：</text>
                                                <text class="f-w-5">{{ item?.contactName || '-' }}</text>
                                            </view>
                                            <view v-if="item?.orgType" class="c-333 f-s-28 pd-5">
                                                <text class="c-#666">组织方式：</text>
                                                <text class="f-w-5">{{ selectDictLabel(pt_org_type, item?.orgType) }}</text>
                                            </view>
                                            <view v-if="item?.orgType" class="c-333 f-s-28 pd-5">
                                                <text class="c-#666">经纬度：</text>
                                                <text class="f-w-5">E{{ item?.gapInfo?.lng }},N{{ item?.gapInfo?.lat }}</text>
                                            </view>
                                        </template>
                                        <view v-if="+(item?.tempFlag ?? 0)" class="temp_flag">暂存</view>
                                    </view>
                                </up-swipe-action-item>
                            </up-swipe-action>
                        </template>
                    </view>
                </view>
            </view>
        </template>
        <template #empty>
            <view class="" style="margin-top: -200rpx">
                <ut-empty class="mg-at" color="#ccc" size="28rpx" image="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/noEmptyBase.png">尚未添加绘制种养殖基地信息~</ut-empty>
                <view class="b-radius c-#fff f-s-36 bg-#37A954 h-78 w-382 d-flex a-c j-c mg-at" @click="showDeleteDialog = true">
                    <img class="w-38 h-36 mr-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/chooseGAP.png" alt="" mode="widthFix" />
                    <text>去添加基地</text>
                </view>
            </view>
        </template>
        <template #bottom>
            <ut-tabar activeTab="base"></ut-tabar>
        </template>
    </z-paging>

    <ut-confirm-dialog v-model:show="showDeleteDialog" width="80vw" title="请选择要添加到基地类型" :confirmText="'确认选择'" :cancelText="'取消'" @confirm="handlechoseConfirm" @cancel="handleDeleteCancel">
        <view class="" v-for="item in pt_base_type" :key="item?.value">
            <view style="border: 1rpx solid" :style="{ backgroundColor: item?.value == basetype ? '#EBF6EE' : '#f7f7f7', borderColor: item?.value == basetype ? '#37A954' : 'transparent' }" class="pr-30 d-flex a-c mb-20 radius-100" @click="handlechose(item.value)">
                <view class="radius-50% mg-8">
                    <up-avatar size="90rpx" :src="item?.avatar || 'https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/common/avatar.png'" class="mr-20"></up-avatar>
                </view>
                <view class="c-#333 f-s-34">
                    {{ item?.label }}
                </view>
                <view class="flex1"></view>
                <view class="d-flex">
                    <img v-if="basetype === item.value" class="w-30 h-30" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/chooseSuccessfully.png" mode="widthFix" alt="" />
                </view>
            </view>
        </view>
    </ut-confirm-dialog>
    <ut-suspension @click="showDeleteDialog = true">
        <image src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/addBase.png" mode="widthFix" class="w-120 h-120"></image>
    </ut-suspension>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { setCipByNum } from '@/utils/public';
import { useInfoStore } from '@/store';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pt_base_type, pt_org_type, pt_base_form } = toRefs<any>(proxy?.useDict('pt_base_type', 'pt_org_type', 'pt_base_form'));
const infoStore = useInfoStore();
// 获取用户信息
const avatar = computed(() => infoStore.userInfo?.avatar || '');
const name = computed(() => infoStore.userInfo?.name || '');
const phone = computed(() => infoStore.userInfo?.phone || '');
const currentCpyName = computed(() => infoStore.userInfo?.currentCpyName || '');
const windowInfo = uni.getWindowInfo();
const safeAreaBottom = windowInfo.safeAreaInsets.bottom;
// 证书文件类型
interface CertFile {
    fileName: string;
    url: string;
    fileSize: number;
}
// 差异信息类型
interface GapInfo {
    id: number;
    sourceType: string;
    gapBaseName: string;
    sn: string;
    medicineName: string;
    medicineId: number;
    area: number;
    basePic: string;
    lng: number;
    lat: number;
    adcode: string;
    address: string;
    ratedDate: string; // 格式: "YYYY-MM-DD"
    certFile: CertFile[];
    res: string;
    auditor: number;
    msg: string;
    adcodeName?: string;
}

// 种植品种类型
interface PlantingVariety {
    baseId: number;
    varietyId: string;
    variety: string;
}

// 坐标点类型
interface Coordinate {
    lng: number;
    lat: number;
}

// 主数据类型
interface BaseData {
    id: number;
    baseName: string;
    baseCode?: string;
    baseType?: string;
    adcode?: string;
    buildDate?: string; // 格式: "YYYY-MM-DD"
    orgType: string;
    contactId: number;
    contactTel: string;
    contactName?: string;
    lng: number;
    lat: number;
    basePic: string;
    address: string;
    area: number;
    gapFlag: string;
    gapInfo: GapInfo;
    cpyid: number;
    appid: number;
    partnerId: number;
    createBy: number;
    updateBy: number;
    createTime: string; // ISO 8601 格式
    updateTime: string; // ISO 8601 格式
    hide: string;
    plantingVarieties: PlantingVariety[];
    coordinates: Coordinate[][]; // 二维坐标数组
    tempFlag?: number | string;
    resInfo?: any[];
}
const instance = getCurrentInstance();
const list = ref<BaseData[]>();
const paging = ref();
const bubble = ref(uni.getMenuButtonBoundingClientRect());

const form = ref({ queryType: '', keyword: '' });
const speciesArray = ref([]);
const navBarBgColor = ref('transparent');
const stickyTop = ref(0);
const systemInfo = uni.getSystemInfoSync();
const sus = ref({
    left: 0,
    bottom: 0,
});
sus.value.left = systemInfo.windowWidth - 10;
sus.value.bottom = systemInfo.windowHeight - 200;
const changeSeach = () => {
    paging.value.reload();
};
const onRefresh = () => {
    paging.value.reload();
};
const onPageScroll = (e: any) => {
    const { scrollTop } = e.detail;
    if (scrollTop > 20) {
        navBarBgColor.value = '#d9f8d6';
    } else {
        navBarBgColor.value = 'transparent';
    }
};
const query = async (pageNum: number, pageSize: number) => {
    const params = {
        pageNum,
        pageSize,
        ...form.value,
    };
    if (pageNum == 1) {
        getBaseCount();
    }
    const res = await useClientRequest.get('/plt-api/app/base/pageList', params);
    console.log(res, 'res');
    if (res) {
        const { rows } = res;
        paging.value.complete(rows);
    }
};
// 查询企业的种植品种
const getSpecies = async () => {
    const res = await useClientRequest.get('/plt-api/app/cpyVariety/list');
    if (res?.code === 200) {
        speciesArray.value = res.data?.map((item: any) => item.medicineName);
    }
};
const showDeleteDialog = ref(false);
const basetype = ref('1');
const handlechose = (item: string) => {
    basetype.value = item;
};

// 处理取消
const handleDeleteCancel = () => {
    showDeleteDialog.value = false;
    basetype.value = '1';
};
const handlechoseConfirm = () => {
    uni.$u.route({ type: 'navigateTo', url: '/plant/base/base-edit/index', params: { baseType: basetype.value } });
};

// 暂存项左滑删除配置
const optionsActionTemp = reactive([
    {
        text: '删除',
        style: {
            backgroundColor: '#F74C30',
        },
    },
]);

// 暂存项删除点击（本地移除）
const clickTempSwipe = async (event: object) => {
    const { name, index } = event as any;
    if (index === 0) {
        try {
            const res = await uni.showModal({
                title: '删除提示',
                content: '确定删除该基地吗？',
                confirmColor: '#F74C30',
            });
            if (!res.confirm) return;
            await uni.showLoading({
                title: '删除中...',
                mask: true,
            });
            await useClientRequest.get(`/plt-api/app/base/delById/${name}`);
            uni.hideLoading();
            uni.showToast({
                title: '删除成功',
                icon: 'success',
            });
            paging.value?.reload();
        } catch (error) {
            console.error('删除暂存基地失败:', error);
        }
    }
};
const typeNums = ref<any[]>([]);
// 获取统计信息
const getBaseCount = async () => {
    try {
        const res = await useClientRequest.get('/plt-api/app/base/getBaseCount');
        if (res?.code === 200) {
            console.log(res);
            typeNums.value = res.data?.map((item: any) => {
                return {
                    label: `${item.name}(${item.num})`,
                    value: item.type,
                };
            });
        }
    } catch (error) {
        console.error('获取地块统计信息失败:', error);
    }
};
onMounted(() => {
    const querys = uni.createSelectorQuery().in(instance?.proxy);
    querys
        .select('#topup-navbar')
        .boundingClientRect((data: any) => {
            console.log(data);

            stickyTop.value = data.top + data.height;
        })
        .exec();
    getSpecies();
    uni.$on('refreshBaseList', () => {
        onRefresh();
    });
});
onShow(() => {
    getSpecies();
});
</script>
<style lang="scss" scoped>
// @import '@/assets/styles/theme.scss';
.search-select-item {
    height: 86rpx;
    background-color: #fff;
    border-radius: 10rpx;
    box-sizing: border-box;
    padding: 12rpx;
}
.temp_flag {
    position: absolute;
    right: 0;
    top: 0;
    background-color: #c5c6c6;
    color: #fff;
    font-size: 20rpx;
    padding: 4rpx 16rpx;
    border-radius: 0 16rpx 0 16rpx;
}
.base-status-gap-1 {
    font-size: 24rpx;
    color: #fff;
    font-weight: 500;
    background-image: linear-gradient(to right, #37a954, #a4d14e);
    padding: 6rpx 24rpx 6rpx 16rpx;
    border-radius: 0 20rpx 20rpx 0;
}
.base-status-gap-2 {
    font-size: 24rpx;
    color: #fff;
    font-weight: 500;
    background: rgba(#fc333f, 0.8);
    padding: 6rpx 24rpx 6rpx 16rpx;
    border-radius: 0 20rpx 20rpx 0;
}
.base-status-gap-0 {
    font-size: 24rpx;
    color: #fff;
    font-weight: 500;
    background: rgba(#ffad11, 0.8);
    padding: 6rpx 24rpx 6rpx 16rpx;
    border-radius: 0 20rpx 20rpx 0;
}
</style>
