<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="120px">
                        <el-form-item label="推荐时间：">
                            <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </el-form-item>
                        <el-form-item label="看诊类型：">
                            <el-select v-model="queryParams.type" class="spec-unit-select">
                                <el-option v-for="dict in treatment_user_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-input v-model="queryParams.searchValue" placeholder="门诊号/住院号/医生" style="width: 240px; " clearable />
                        </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="emit('addDaily')" v-hasPermi="['patients:dailyMealPlan:add']">新增日常膳食</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="mealPlanList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="推荐时间" align="center" prop="createTime" />
                <el-table-column label="看诊类型" align="center" prop="type">
                    <template #default="scope">
                        <span>{{getDictLabel(treatment_user_type ,scope.row.type )|| '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="门诊/住院号" align="center" prop="outpatientNo" />
                <el-table-column label="推荐医生" align="center" prop="createByUser" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['patients:dailyMealPlan:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['patients:dailyMealPlan:remove']"></el-button>
                        </el-tooltip>
                    </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-card>

    </div>
</template>

<script setup name="MealPlan" lang="ts">
    import { listDailyMealPlan, getMealPlan, delMealPlan, addMealPlan, updateMealPlan } from '@/api/patients/dailyMealPlan';
    import { MealPlanVO, MealPlanQuery, MealPlanForm } from '@/api/patients/dailyMealPlan/types';

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { treatment_user_type } = toRefs < any > (proxy ?.useDict('treatment_user_type'));

    const mealPlanList = ref < MealPlanVO[] > ([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref < Array < string | number >> ([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const emit = defineEmits(['addDaily']);

    const queryFormRef = ref < ElFormInstance > ();
    const mealPlanFormRef = ref < ElFormInstance > ();

    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });
    const props = defineProps({
        patientInfo: {
            type: Object,
            required: true,
            default: () => ({
                id: '',
                name: '',
                age: '',
                gender: ''
            })
        }
    });

    const initFormData: MealPlanForm = {
        id: undefined,
        type: props.patientInfo.type,
        patientId: props.patientInfo.id,
        outpatientNo: props.patientInfo.outpatientNo,
        deptId: props.patientInfo.deptId,
        recommendStartDate: undefined,
        recommendEndDate: undefined,
        status: undefined,
        remark: undefined,
        mealRecipeList: [],
    }
    const data = reactive < PageData < MealPlanForm,
        MealPlanQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                type: undefined,
                patientId: props.patientInfo.id,
                outpatientNo: undefined,
                deptId: undefined,
                dateRange: [],
                searchValue: undefined,
                params: {}
            },
            rules: {
                id: [
                    { required: true, message: "主键不能为空", trigger: "blur" }
                ],
                patientId: [
                    { required: true, message: "患者ID不能为空", trigger: "blur" }
                ],
            }
        });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询日常膳食主列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listDailyMealPlan(queryParams.value);
        mealPlanList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }

    // 字典label工具
    function getDictLabel(dictList: any[], value: string) {
        if (!dictList || !Array.isArray(dictList)) return value || '--';
        const found = dictList.find(item => item.value === value);
        return found ? found.label : value || '--';
    }

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        mealPlanFormRef.value ?.resetFields();
        queryParams.value.dateRange = undefined;
        queryParams.value.type = undefined;
        queryParams.value.searchValue = undefined;
        queryParams.value.pageNum = 1;
        queryParams.value.pageSize = 10;
    }

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        queryParams.value.dateRange = undefined;
        queryParams.value.type = undefined;
        queryParams.value.searchValue = undefined;
        queryParams.value.pageNum = 1;
        queryParams.value.pageSize = 10;
        handleQuery();
    }

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

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        dialog.visible = true;
        dialog.title = "添加日常膳食";
    }

    /** 修改按钮操作 */
    const handleUpdate = async (row ? : MealPlanVO) => {
        reset();
        const _id = row ?.id || ids.value[0]
        const res = await getMealPlan(_id);
        Object.assign(form.value, res.data);
        dialog.visible = true;
        dialog.title = "修改日常膳食";
    }

    /** 提交按钮 */
    const submitForm = (mealPlanForm) => {

        console.log('------' + mealPlanForm);

        form.value.recommendStartDate = mealPlanForm.mealTimeRange[0];
        form.value.recommendEndDate = mealPlanForm.mealTimeRange[1];
        form.value.mealRecipeList = mealPlanForm.mealRecipeList;
        addMealPlan(form.value).finally(() => buttonLoading.value = false);
        getList();
        mealPlanFormRef.value ?.validate(async (valid: boolean) => {
            if (true) {
                form.value.recommendStartDate = mealPlanForm.mealTimeRange[0];
                form.value.recommendEndDate = mealPlanForm.mealTimeRange[1];
                form.value.mealRecipeList = mealPlanForm.mealRecipeList;
                buttonLoading.value = true;
                if (form.value.id) {
                    await updateMealPlan(form.value).finally(() => buttonLoading.value = false);
                } else {
                    await addMealPlan(form.value).finally(() => buttonLoading.value = false);
                }
                proxy ?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
            }
        });
    }

    defineExpose({ submitForm });

    /** 删除按钮操作 */
    const handleDelete = async (row ? : MealPlanVO) => {
        const _ids = row ?.id || ids.value;
        await proxy ?.$modal.confirm('是否确认删除日常膳食主编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
        await delMealPlan(_ids);
        proxy ?.$modal.msgSuccess("删除成功");
        await getList();
    }

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