<template>
    <div style="margin: 0;height: 100%">
        <yz-query-condition :patient-info="huanZheXinXi"
                            @batchDeleteOrdersClick="batchDeleteOrdersClick"
                            :add-yi-zhu-click="addYiZhuClick"
                            :click-on-the-order-template="clickOnTheOrderTemplate"
                            :confirm-orders-click="confirmOrdersClick"/>
        <div>
            <div style="height: 5px"/>
            <button @click="orderTemplateClick" title="维护自己创建的模板">维护模板</button>
            <button @click="orderTemplateClickCopy" title="维护自己创建的模板">选中医嘱做模板</button>
            <el-divider direction="vertical"></el-divider>
            <button @click="clickToStopTheOrder" title="选择了停止时间后记得选中医嘱在点击">批量停止</button>
            <button :disabled="stringIsBlank(huanZheXinXi.inpatientNo)"
                    @click="clickToModifyTheDoctorSOrderTime"
                    title="跳转到修改医嘱时间的页面，可修改开始和停止时间">
                修改医嘱时间
            </button>
            <button :disabled="stringIsBlank(huanZheXinXi.inpatientNo)"
                    @click="jumpToMedicalRecord" title="跳转到患者的病案首页">
                病案首页
            </button>
            <button @click="confirmAssociationClick" title="关联医嘱">关联</button>
            <button @click="openRationalDrugUse" title="进入到合理用药的页面">合理用药</button>
            <button @click="allergen.open()" title="患者过敏源信息维护">过敏源维护</button>
            <blood-sugar :pat-no="huanZheXinXi.inpatientNo" :times="huanZheXinXi.admissTimes"/>
            <report-of-infectious-diseases :pat-no="huanZheXinXi.inpatientNo"
                                           :times="huanZheXinXi.admissTimes"
                                           :ward="huanZheXinXi.admissWard"/>
        </div>
        <div style="height: 5px"/>
        <yz-editor :patient-info="huanZheXinXi"
                   ref="yzEditorRef"
                   :open-group-order-template="openGroupOrderTemplate"
                   @successfullyEntered="successfullyEntered"/>

        <yz-table-v2 ref="tableRef"
                     @void-orders="voidOrdersClick"
                     @clickAssociate="clickAssociate"
                     @rowClick="rowClick"/>

        <doctor-s-order-fee :data="chargeDetails.data"
                            v-if="chargeDetails.dialog"
                            :sum="chargeDetails.sum"
                            @close="chargeDetails.dialog = false"/>
        <!--  获取模板的数据  -->
        <huo-qu-mu-ban
                ref="mubanRef"
                :editor="false"
                @muBanShuJu="muBanShuJu"/>

        <xc-dialog v-model="stopOrderDialog.dialog" title="停止医嘱错误信息">
            <div v-for="(value,key) in stopOrderDialog.error">
                医嘱号： {{ key }} 序号： {{ getYzIndex(key) + 1 }}
                <br>
                {{ value }}
            </div>
        </xc-dialog>

        <yao-ping-xiang-qing v-if="drugManual.dialog"
                             :code="drugManual.code"
                             @close="drugManual.dialog = false"/>

        <!-- 这个是过敏源的 -->
        <AllergenEntry v-if="allergen.dialog"
                       :pat-no="huanZheXinXi.inpatientNo"
                       @close="allergen.dialog = false"/>

        <order-progress ref="orderProgressRef"/>

        <!--  合理用药窗口  -->
        <rational-drug-use-window ref="reasonableRef" @submit="confirmOrder"/>
        <fee-table/>
    </div>
</template>

