<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="150px">
                        <el-form-item label="耗材分类" prop="suppliesCategoryId">
                            <el-cascader v-model="queryParams.suppliesCategoryList" :options="categoryOptions" :props="{
                                    checkStrictly: true,
                                    emitPath: true,
                                    value: 'value',
                                    label: 'label',
                                    children: 'children'
                                }" placeholder="请选择" clearable filterable style="width: 200px" />
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="queryParams.suppliesName" placeholder="请输入名称/编码" clearable @keyup.enter="handleQuery" style="margin-left: 30px" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['warehouse:suppliesManage:add']">新增耗材</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain @click="handleImport" v-hasPermi="['warehouse:suppliesManage:import']">导入</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain @click="handleExport" v-hasPermi="['warehouse:suppliesManage:export']">导出</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain @click="downLoadTemplate" v-hasPermi="['warehouse:suppliesManage:export']">下载模板</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain @click="openBatchSetDialog">批量设置</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="manageList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="耗材名称" align="center" prop="suppliesName" />
                <el-table-column label="商品编码" align="center" prop="suppliesCode" />
                <el-table-column label="耗材分类" align="center">
                    <template #default="{ row }">
                        {{ getCategoryName(row.suppliesCategoryId) }}
                    </template>
                </el-table-column>
                <el-table-column label="规格" align="center">
                    <template #default="scope">
                        {{ scope.row.suppliesSpec}}{{ product_spec_unit.find(item => item.value === scope.row.suppliesSpecUnit)?.label || '--' }}/{{ product_package_unit.find(item => item.value === scope.row.suppliesUnit)?.label || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="许可证临期提醒" align="center" prop="licenseExpiryReminder" width="180">
                    <template #default="scope">
                        <span v-if="scope.row.licenseExpiryReminder > 0">{{ scope.row.licenseExpiryReminder + '个月' }}</span>
                        <span v-else>{{ '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="保质期临期提醒" align="center" prop="shelfLifeReminder" width="180">
                    <template #default="scope">
                        <span>{{ scope.row.shelfLifeReminder }}个月</span>
                    </template>
                </el-table-column>
                <el-table-column label="上架状态" align="center" prop="putFlag" width="100">
                    <template #default="{ row }">
                        {{ put_flag.find(item => item.value === row.putFlag)?.label || row.putFlag }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
                    <template #default="scope">
                        <el-button v-if="scope.row.putFlag === '1'" link type="danger" @click="handlePutFlag(scope.row, '0')">下架</el-button>
                        <el-button v-else link type="success" @click="handlePutFlag(scope.row, '1')">上架</el-button>
                        <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
            <el-dialog title="批量设置" v-model="batchSetDialogVisible" width="400px" append-to-body>
                <el-form :model="batchSetForm" label-width="120px" :rules="rules">
                    <el-form-item label="保质期临期提醒" prop="shelfLifeReminder">
                        <el-input v-model="batchSetForm.shelfLifeReminder" min="1" placeholder="请输入" style="width: 200px;">
                            <template #append>个月</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="许可证临期提醒" prop="licenseExpiryReminder">
                        <el-input v-model="batchSetForm.licenseExpiryReminder" min="1" placeholder="请输入" style="width: 200px;">
                            <template #append>个月</template>
                        </el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button type="primary" @click="handleBatchSetSubmit">提交</el-button>
                    <el-button @click="batchSetDialogVisible = false">取消</el-button>
                </template>
            </el-dialog>
            <!-- 上传excel -->
            <el-dialog :title="dialogFile.title" v-model="dialogFile.visible" width="700px" append-to-body>
                <el-upload drag :action="uploadFileUrl" :headers="headers" :file-list="fileList" accept=".xlsx,.xls" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" :on-error="handleUploadError">
                    <el-icon class="el-icon--upload">
                        <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">
                        将文件拖到此处，或 <em>点击上传</em>
                    </div>
                </el-upload>
                <div class="el-upload__tip">
                    请上传 .xls , .xlsx 标准格式文件
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup name="SuppliesManage" lang="ts">
    import { ref, reactive, onMounted, getCurrentInstance, type ComponentInternalInstance } from 'vue';
    import { listSuppliesManage, delSuppliesManage, batchUpdateSuppliesManage, updateSuppliesManage } from '@/api/warehouse/suppliesManage';
    import { SuppliesManageVO, SuppliesManageQuery } from '@/api/warehouse/suppliesManage/types';
    import { listSuppliesCategory } from '@/api/warehouse/suppliesCategory';
    import { useRouter } from 'vue-router';
    import { globalHeaders } from '@/utils/request';
    import type { FormInstance } from 'element-plus';

    import { listSupplier } from '@/api/warehouse/productSupplier'
    import { listManufacturer } from '@/api/warehouse/productManufacturer'

    import type { SupplierQuery } from '@/api/warehouse/productSupplier/types';
    import type { ManufacturerQuery } from '@/api/warehouse/productManufacturer/types';

    const router = useRouter();
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { product_package_unit, put_flag, product_spec_unit } = toRefs < any > (proxy ?.useDict('product_package_unit', 'put_flag', 'product_spec_unit'));

    const manageList = ref < SuppliesManageVO[] > ([]);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref < Array < string | number >> ([]);
    const fileList = ref < any[] > ([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const headers = ref(globalHeaders());
    const batchSetDialogVisible = ref(false);
    const baseUrl = import.meta.env.VITE_APP_BASE_API;
    const uploadFileUrl = ref(baseUrl + '/warehouse/suppliesManage/importExcel');
    const dialogFile = reactive < DialogOption > ({
        visible: false,
        title: '请上传'
    });

    const rules = {
        shelfLifeReminder: [{ required: true, message: "保质期临期提醒不能为空", trigger: "blur" }],
        licenseExpiryReminder: [{ required: true, message: "许可证临期提醒不能为空", trigger: "blur" }],

    };

    interface ManufacturerOption {
        value: string | number;
        label: string;
    }

    // 分类选项
    const categoryOptions = ref < any[] > ([]);

    const queryFormRef = ref < FormInstance > ();

    const productSupplierList = ref < ManufacturerOption[] > ([]);

    const productManufacturerList = ref < ManufacturerOption[] > ([]);

    const queryParams = reactive < SuppliesManageQuery > ({
        pageNum: 1,
        pageSize: 10,
        suppliesName: '',
        suppliesCategoryId: '',
        suppliesCategoryList: [],
    });
    const batchSetForm = reactive({
        shelfLifeReminder: '',
        licenseExpiryReminder: ''
    });
    /** 查询耗材管理列表 */
    const getList = async () => {
        loading.value = true;
        try {
            const res = await listSuppliesManage(queryParams);
            manageList.value = res.rows;
            total.value = res.total;
        } finally {
            loading.value = false;
        }
    };

    /** 搜索按钮操作 */
    const handleQuery = () => {
        // 取最后一级分类ID传给后端
        if (queryParams.suppliesCategoryList && queryParams.suppliesCategoryList.length) {
            queryParams.suppliesCategoryId = queryParams.suppliesCategoryList.slice(-1)[0];
        } else {
            queryParams.suppliesCategoryId = undefined;
        }
        queryParams.pageNum = 1;
        getList();
    };

    onMounted(async () => {
        getList();
        getSupplierList(); // 初始化时加载供应商数据
        getManufacturerList(); // 初始化时加载厂商数据
        const res = await listSuppliesCategory();
        categoryOptions.value = buildCategoryTree(res.rows || []);
    });

    function openBatchSetDialog() {
        if (!ids.value.length) {
            proxy ?.$modal.msgWarning('请先选择要批量设置的产品');
            return;
        }
        batchSetForm.shelfLifeReminder = '';
        batchSetForm.licenseExpiryReminder = '';
        batchSetDialogVisible.value = true;
    };
    async function handleBatchSetSubmit() {
        const params = {
            ids: ids.value,
            shelfLifeReminder: batchSetForm.shelfLifeReminder,
            licenseExpiryReminder: batchSetForm.licenseExpiryReminder
        };

        try {
            await batchUpdateSuppliesManage(params);
            proxy ?.$modal.msgSuccess('批量设置成功');
            batchSetDialogVisible.value = false;
            getList();
        } catch (e) {
            proxy ?.$modal.msgError('批量设置失败');
        }
    }
    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        queryParams.suppliesCategoryList = [];
        queryParams.suppliesName = undefined;
        handleQuery();
    };
    /** 获取生产厂商列表 */
    const getManufacturerList = async () => {
        try {
            const params: ManufacturerQuery = {
                pageNum: 1,
                pageSize: 10,
                name: undefined,
                params: {}
            };
            const res = await listManufacturer(params);
            productManufacturerList.value = res.rows.map(item => ({
                value: item.id,
                label: item.name
            }));
        } catch (error) {
            proxy ?.$modal.msgError("获取生产厂商列表失败");
            console.error("获取生产厂商列表失败:", error);
        }
    }

    /** 获取供应商列表 */
    const getSupplierList = async () => {
        try {
            const params: SupplierQuery = {
                pageNum: 1,
                pageSize: 10,
                name: undefined,
                params: {}
            };
            const res = await listSupplier(params);
            productSupplierList.value = res.rows.map(item => ({
                value: item.id,
                label: item.name
            }));
        } catch (error) {
            proxy ?.$modal.msgError("获取供应商列表失败");
            console.error("获取供应商列表失败:", error);
        }
    }


    /** 新增按钮操作 */
    const handleAdd = () => {
        router.push({
            path: '/warehouse/suppliesAddOrEdit',
            query: {
                productSupplierList: JSON.stringify(productSupplierList.value), // 序列化数组数据
                productManufacturerList: JSON.stringify(productManufacturerList.value), // 序列化数组数据
            },
        });
    };

    /** 导入按钮操作 */
    const handleImport = () => {
        dialogFile.visible = true;
        fileList.value = [];
    };

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy ?.download('warehouse/suppliesManage/export', {
            ...queryParams
        }, `suppliesManage_${new Date().getTime()}.xlsx`);
    };

    /** 下载模板按钮操作 */
    const downLoadTemplate = () => {
        proxy ?.getDownload('warehouse/suppliesManage/downLoadTemplate', {}, `耗材模版.xlsx`)
    }

    // 上传失败
    const handleUploadError = () => {
        proxy ?.$modal.msgError('上传Excel失败');
        proxy ?.$modal.closeLoading();
    };

    // 上传成功回调
    const handleUploadSuccess = (res: any, file: UploadFile) => {
        if (res.code === 200) {
            dialogFile.visible = false;
            fileList.value = [];
            proxy ?.$modal.closeLoading();
            getList();
        } else {
            proxy ?.$modal.msgError(res.msg);
            proxy ?.$modal.closeLoading();
        }
        fileList.value = [];
    };


    /** 上传前loading加载 */
    const handleBeforeUpload = (file: any) => {
        const isLt = file.size / 1024 / 1024 < 10;
        if (!isLt) {
            proxy ?.$modal.msgError(`上传文件大小不能超过10MB!`);
            return false;
        }
        proxy ?.$modal.loading('正在上传文件，请稍候...');
        return true;
    };

    /** 获取分类名称 */
    const getCategoryName = (categoryIds) => {
        if (!categoryIds) return '--';

        // 处理多个分类ID的情况
        const ids = categoryIds.toString().split(',');
        const categoryNames = ids.map(id => {
            const findCategory = (categories, targetId) => {
                for (const category of categories) {
                    if (category.value.toString() === targetId.toString()) {
                        return category.label;
                    }
                    if (category.children) {
                        const found = findCategory(category.children, targetId);
                        if (found) return found;
                    }
                }
                return null;
            };
            return findCategory(categoryOptions.value, id);
        }).filter(name => name !== null);

        return categoryNames.length > 0 ? categoryNames.join('/') : '--';
    };

    function buildCategoryTree(flatList: any[]) {
        const idMap: Record < string, any > = {};
        const tree = [];
        flatList.forEach((item) => {
            idMap[item.categoryId] = {
                label: item.categoryName,
                value: item.categoryId,
                children: []
            };
        });
        flatList.forEach((item) => {
            if (item.parentId && item.parentId !== 0 && idMap[item.parentId]) {
                idMap[item.parentId].children.push(idMap[item.categoryId]);
            } else if (item.parentId === 0) {
                tree.push(idMap[item.categoryId]);
            }
        });
        // 去除没有children的children字段
        function clean(node: any) {
            if (node.children && node.children.length === 0) {
                delete node.children;
            } else if (node.children) {
                node.children.forEach(clean);
            }
        }
        tree.forEach(clean);
        return tree;
    }

    // 上下架切换
    const handlePutFlag = async (row: SuppliesManageVO, flag: string) => {
        await proxy ?.$modal.confirm(`是否确认${flag === '1' ? '上架' : '下架'}该耗材？`);
        const updateData = { ...row, putFlag: flag };
        await updateSuppliesManage(updateData);
        proxy ?.$modal.msgSuccess(`${flag === '1' ? '上架' : '下架'}成功`);
        await getList();
    };

    /** 查看详情 */
    const handleDetail = (row: SuppliesManageVO) => {
        router.push({
            path: `/warehouse/suppliesManageDetail/${row.id}`,
            query: {
                productSupplierList: JSON.stringify(productSupplierList.value), // 序列化数组数据
                productManufacturerList: JSON.stringify(productManufacturerList.value), // 序列化数组数据
            },
        });
    };

    /** 多选框选中数据 */
    const handleSelectionChange = (selection: SuppliesManageVO[]) => {
        ids.value = selection.map((item) => item.id);
        single.value = selection.length !== 1;
        multiple.value = !selection.length;
    };
</script>