<template>
    <page-layer>
        <template #header>
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" :shortcuts="shortcuts"> </el-date-picker>
            <el-autocomplete v-model="dept" value-key="name" :fetch-suggestions="querySearchDept"
                :trigger-on-focus="false" clearable class="inline-input w-50 m-2" style="width: 200px"
                placeholder="请输入关键字" @select="handleSelect">
                <template #prepend>科室</template>
            </el-autocomplete>
            <el-select v-model="insurId" style="width: 180px" placeholder="请选择险种">
                <el-option label="长沙县城职普通住院" value="1"></el-option>
                <el-option label="长沙县城居普通住院" value="2"></el-option>
                <el-option label="浏阳市城职普通住院" value="3"></el-option>
                <el-option label="浏阳市城居普通住院" value="4"></el-option>
            </el-select>
            <el-button type="primary" icon="Search" @click="query" style="margin-left: 5px">查询</el-button>
            <el-button type="primary" icon="Download" @click="exportAvgFee" style="margin-left: 5px">导出</el-button>
        </template>
        <template #main>
            <el-row :gutter="6" style="text-align: center; padding-top: 10px">
                <el-col :span="6">险种：{{ returnData.insurName }}</el-col>
                <el-col :span="6">次均费用：{{ returnData.avgFee }}</el-col>
                <el-col :span="6">倍率：{{ returnData.avgRates }}</el-col>
                <el-col :span="6">单列：{{ returnData.dlFee }}</el-col>
            </el-row>
            <div style="margin: 5px 0; border-top: 1px solid gray"></div>
            <el-table :data="returnData.returnData" :height="tableHeight" highlight-current-row stripe show-summary
                :summary-method="getSummaries" @row-dblclick="dbClnAvgFeeYsData">
                <el-table-column prop="deptName" label="科室" align="left" width="160" fixed></el-table-column>
                <el-table-column prop="insurName" label="险种" align="left" width="120" fixed></el-table-column>
                <el-table-column prop="zfy" label="总费用" align="right"></el-table-column>
                <el-table-column prop="rs" label="结算人次" align="right"></el-table-column>
                <el-table-column prop="cjfy" label="次均费用" align="right"></el-table-column>
                <el-table-column prop="inDays" label="床日数" align="right"></el-table-column>
                <el-table-column prop="avgDays" label="平均住院天数" align="right"></el-table-column>
                <el-table-column prop="crf" label="床日费用" align="right"></el-table-column>
                <el-table-column prop="ypf" label="药品费" align="right"></el-table-column>
                <el-table-column prop="ypbl" label="药占比" align="right"></el-table-column>
                <el-table-column prop="zf" label="自付费用" align="right"></el-table-column>
                <el-table-column prop="zfbl" label="自付比" align="right"></el-table-column>
                <el-table-column prop="dlRs" label="单列人次" align="right"></el-table-column>
                <el-table-column prop="dlf" label="单列费用" align="right"></el-table-column>
                <el-table-column prop="bal" label="控制" align="right">
                    <template #default="scope">
                        <span v-if="scope.row.bal < 0" style="color: red">{{ scope.row.bal }}</span>
                        <span v-else>{{ scope.row.bal }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </page-layer>
    <el-dialog v-model="showDoctorAvgFee" :close-on-click-modal="false" :close-on-press-escape="false"
        :title="doctorDialogTitle" width="80%">
        <div style="width: 120px; height: 36px; position: absolute; top: 16px; right: 60px">
            <el-button icon="Download" type="primary" @click="exportAvgFeeDoctor">导出</el-button>
        </div>
        <el-table :data="doctorAvgFee" height="560" highlight-current-row stripe show-summary
            :summary-method="getSummaries" @row-dblclick="dbClnAvgFeeBrData">
            <el-table-column prop="deptName" label="科室" align="left" width="160" fixed></el-table-column>
            <el-table-column prop="doctor" label="医生" fixed></el-table-column>
            <el-table-column prop="insurName" label="险种" align="left" width="120" fixed></el-table-column>
            <el-table-column prop="zfy" label="总费用" align="right"></el-table-column>
            <el-table-column prop="rs" label="结算人次" align="right"></el-table-column>
            <el-table-column prop="cjfy" label="次均费用" align="right"></el-table-column>
            <el-table-column prop="inDays" label="床日数" align="right"></el-table-column>
            <el-table-column prop="avgDays" label="平均住院天数" align="right"></el-table-column>
            <el-table-column prop="crf" label="床日费用" align="right"></el-table-column>
            <el-table-column prop="ypf" label="药品费" align="right"></el-table-column>
            <el-table-column prop="ypbl" label="药占比" align="right"></el-table-column>
            <el-table-column prop="zf" label="自付费用" align="right"></el-table-column>
            <el-table-column prop="zfbl" label="自付比" align="right"></el-table-column>
            <el-table-column prop="dlRs" label="单列人次" align="right"></el-table-column>
            <el-table-column prop="dlf" label="单列费用" align="right"></el-table-column>
            <el-table-column prop="bal" label="控制" align="right">
                <template #default="scope">
                    <span v-if="scope.row.bal < 0" style="color: red">{{ scope.row.bal }}</span>
                    <span v-else>{{ scope.row.bal }}</span>
                </template>
            </el-table-column>
        </el-table>
    </el-dialog>
    <el-dialog v-model="showPatientAvgFee" :close-on-click-modal="false" :close-on-press-escape="false"
        :title="patientDialogTitle" width="80%">
        <div style="width: 120px; height: 36px; position: absolute; top: 16px; right: 60px">
            <el-button icon="Download" type="primary" @click="exportAvgFeePatient">导出</el-button>
        </div>
        <el-table :data="patientAvgFee" height="560" highlight-current-row stripe show-summary
            :summary-method="getSummaries">
            <el-table-column prop="deptName" label="科室" align="left" width="160" fixed></el-table-column>
            <el-table-column prop="doctor" label="医生" fixed></el-table-column>
            <el-table-column prop="insurName" label="险种" align="left" width="120" fixed></el-table-column>
            <el-table-column prop="xm" label="姓名"></el-table-column>
            <el-table-column prop="zyh" label="住院号"></el-table-column>
            <el-table-column prop="zfy" label="总费用" align="right"></el-table-column>
            <el-table-column prop="inDays" label="床日数" align="right"></el-table-column>
            <el-table-column prop="crf" label="床日费用" align="right"></el-table-column>
            <el-table-column prop="ypf" label="药品费" align="right"></el-table-column>
            <el-table-column prop="ypbl" label="药占比" align="right"></el-table-column>
            <el-table-column prop="zf" label="自付费用" align="right"></el-table-column>
            <el-table-column prop="zfbl" label="自付比" align="right"></el-table-column>
            <el-table-column prop="bal" label="控制" align="right">
                <template #default="scope">
                    <span v-if="scope.row.bal < 0" style="color: red">{{ scope.row.bal }}</span>
                    <span v-else>{{ scope.row.bal }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="jslx" label="结算类型"></el-table-column>
            <el-table-column prop="zyzd" label="主要诊断" align="left" width="180" show-overflow-tooltip></el-table-column>
            <el-table-column prop="zyss" label="主要手术" align="left" width="180" show-overflow-tooltip></el-table-column>
        </el-table>
    </el-dialog>
</template>

<script >
import PageLayer from "@/layout/PageLayer";
import { reactive, ref } from '@vue/reactivity'
import store from '@/store'
import { shortcuts, seltYearAndNowLast } from '@/data/shortcuts'
import { formatDate, getDateRangeFormatDate } from '@/utils/date'
import { selectSmallDept } from '@/api/medical-insurance/si-yb-util'
import { selectClnTimesAvg, selectClnAvgFeeDoctor, selectClnAvgFeePatient } from '@/api/ybkf/yb-clnavg.js'
import { Export } from '@/utils/ExportExcel'
import { clone } from '@/utils/clone'
export default {
    components: { PageLayer },
    setup() {
        const windowSize = store.state.app.windowSize;
        const tableHeight = windowSize.h / 1.06;
        const start = formatDate(seltYearAndNowLast[0].value[0]);
        const end = formatDate(seltYearAndNowLast[1].value[1]);
        const insurId = ref("");
        const dept = ref("");
        const queryTerm = reactive({
            startTime: "",
            endTime: "",
            insurName: "",
            dept: "",
        });
        onMounted(() => {
            queryTerm.startTime = start;
            queryTerm.endTime = end + " 23:59:59";
            dateRange.value = [start, end];
            insurId.value = "1";
        });
        const handleSelect = (item) => { };
        const querySearchDept = async (str, cb) => {
            let results = await selectSmallDept({ str });
            if (results) {
                // 调用 callback 返回建议列表的数据
                cb(results);
            }
        };
        const dateRange = ref([]);
        const returnData = ref([]);
        const query = () => {
            if (dateRange.value) {
                let dateS = getDateRangeFormatDate(dateRange.value);
                queryTerm.startTime = dateS.startTime;
                queryTerm.endTime = dateS.endTime;
            }
            else {
                queryTerm.startTime = start;
                queryTerm.endTime = end;
                ElMessage({
                    type: "info",
                    message: "默认查询本月的数据",
                    duration: 2500,
                    showClose: true,
                });
            }
            queryTerm.insurName = filterInsurName();
            queryTerm.dept = dept.value;
            selectClnTimesAvg(queryTerm)
                .then((res) => {
                    returnData.value = res;
                })
                .catch(() => {
                    returnData.value = [];
                });
            returnData.value = [];
        };
        // ---------------------------- 查询医生的次均费用 -----------------------------------------------------
        const showDoctorAvgFee = ref(false)
        const doctorAvgFee = ref([])
        const dbClnAvgFeeYsData = (row) => {
            let selectInfo = clone(queryTerm)
            selectInfo.dept = row.deptName;
            selectInfo.insurName = filterInsurName();
            selectClnAvgFeeDoctor(selectInfo)
                .then((res) => {
                    doctorAvgFee.value = res
                    showDoctorAvgFee.value = true
                })
                .catch(() => {
                    doctorAvgFee.value = []
                })
        }

        const doctorDialogTitle = computed(() => {
            return '长浏宁次均费用统计(医生)'
        })

        // ---------------------------- 查询病人的次均费用 -----------------------------------------------------
        const showPatientAvgFee = ref(false)
        const patientAvgFee = ref([])
        const dbClnAvgFeeBrData = (row) => {
            let selectInfo = clone(queryTerm)
            selectInfo.dept = row.deptName;
            selectInfo.doctor = row.doctor;
            selectInfo.insurName = filterInsurName();
            selectClnAvgFeePatient(selectInfo)
                .then((res) => {
                    patientAvgFee.value = res
                    showPatientAvgFee.value = true
                })
                .catch(() => {
                    patientAvgFee.value = []
                })
        }

        const patientDialogTitle = computed(() => {
            return '长浏宁次均费用统计(病人)'
        })

        const filterInsurName = () => {
            if (insurId.value == "1") {
                return "长沙县城职普通住院";
            }
            else if (insurId.value == "2") {
                return "长沙县城居普通住院";
            }
            else if (insurId.value == "3") {
                return "浏阳市城职普通住院";
            }
            else if (insurId.value == "4") {
                return "浏阳市城居普通住院";
            }
            else {
                return "";
            }
        };
        let sum = {
            deptName: "",
            insurName: "",
            zfy: "",
            rs: "",
            cjfy: "",
            inDays: "",
            avgDays: "",
            crf: "",
            ypf: "",
            ypbl: "",
            zf: "",
            zfbl: "",
            dlRs: "",
            dlf: "",
            bal: ""
        };
        const getSummaries = (param) => {
            const { columns, data } = param
            const sums = []
            let zfyIndex, rsIndex, cjfyIndex, inDaysIndex, avgDaysIndex, crfIndex, ypfIndex, ypblIndex, zfIndex, zfblIndex, dlRsIndex, dlfIndex, balIndex

            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计'
                    return
                }

                if (column.property === 'insurName' || column.property === 'doctor' || column.property === 'zyss' || column.property === 'zyh') {
                    sums[index] = ''
                    return
                }

                if (column.property === 'zfy') {
                    zfyIndex = index
                }
                if (column.property === 'rs') {
                    rsIndex = index
                }
                if (column.property === 'cjfy') {
                    cjfyIndex = index
                }
                if (column.property === 'inDays') {
                    inDaysIndex = index
                }
                if (column.property === 'avgDays') {
                    avgDaysIndex = index
                }
                if (column.property === 'crf') {
                    crfIndex = index
                }
                if (column.property === 'ypf') {
                    ypfIndex = index
                }
                if (column.property === 'ypbl') {
                    ypblIndex = index
                }
                if (column.property === 'zf') {
                    zfIndex = index
                }
                if (column.property === 'zfbl') {
                    zfblIndex = index
                }
                if (column.property === 'dlRs') {
                    dlRsIndex = index
                }
                if (column.property === 'dlf') {
                    dlfIndex = index
                }
                if (column.property === 'bal') {
                    balIndex = index
                }

                const values = data.map((item) => Number(item[column.property]))
                if (!values.every((value) => isNaN(value))) {
                    let hj = values.reduce((prev, curr) => {
                        const value = Number(curr)
                        if (!isNaN(value)) {
                            return prev + curr
                        } else {
                            return prev
                        }
                    }, 0)

                    let reg = /rs$/
                    if (!reg.test(column.property)) {
                        sums[index] = hj.toFixed(2)
                    } else {
                        sums[index] = hj
                    }
                    if (column.property === 'dlRs' || column.property === 'inDays') {
                        sums[index] = hj
                    }
                } else {
                    sums[index] = ''
                }
            })
            sums[cjfyIndex] = ((sums[zfyIndex] / sums[rsIndex])).toFixed(2)
            sums[avgDaysIndex] = ((sums[inDaysIndex] / sums[rsIndex])).toFixed(0)
            sums[crfIndex] = ((sums[zfyIndex] / sums[inDaysIndex])).toFixed(2)
            sums[ypblIndex] = ((sums[ypfIndex] / sums[zfyIndex]) * 100).toFixed(2)
            sums[zfblIndex] = ((sums[zfIndex] / sums[zfyIndex]) * 100).toFixed(2)
            sum.deptName = sums[0];
            sum.zfy = sums[zfyIndex];
            sum.rs = sums[rsIndex];
            sum.cjfy = sums[cjfyIndex];
            sum.inDays = sums[inDaysIndex];
            sum.avgDays = sums[avgDaysIndex];
            sum.crf = sums[crfIndex];
            sum.ypf = sums[ypfIndex];
            sum.ypbl = sums[ypblIndex];
            sum.zf = sums[zfIndex];
            sum.zfbl = sums[zfblIndex];
            sum.dlRs = sums[dlRsIndex];
            sum.dlf = sums[dlfIndex];
            sum.bal = sums[balIndex];
            return sums
        }
        const exportAvgFee = () => {
            if (returnData.value.returnData.length === 0) {
                ElMessage({
                    message: "没有可以导出的数据！",
                    type: "warning",
                    duration: 2500,
                    showClose: true,
                });
            }
            else {
                const title = {
                    deptName: "科室",
                    insurName: "险种",
                    zfy: "总费用",
                    rs: "结算人次",
                    cjfy: "次均费用",
                    inDays: "床日数",
                    avgDays: "平均住院天数",
                    crf: "床日费用",
                    ypf: "药品费",
                    ypbl: "药占比",
                    zf: "自付费用",
                    zfbl: "自付比",
                    dlRs: "单列人次",
                    dlf: "单列费用",
                    bal: "控制",
                };

                let d = clone(returnData.value.returnData)
                d.push(sum)
                Export(d, title, "长浏宁次均费用统计");
            }
        };
        const exportAvgFeeDoctor = () => {
            if (doctorAvgFee.value.length === 0) {
                ElMessage({
                    message: "没有可以导出的数据！",
                    type: "warning",
                    duration: 2500,
                    showClose: true,
                });
            }
            else {
                const title = {
                    deptName: "科室",
                    doctor: "医生",
                    insurName: "险种",
                    zfy: "总费用",
                    rs: "结算人次",
                    cjfy: "次均费用",
                    inDays: "床日数",
                    avgDays: "平均住院天数",
                    crf: "床日费用",
                    ypf: "药品费",
                    ypbl: "药占比",
                    zf: "自付费用",
                    zfbl: "自付比",
                    dlRs: "单列人次",
                    dlf: "单列费用",
                    bal: "控制",
                };

                let d = clone(doctorAvgFee.value)
                d.push(sum)
                Export(d, title, "长浏宁次均费用统计(医生)");
            }
        };
        const exportAvgFeePatient = () => {
            if (patientAvgFee.value.length === 0) {
                ElMessage({
                    message: "没有可以导出的数据！",
                    type: "warning",
                    duration: 2500,
                    showClose: true,
                });
            }
            else {
                const title = {
                    deptName: "科室",
                    doctor: "医生",
                    insurName: "险种",
                    xm: "姓名",
                    zyh: "住院号",
                    zfy: "总费用",
                    inDays: "床日数",
                    crf: "床日费用",
                    ypf: "药品费",
                    ypbl: "药占比",
                    zf: "自付费用",
                    zfbl: "自付比",
                    bal: "控制",
                    jslx: "结算类型",
                    zyzd: "主要诊断",
                    zyss: "主要手术",
                };
                let d = clone(patientAvgFee.value)
                d.push(sum)
                Export(d, title, "长浏宁次均费用统计(病人)");
            }
        };
        return {
            dateRange,
            shortcuts,
            tableHeight,
            queryTerm,
            insurId,
            dept,
            returnData,
            doctorAvgFee,
            showDoctorAvgFee,
            doctorDialogTitle,
            showPatientAvgFee,
            patientAvgFee,
            patientDialogTitle,
            query,
            handleSelect,
            querySearchDept,
            exportAvgFee,
            getSummaries,
            dbClnAvgFeeYsData,
            dbClnAvgFeeBrData,
            exportAvgFeeDoctor,
            exportAvgFeePatient,
        };
    }
}
</script>