<script name="YiZhuLuRuZhuJian" setup>
import {
    associateOrdersApi, deleteMultipleOrders, huoQuYiZhuShuJu,
    insertTemplateOrder,
    stopOrder, voidOrders,
} from '@/api/zhu-yuan-yi-sheng/yi-zhu-lu-ru'
import {
    huanZheXinXi,
    getYzIndex,
    zkList,
    queryParam,
    clickOnThePatient,
    drugManual,
    associateOrders,
    clearAssociate, youWuXuanZheHuanZhe, yzData, errorMsg, yzMitt
} from '../public-js/zhu-yuan-yi-sheng'
import store from '@/store'
import {listIsBlank, stringIsBlank, stringNotBlank} from '@/utils/blank-utils'
import {getTheTransferList} from '@/api/public-api'
import router from '@/router'
import sleep from "@/utils/sleep";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {ElMessageBox} from "element-plus";
import YzQueryCondition from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/yz-header/YzQueryCondition";
import YzEditor from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/yz-edit/YzEditor.vue";
import HuoQuMuBan from '@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/HuoQuMuBan.vue'
import {getFormatDatetime} from "@/utils/date";
import XcDialog from "@/components/xiao-chan/dialog/XcDialog";
import {xcMessage} from "@/utils/xiaochan-element-plus";
import YaoPingXiangQing from "@/components/zhu-yuan-yi-sheng/he-li-yong-yao/YaoPingXiangQing.vue";
import AllergenEntry from "@/components/zhu-yuan-yi-sheng/AllergenEntry.vue";
import OrderProgress from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/OrderProgress.vue";
import RationalDrugUseWindow from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/RationalDrugUseWindow.vue";
import ReportOfInfectiousDiseases
    from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/report-of-infectious-diseases/ReportOfInfectiousDiseases.vue";
import YzTableV2 from "@/components/zhu-yuan-yi-sheng/yi-zhu-lu-ru/table/YzTableV2.vue";
import {clone} from "@/utils/clone";
import BloodSugar from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/BloodSugar.vue";
import FeeTable from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/FeeTable.vue";

const windowSize = computed(() => {
    return store.state.app.windowSize
})

const user = computed(() => {
    return store.state.user.info
})

let allergen = $ref({
    dialog: false,
    open: () => {
        if (youWuXuanZheHuanZhe()) return
        allergen.dialog = true
    }
})

// 医嘱进度
const orderProgressRef = ref(null)

// 医嘱编辑
const yzEditorRef = ref(null)
const successfullyEntered = async (data) => {
    queryParam.value.displayRange = 0
    queryParam.value.zhuangTai = 0
    yzData.value = await huoQuYiZhuShuJu({
        patNo: huanZheXinXi.value.inpatientNo,
        times: huanZheXinXi.value.admissTimes
    })
    yzMitt.emit('clearSelected')
    if (data != null) {
        tableRef.value.scrollTo(data.actOrderNo.toString())
    }
    addYiZhuClick()
}
/**
 * 下面这里是添加医嘱了
 */
const addYiZhuClick = () => {
    yzEditorRef.value.addOrderNo()
}

const reasonableRef = ref(null)

/**
 * 确认医嘱 , 已经做过无患者的判断了
 */
const confirmOrdersClick = async () => {
    // 如果没有问题就可以直接确认医嘱了。
    let temp = await reasonableRef.value.check(huanZheXinXi.value.inpatientNo, huanZheXinXi.value.admissTimes)
    if (temp) {
        await confirmOrder()
    }
}

// 真正的向后台确认医嘱
const confirmOrder = async () => {
    // 确认医嘱
    await yzEditorRef.value.confirmOrdersClick()
    // 查询医嘱
    await yzMitt.emit('queryYz');
}

const openRationalDrugUse = () => {
    window.open('http://172.16.32.121:9097/index.html')
}

// 表格
const tableRef = ref(null)
const rowClick = (val) => {
    orderProgressRef.value.fillOrder(val)
    if (associateOrders.value.actOrderNo) {
        let index = associateOrders.value.associatedGroup.indexOf(val.actOrderNo)
        if (associateOrders.value.actOrderNo === val.actOrderNo) {
            BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联自己');
        }

        if (val.orderCode !== '06054' && val.serial === '00') {
            BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联项目');
        }
        if (val.statusFlag !== '1') {
            BizException(ExceptionEnum.MESSAGE_ERROR, '无法关联不是录入状态的医嘱。');
        }
        if (index > -1) {
            val.associationFlag = false;
            associateOrders.value.associatedGroup.splice(index, 1);
        } else {
            val.associationFlag = true;
            associateOrders.value.associatedGroup.push(val.actOrderNo);
        }
    } else {
        yzEditorRef.value.fillData(val)
    }

}

const stopOrderDialog = ref({
    dialog: false,
    error: ''
})

