<template>
    <my-layout>
        <layout-item class="bg-white">
            <div class="py-5px flex" @keyup.enter="search()">
                <expand-filter-box v-model:can-expand="canExpand" :enable-expand="false" class="flex-grow"
                    :expand="expand">
                    <input-filter v-model="queryForm.drugName" label="药品名称" placeholder="输入搜索内容" :width="240" />

                    <date-range-filter v-model:dates="queryForm.dates" label="登记时间" :text="dateText" :width="240"
                        :showShortcuts="false" />
                    <check-box-filter v-model="queryForm.regTypes" label="登记来源" :list="regTypeList" :width="240" />

                    <!-- <custom-filter label="缺货药品库" :width="300">
                        <el-select v-model="queryForm.storeId" class="w-full" placeholder="全部" clearable>
                            <el-option label="全部" value="" />
                            <el-option label="配送药品库" value="1" />
                            <el-option label="药店药品库" value="2" />
                        </el-select>
                    </custom-filter> -->
                </expand-filter-box>
                <div class="flex-shrink-0 flex items-center h-40px pr-15px">
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button plain @click="clear()">重置</el-button>
                    <el-button type="success" @click="exportExcel">导出Excel</el-button>
                </div>
            </div>
        </layout-item>
        <layout-main :scroll="false">
            <el-table v-loading="loading" border ref="tableRef" height="100%" :data="list">
                <el-common-column prop="createTime" label="登记时间" :width="160" />
                <el-common-column prop="drugName" label="药品名称" min-width="160" show-overflow-tooltip />
                <!-- <el-common-column prop="spec" label="规格" :width="100" />
                <el-common-column prop="manufacturer" label="厂家" :width="120" show-overflow-tooltip /> -->
                <el-common-column prop="insuranceCode" label="医保编码" :min-width="230" />
                <el-common-column prop="attachmentCount" label="附件" :width="80">
                    <template #default="{ row }">
                        <el-text v-if="row.attachmentCount > 0" type="primary" class="cursor-pointer"
                            @click="viewAttachments(row)">
                            {{ row.attachmentCount }}
                        </el-text>
                        <span v-else>—</span>
                    </template>
                </el-common-column>
                <el-common-column prop="remark" label="备注说明" min-width="100" show-overflow-tooltip />
                <!-- <el-common-column prop="storeName" label="缺货药品库" :min-width="120" /> -->
                <el-common-column prop="patientName" label="关联患者" :min-width="100">
                    <template #default="{ row }">
                        <el-text type="primary" class="cursor-pointer" @click="viewPatient(row)">{{ row.patientName
                            }}</el-text>
                    </template>
                </el-common-column>
                <el-common-column prop="phone" label="联系电话" :width="120" />
                <el-common-column prop="phone" label="登记来源" :width="120">
                    <template #default="{ row }">
                        {{ regType[row.regType]||'' }}
                    </template>
                </el-common-column>
            </el-table>
        </layout-main>
        <layout-item>
            <pagination :totalRow="total" :pageSize="pageSize" :currentPage="page" @handle-size-change="changeSize"
                @handle-current-change="changePage" />
        </layout-item>
    </my-layout>
    <el-image-viewer v-if="imageViewerVisible" :url-list="imageList" :initial-index="imageIndex"
        @close="imageViewerVisible = false" />
    <archive-drawer :patient="currentPatient || {}" :visible="archiveVisible" @close="archiveVisible = false" />
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { dayjs, ElMessage } from "element-plus";
import useElPagination from "@/hooks/useElPagination";
import { getLackMedicineList, downloadLackMedicineExcel, getOrderPatientList } from "@/api/hlw";
import { InputFilter, expandFilterBox, CustomFilter, DateRangeFilter, CheckBoxFilter } from "@/components/filter-bar";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import pagination from "@/components/pagination/pagination.vue";
import elCommonColumn from "@/components/el-common-column/el-common-column.vue";
import archiveDrawer from "@/components/archive-drawer/archive-drawer.vue";

const regType = {
    outOfStock: '药品未入库',//缺货
    lowStock: '药品库存不足',//库存不足
    report: '患者自主登记'// 自主登记
}
const regTypeList = Object.keys(regType).map(key => ({ label: regType[key], value: key }));

const { list, page, pageSize, total, changePage, changeSize } = useElPagination(fetchData);

const queryForm = ref({
    drugName: "",
    storeId: "1",
    dates: [],
    regTypes: []
});

const canExpand = ref(false);
const expand = ref(false);
const loading = ref(false);
const imageViewerVisible = ref(false);
const imageList = ref([]);
const imageIndex = ref(0);
const archiveVisible = ref(false);
const currentPatient = ref({});

const dateText = computed(() =>
    queryForm.value.dates && queryForm.value.dates.length > 0
        ? `${queryForm.value.dates[0]} - ${queryForm.value.dates[1]}`
        : "全部"
);

function clear() {
    queryForm.value = {
        drugName: "",
        storeId: "1",
        dates: [],
        regTypes: []
    };
    search();
}

