<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">

                        <el-form-item label="营养评估类型" prop="configId" label-width="100px">
                            <div>
                                <el-select v-model="queryParams.configId" placeholder="请选择" clearable>
                                    <el-option v-for="item in screeningAssessmentConfigList" :key="item.configId" :label="item.name" :value="item.configId" />
                                </el-select>
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="evaluationList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="营养评估时间" align="center" prop="screeningTime" />
                <el-table-column label="营养评估类型" align="center" prop="configName" />
                <el-table-column label="营养评估分数" align="center" prop="">
                    <template>
                        <span>{{ '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="营养评估结论" align="center" prop="">
                    <template>
                        <span>{{ '--' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="筛查医生/护士" align="center" prop="createByName" />
                <!-- <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="View" @click="handleView(scope.row)" v-hasPermi="['system:evaluation:edit']">详情</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="Evaluation" lang="ts">
    import { listEvaluation, getEvaluation, delEvaluation, addEvaluation, updateEvaluation } from '@/api/patients/evaluation';
    import { EvaluationVO, EvaluationQuery, EvaluationForm } from '@/api/patients/evaluation/types';
    import { ScreeningAssessmentConfigQuery, ScreeningAssessmentConfigVO } from '@/api/system/screeningAssessmentConfig/types';
    import { listScreeningAssessmentConfig } from '@/api/system/screeningAssessmentConfig';

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

    const screeningTime = ref < [DateModelType, DateModelType] > (['', '']);
    const screeningAssessmentConfigList = ref < ScreeningAssessmentConfigVO[] > ([]);
    const evaluationList = ref < EvaluationVO[] > ([]);
    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 queryFormRef = ref < ElFormInstance > ();
    const evaluationFormRef = ref < ElFormInstance > ();
    const emit = defineEmits(['change'])

    const dialog = reactive < DialogOption > ({
        visible: false,
        title: ''
    });

    const initFormData: EvaluationForm = {
        id: undefined,
        patientId: undefined,
        configId: undefined,
        screeningTime: undefined,
        visitType: undefined,
        patientNo: undefined,
        paymentStatus: undefined,
        content: undefined,
        status: undefined,
    }
    const data = reactive < PageData < EvaluationForm,
        EvaluationQuery >> ({
            form: { ...initFormData },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                patientId: undefined,
                configId: undefined,
                screeningTime: undefined,
                visitType: undefined,
                patientNo: undefined,
                paymentStatus: undefined,
                content: undefined,
                status: undefined,
                params: {}
            },
            rules: {
                id: [
                    { required: true, message: "主键ID不能为空", trigger: "blur" }
                ],
                configId: [
                    { required: true, message: "营养评估类型不能为空", trigger: "blur" }
                ],
                screeningTime: [
                    { required: true, message: "筛查时间不能为空", trigger: "blur" }
                ],
                visitType: [
                    { required: true, message: "看诊类型不能为空", trigger: "change" }
                ],
                patientNo: [
                    { required: true, message: "门诊/住院号不能为空", trigger: "blur" }
                ],
            }
        });

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

    /** 查询筛查/评估配置列表 */
    const getScreeningConfigList = async () => {
        let param = ref < ScreeningAssessmentConfigQuery > ({
            pageNum: 1,
            type: '2',
            pageSize: -1,
        });
        const res = await listScreeningAssessmentConfig(param.value);
        screeningAssessmentConfigList.value = res.rows;
    }

    /** 查询营养评估列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listEvaluation(queryParams.value);
        evaluationList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }

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

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        evaluationFormRef.value ?.resetFields();
    }

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

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value ?.resetFields();
        handleQuery();
    }

    /** 多选框选中数据 */
    const handleSelectionChange = (selection: EvaluationVO[]) => {
        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 ? : EvaluationVO) => {
        reset();
        const _id = row ?.id || ids.value[0]
        const res = await getEvaluation(_id);
        Object.assign(form.value, res.data);
        dialog.visible = true;
        dialog.title = "修改营养评估";
    }

    /** 提交按钮 */
    const submitForm = () => {
        evaluationFormRef.value ?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.id) {
                    await updateEvaluation(form.value).finally(() => buttonLoading.value = false);
                } else {
                    await addEvaluation(form.value).finally(() => buttonLoading.value = false);
                }
                proxy ?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
            }
        });
    }

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

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy ?.download('system/evaluation/export', {
            ...queryParams.value
        }, `evaluation_${new Date().getTime()}.xlsx`)
    }

    const handleView = async (row ? : EvaluationVO) => {
        emit('change', 'nutritionEvaluationAdd', window.btoa(row.id.toString()))
    }

    const handleScreeningSelect = (configId: number) => {
        emit('change', 'nutritionEvaluationAdd', configId)
    }

    function formatDate(date) {
        const pad = n => n < 10 ? '0' + n : n;
        return date.getFullYear() + '-' +
            pad(date.getMonth() + 1) + '-' +
            pad(date.getDate());
    }

    onMounted(() => {
        getList();

        getScreeningConfigList();
        let now = new Date();
        let start = formatDate(now);
        let end = formatDate(new Date(now.getTime() - 24 * 60 * 60 * 1000 * 30));
        screeningTime.value = [end + ' 00:00:00', start + ' 23:59:59'];
    });
</script>

<style scoped>
    .screening-type-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
    }

    .screening-type-btn {
        font-weight: normal;
        font-size: 16px;
        height: 48px;
        border-radius: 8px;
    }
</style>