/**
 * 停止医嘱
 */
const clickToStopTheOrder = () => {
    let tempData = tableRef.value.getSelectedData()
    tempData.forEach(item => {
        // 因为前端用的是浏览器自带的 所以要删除 T
        item.endTime = getFormatDatetime(item.endTimeTemp)
    })

    let param = {
        inpatientNo: huanZheXinXi.value.inpatientNo,
        admissTimes: huanZheXinXi.value.admissTimes,
        list: tempData
    }
    stopOrder(param).then(res => {
        if (res?.error) {
            stopOrderDialog.value.error = res.data
            stopOrderDialog.value.dialog = true
            for (let i = 0; i < tempData.length; i++) {
                let item = tempData[i]
                item.endTime = ''
            }
        } else {
            stopOrderDialog.value.error = {}
            yzMitt.emit('queryYz')
        }
    })
}


/**
 * 作废医嘱
 */
const voidOrdersClick = (val) => {
    ElMessageBox.prompt(`请问是否要撤销<br><span style="color: red">【${val.orderName}】</span>医嘱<br>
                        撤销父医嘱会自动撤销子医嘱。`, '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => {
            val = val.trim()
            if (val === null || val.length < 1 || val.length > 50) {
                return false;
            }
        },
        dangerouslyUseHTMLString: true,
        inputErrorMessage: '作废原因，不能为空，最多可输入50个字符。',
        closeOnPressEscape: false,
        closeOnClickModal: false
    }).then(({value}) => {
        voidOrders(val.id, value).then(res => {
            yzMitt.emit('queryYz')
        })
    }).catch(() => {

    })
}


/**
 * 右键点击查看医嘱产生的费用
 * @param val
 */
let doctorSOrderFee = $ref({
    data: {},
    problem: {},
    totalCost: {}
})
let chargeDetails = $ref({
    dialog: false,
    data: [],
    sum: {}
})

const clickToViewTheDoctorSOrderFee = (val) => {
    chargeDetails.data = doctorSOrderFee.data[val.actOrderNoStr]
    if (chargeDetails.data) {
        chargeDetails.sum = doctorSOrderFee.totalCost[val.actOrderNoStr]
        chargeDetails.dialog = true
    } else {
        BizException(ExceptionEnum.MESSAGE_ERROR, '该医嘱还没有产生费用')
    }
}

// 获取模板
const mubanRef = ref(null)
const clickOnTheOrderTemplate = () => {
    if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择患者')
    }
    mubanRef.value.openOrCloseDialog(true)
}
/**
 * 把模板的数据插入到患者的医嘱表
 * @param val
 */
const muBanShuJu = (val) => {
    let tempGroupNo = ['71', '73']
    if (queryParam.value.frequCode === 'takeMedicine') {
        val = val.filter((item) => {
            item.selfBuy = '4'
            if (stringIsBlank(item.instruction)) {
                item.instruction = item.frequCodeName;
            }
            item.supplyCode = '007'
            item.frequCode = 'ONCE'
            return item.serial !== '00'
        })
        if (val.length === 0) {
            BizException(ExceptionEnum.LOGICAL_ERROR, '项目无法出院带药。')
        }
    }
    val.forEach(item => {
        if (item.serial === '00') {
            item.groupNo = '00'
        } else {
            if (!tempGroupNo.includes(item.groupNo)) {
                item.groupNo = queryParam.value.groupNo;
            }
        }
    })
    let param = {
        inpatientNo: huanZheXinXi.value.inpatientNo,
        admissTimes: huanZheXinXi.value.admissTimes,
        groupNo: queryParam.value.groupNo,
        list: val
    }
    insertTemplateOrder(param).then(async (list) => {
        mubanRef.value.openOrCloseDialog(false)
        await successfullyEntered()
        let data = {}
        list.forEach(item => {
            data[item] = true
        })
        tableRef.value.callTemplate(data)
    })
}

/**
 * 打开模板的对话框
 * @param code
 * @returns {Promise<void>}
 */
const openGroupOrderTemplate = async (code) => {
    mubanRef.value.openOrCloseDialog(true)
    await nextTick()
    mubanRef.value.openTemplateByCode(code)
}


/**
 * 添加模板
 */
