<template>
    <z-paging ref="paging" v-model="list" bgColor="#fff" @query="query" :auto="false" safe-area-inset-bottom>
        <template #top>
            <view class="">
                <up-navbar :title="title" @leftClick="navigateBackOrHome()" :fixed="false"></up-navbar>
                <view class="pd-20">
                    <ut-search ref="searchRef" v-model="form.medicineName" @search="changeSeach" @change="changeSeach" margin="0" :border="false" :placeholder="placeholder" bgColor="#f7f7f7" height="86rpx" borderRadius="16rpx"></ut-search>
                </view>
            </view>
        </template>
        <template v-if="list.length == 0 && !form.medicineName.trim()">
            <view class="pd-20">
                <view class="f-s-32 c-333 f-w-5 mb-20">已配置的主营品种</view>
                <!-- speLable 组件使用示例 -->
                <view class="d-flex a-c f-w-w">
                    <spe-lable class="mr-20 mb-20" v-for="(item, index) in speArray" :key="index" :text="item?.medicineName" size="30rpx" :id="item?.id" @close="() => handleLabelClose(item?.id)" />
                </view>
                <ut-empty class="mg-at" v-if="speArray.length == 0">
                    <view class="d-flex a-c j-c f-s-28 c-ccc">暂未配置单位主营品种 </view>
                    <view class="d-flex a-c j-c f-s-28 c-ccc">点击上方搜索框搜索后添加~</view>
                </ut-empty>
            </view>
        </template>
        <template v-for="(item, index) in list" :key="index">
            <spe-list :text="item?.medicineName" :searchText="form.medicineName" :check="item?.isChoice" @update:check="(value) => handleCheckChange(value, item?.medicineCode)"> </spe-list>
        </template>
        <template #empty>
            <ut-empty class="mg-at">
                <view class="d-flex a-c j-c f-s-28 c-ccc">暂未搜索到该品种</view>
            </ut-empty>
        </template>
        <template #bottom v-if="form.medicineName.trim()">
            <view class="base-bottom-wrap pd-20 pb-0">
                <up-button type="primary" @click="subMit">确认</up-button>
            </view>
        </template>
    </z-paging>
    <ut-confirm-dialog v-model:show="showDeleteDialog" title="删除确认" :confirmText="'删除'" :cancelText="'取消'" @confirm="handleDeleteConfirm" @cancel="handleDeleteCancel">
        <text>确定要删除这个品种吗？删除后不可恢复。</text>
    </ut-confirm-dialog>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import speLable from '../models/speLable.vue';
import SpeList from '../models/speList.vue';

interface ListItem {
    rows: SpeArrayItem[];
    code: number;
    msg: string;
    total: number;
}
//定义speArray
interface SpeArrayItem {
    id: number;
    abbreviation?: string;
    createdTime: string | null;
    creator: string | null;
    delFlag: number;
    genusLatinName: string;
    genusName: string;
    isChoice: string; // 或改为 boolean
    latinName: string;
    medicineName: string;
    modifier: string | null;
    sourceType: number;
    updateTime: string | null;
    medicineCode?: string | null;
}

const list = ref<SpeArrayItem[]>([]);
const paging = ref();
const title = ref('配置单位主营品种');
const placeholder = ref('请搜索药材品种名称选择添加');
const form = ref({
    medicineName: '',
});
const speArray = ref<any[]>([]);
// 删除确认相关状态
const showDeleteDialog = ref(false);
const currentDeleteId = ref<number | null>(null);
const getSpecies = async () => {
    const res = await useClientRequest.get('/plt-api/app/cpyVariety/list');
    if (res.code === 200) {
        speArray.value = res.data;
        speArray.value.forEach((item) => {
            item.isChoice = '1';
        });
    }
};
// 处理标签关闭事件
const handleLabelClose = (id: string | number) => {
    currentDeleteId.value = id as number;
    showDeleteDialog.value = true;
};
const handleCheckChange = (newCheckValue: string, medicineCode: string | null) => {
    // 根据ID找到对应的列表项并更新
    const item = list.value.find((item) => item.medicineCode === medicineCode);
    if (item) {
        item.isChoice = newCheckValue;
    }
    speArray.value = speArray.value.filter((item) => item.medicineCode !== medicineCode);
    console.log(speArray.value, 'speArray.value');
};
const query = async (pageNum: number, pageSize: number) => {
    const params = {
        pageNum,
        pageSize,
        ...form.value,
    };
    if (!params.medicineName?.trim()) {
        // 处理空、null、undefined、纯空格的情况
        return;
    }
    // const res = await cpyList(params);
    const res: ListItem = await useClientRequest.get<ListItem>('/plt-api/app/medicine/pageList', params);
    const { rows } = res;
    // 给列表项添加 isChoice 属性
    paging.value.complete(rows);
};
const changeSeach = () => {
    paging.value.reload();
};
const onRefresh = () => {
    paging.value.reload();
};
const subMit = async () => {
    // 方法1：使用 Set 避免重复，更高效
    const existingIds = new Set(speArray.value.map((speItem) => speItem.medicineCode));
    list.value.forEach((item) => {
        console.log(item);
        if (item.isChoice === '1' && !existingIds.has(item.medicineCode)) {
            speArray.value.push({ medicineName: item?.medicineName, medicineCode: item?.medicineCode, isChoice: '1' });
        }
    });
    console.log(speArray.value, 'speArray.value');

    // 直接使用过滤后的 speArray 中的所有 id
    await useClientRequest.post('/plt-api/app/cpyVariety/add', {
        medicineCodes: speArray.value.map((item) => item.medicineCode),
    });

    form.value.medicineName = '';
    onRefresh();
    getSpecies();
};

// 处理删除确认
const handleDeleteConfirm = async () => {
    if (currentDeleteId.value !== null) {
        await useClientRequest.get(`/plt-api/app/cpyVariety/delById/${currentDeleteId.value}`);
        getSpecies();
    }
    showDeleteDialog.value = false;
    currentDeleteId.value = null;
};

// 处理删除取消
const handleDeleteCancel = () => {
    showDeleteDialog.value = false;
    currentDeleteId.value = null;
};
onMounted(() => {
    getSpecies();
});
</script>