function search() {
    page.value = 1;
    fetchData();
}

function exportExcel() {
    const params = {};

    if (queryForm.value.drugName) {
        params.drugName = queryForm.value.drugName.trim();
    }
    if (queryForm.value.regTypes) {
        params.regTypes = queryForm.value.regTypes
    }

    if (queryForm.value.storeId === "1") {
        params.inventory = "online";
    } else if (queryForm.value.storeId === "2") {
        params.inventory = "store";
    }

    if (Array.isArray(queryForm.value.dates) && queryForm.value.dates.length === 2) {
        params.startTime = queryForm.value.dates[0];
        params.endTime = queryForm.value.dates[1];
    }

    downloadLackMedicineExcel(params);
}

function viewAttachments(row) {
    const images = row && row.raw && Array.isArray(row.raw.images) ? row.raw.images : [];
    if (!images.length) return;
    imageList.value = images;
    imageIndex.value = 0;
    imageViewerVisible.value = true;
}

async function viewPatient(row) {
    const raw = row && row.raw ? row.raw : {};
    // 基础信息：用缺货登记里的数据兜底
    let patientData = {
        name: raw.patientName || "",
        mobile: raw.phone || "",
        patientId: raw.patientId || "",
        idCard: "",
        address: "",
        blhno: "",
        age: "",
        sex: "",
    };

    // 如果有任一条件（patientId / 姓名 / 手机），尝试从问诊订单侧补全档案信息
    const hasName = typeof raw.patientName === "string" && raw.patientName.trim() !== "";
    const hasMobile = typeof raw.phone === "string" && raw.phone.trim() !== "";
    const hasPatientId = typeof raw.patientId === "string" && raw.patientId.trim() !== "";

    // 优先 patientId，再退回到 姓名+手机号
    if (hasPatientId || hasMobile || hasName) {
        try {
            const query = {
                page: 1,
                pageSize: 1,
            };
            if (hasPatientId) {
                query.patientId = raw.patientId.trim();
            } else {
                // 兼容逻辑：按姓名+手机号查询
                if (hasName) {
                    query.name = raw.patientName.trim();
                }
                if (hasMobile) {
                    query.mobile = raw.phone.trim();
                }
            }

            const { success, data } = await getOrderPatientList(query);
            const list = success && data && Array.isArray(data.list) ? data.list : [];
            if (list.length > 0) {
                const p = list[0];
                patientData = {
                    name: p.name || patientData.name,
                    mobile: p.mobile || patientData.mobile,
                    // 用后端返回的 patientId 覆盖本地的
                    patientId: p.patientId || patientData.patientId,
                    idCard: p.idCard || "",
                    address: p.address || "",
                    blhno: p.blhno || "",
                    age: p.age || "",
                    sex: p.sex || "",
                };
            }
        } catch (e) {
            // 异常时保留缺货登记里的基础信息
        }
    }

    currentPatient.value = patientData;
    archiveVisible.value = true;
}


async function fetchData() {
    loading.value = true;
    try {
        const params = {
            page: page.value,
            pageSize: pageSize.value,
        };

        if (queryForm.value.drugName) {
            params.drugName = queryForm.value.drugName.trim();
        }
        if (queryForm.value.regTypes) {
            params.regTypes = queryForm.value.regTypes
        }

        // 缺货药品库筛选：1=配送药品库(online)，2=药店药品库(store)
        if (queryForm.value.storeId === "1") {
            params.inventory = "online";
        } else if (queryForm.value.storeId === "2") {
            params.inventory = "store";
        }

        if (Array.isArray(queryForm.value.dates) && queryForm.value.dates.length === 2) {
            params.startTime = queryForm.value.dates[0];
            params.endTime = queryForm.value.dates[1];
        }

        const { success, data, message } = await getLackMedicineList(params);
        if (!success) {
            ElMessage.error(message || "获取缺货登记列表失败");
            list.value = [];
            total.value = 0;
            return;
        }

        const payload = data || {};
        const rawList = Array.isArray(payload.data) ? payload.data : [];
        const totalCount = typeof payload.total === "number" ? payload.total : 0;

        list.value = rawList.map((item) => {
            const images = Array.isArray(item.images) ? item.images : [];
            return {
                id: item._id ? String(item._id) : "",
                createTime: item.createTime ? dayjs(item.createTime).format("YYYY-MM-DD HH:mm") : "",
                drugName: item.drugName || "",
                spec: item.spec || "",
                manufacturer: item.manufacturer || "",
                insuranceCode: item.insuranceCode || "",
                attachmentCount: images.length,
                remark: item.description || "",
                storeName: item.inventory === "store" ? "药店药品库" : "配送药品库",
                patientName: item.patientName || "",
                phone: item.phone || "",
                raw: item,
                regType: item.regType || "",
            };
        });

        total.value = totalCount;
    } finally {
        loading.value = false;
    }
}

onMounted(() => {
    search();
});
</script>

<style scoped></style>