const orderTemplateClick = () => {
    router.push({
        name: 'orderTemplateMaintenance',
    })
}

const orderTemplateClickCopy = () => {
    let temp = clone(tableRef.value.getSelectedData())
    if (listIsBlank(temp)) {
        xcMessage.error('请先选中医嘱。')
        return
    }
    let dept = {
        code: huanZheXinXi.value.zkWard,
        name: huanZheXinXi.value.zkWardName
    }
    router.push({
        name: 'orderTemplateMaintenance',
        params: {
            data: JSON.stringify(temp),
            dept: JSON.stringify(dept)
        }
    })
}

onMounted(async () => {
    await sleep(200)
    zkList.value = await getTheTransferList()
})


// 点击修改医嘱时间
const clickToModifyTheDoctorSOrderTime = () => {
    router.push({
        name: 'yzActOrderModify',
        query: {
            patNo: huanZheXinXi.value.inpatientNo,
        },
    })
}

// 跳转到病案首页
const jumpToMedicalRecord = () => {
    router.push({
        name: 'fillCaseFrontSheet',
        query: {
            patNo: huanZheXinXi.value.inpatientNo,
            deptCode: huanZheXinXi.value.smallDept,
        },
    })
}

// 点击关联
const clickAssociate = async (data) => {
    if (stringNotBlank(data.parentNo)) {
        xcMessage.error('该医嘱已经有父医嘱了。');
    } else if (data.statusFlag !== '1') {
        xcMessage.error('不是录入状态的医嘱无法关联。');
    } else if (data.serial === '00') {
        xcMessage.error('项目无法关联。');
    } else {
        if (associateOrders.value.actOrderNo === null) {
            await yzMitt.emit('queryYz')
            associateOrders.value.actOrderNo = data.actOrderNo
        } else {
            xcMessage.error('请先确认当前关联医嘱。')
        }
    }
}

// 点击确认关联
const confirmAssociationClick = () => {
    if (associateOrders.value.actOrderNo === null) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '请先选择需要关联的父医嘱')
    }
    if (associateOrders.value.associatedGroup.length === 0) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '至少选择一个子医嘱')
    }
    ElMessageBox.confirm('请确认是否要关联这些医嘱。', '提示', {
        type: 'warning'
    }).then(() => {
        associateOrdersApi(associateOrders.value).then((res) => {
            clearAssociate()
            yzMitt.emit('queryYz')
        })
    }).catch(() => {
    })
}

/**
 * 点击批量删除数据
 */
const batchDeleteOrdersClick = () => {
    let tempData = tableRef.value.getSelectedData()
    if (tempData.length === 0) {
        BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择要删除的数据");
    }
    ElMessageBox.confirm('是否要批量删除这些医嘱？', '提示', {
        type: 'warning'
    }).then(() => {
        let param = {
            inpatientNo: huanZheXinXi.value.inpatientNo,
            admissTimes: huanZheXinXi.value.admissTimes,
            list: tempData
        }
        deleteMultipleOrders(param).then((res) => {
            if (res !== null && res.error) {
                let errData = []
                for (const key in res.data) {
                    let index = getYzIndex(key)
                    let tempYzData = yzData.value[index]
                    yzData.value[index].error = true
                    errData.push({
                        actOrderNo: key,
                        orderName: tempYzData.orderName,
                        errorMessage: res.data[key]
                    })
                }
                errorMsg.value.dialog = true
                errorMsg.value.type = 2
                errorMsg.value.data = errData
            } else {
                yzMitt.emit('queryYz', false)
            }
        })
    }).catch(() => {
    })
}


onActivated(async () => {
    if (router.currentRoute.value.params.inpatientNo) {
        await nextTick()
        await clickOnThePatient(router.currentRoute.value.params.inpatientNo);
        await yzMitt.emit('queryYz')
    }
})


</script>

<style scoped lang="scss">
:deep(.el-table .children-row) {
  background: rgba(145, 247, 145, 0.93);
}

:deep(.el-table) {
  --el-table-row-hover-background-color: #85dbfd7a;
}

:deep(.el-dropdown-menu__item) {
  font-size: 14px !important;
  height: 26px;
  line-height: 26px;
  font-weight: bold;
}

</style>
