// 判断是否选择了患者
import {stringIsBlank, stringNotBlank} from "@/utils/blank-utils";
import {ElMessage} from "element-plus";
import {getPatientInfo} from "@/api/inpatient/patient";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {ref} from "vue";
import {getServerDateApi} from "@/api/public-api";
import {getFormatDatetime} from "@/utils/date";
import {isDev} from "@/utils/public";

// 患者信息
export const huanZheXinXi = ref({})
// 是否点击了修改整个模板
export const muBanMing = ref({})
// 复制选中的医嘱
export const fuZhiYiZhu = ref([])
// 错误信息
export const cuoWuXinXi = ref('')
// 编辑器大小
export const winsize = ref({
    editor: 968,
    main: 0
})

export function youWuXuanZheHuanZhe() {
    if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
        ElMessage({
            message: '请先选择患者', showClose: true, type: 'error'
        })
        return true
    }
    return false
}


export function getSelfBuy(val) {
    if (stringIsBlank(val)) return ""
    switch (val) {
        case '1':
            return "自备"
        case '2':
            return "嘱托"
        case '3':
            return "基数药"
        default:
            return "";
    }
}

export function shouShuDengJi(val) {
    if (stringIsBlank(val)) return ""
    switch (val) {
        case "1":
            return "四级";
        case "2":
            return "三级";
        case "3":
            return "二级";
        case "4":
            return "一级";
        default:
            return "";
    }
}

export let zkList = ref([])
// 医嘱查询条件
export const queryParam = ref({
    displayRange: 0,
    frequCode: isDev ? 0 : 2,
    zhuangTai: isDev ? 0 : 3,
    groupNo: '73',
    patNo: '',
    times: 0,
});

// 医嘱数据
export const yiZhuData = ref({
    id: '',
    actOrderNo: isDev ? 'tempOrderNo' : null,
    orderName: '',
    orderCode: '',
    // 频率
    frequCode: '',
    frequCodeName: '',
    drugSpecification: '',
    dose: 0,
    // 领量
    doseUnit: '',
    doseUnitName: '',
    supplyCode: '',
    supplyCodeName: '',
    startTime: '',
    endTime: '',
    orderTime: '',
    doctorName: '',
    drugFlag: '',
    execUnit: '',
    execUnitName: '',
    parentNo: '',
    parentNoName: '',
    physicianName: '',
    discription: '',
    instruction: null,
    kfFlag: null,
    selfBuy: null,
    ybSelfFlag: '0',
    emergencyFlag: '0',
    drugQuan: 0,
    miniUnitName: '',
    serial: '',
    miniUnit: '',
    psFlag: false,
    kjywFlag: 0,
    yyfs: null,
    ssqk: null,
    yysj: null,
    zkObj: '',
    zkWardCode: '',
    zkDeptCode: '',
    statusFlag: '1',
    groupNo: '00',
});
// 保存医嘱数据
export const yzData = ref([])
let newDate = ''
getServerDateApi().then(res => {
    newDate = res
})
// 数据筛选
export const tempYzData = computed(() => {
    selectedData.value = []
    return yzData.value.filter((item, index) => {
        item.tempCheckbox = false
        let flag = queryParam.value.displayRange === 0
        let frequFlag = queryParam.value.frequCode === 0
        let zhuangTai = queryParam.value.zhuangTai === 0
        if (isCydy()) {
            return item.selfBuy === '4'
        }

        if (queryParam.value.displayRange === 1) {
            // 停止的医嘱
            flag = item.statusFlag === '5'
        } else if (queryParam.value.displayRange === 2) {
            flag = item.statusFlag === '2' || item.statusFlag === '3' || item.statusFlag === '4'
        } else if (queryParam.value.displayRange === 3) {
            flag = getFormatDatetime(newDate, 'YYYY-MM-DD') === getFormatDatetime(item.startTime, 'YYYY-MM-DD')
        }

        if (queryParam.value.frequCode === 1) {
            frequFlag = item.frequCode === 'ONCE'
        } else if (queryParam.value.frequCode === 2) {
            frequFlag = item.frequCode !== 'ONCE'
        }

        if (queryParam.value.zhuangTai === 1) {
            zhuangTai = item.statusFlag === '1'
        } else if (queryParam.value.zhuangTai === 2) {
            zhuangTai = item.statusFlag === '2'
        } else if (queryParam.value.zhuangTai === 3) {
            zhuangTai = item.statusFlag === '3' || item.statusFlag === '4'
        } else if (queryParam.value.zhuangTai === 5) {
            zhuangTai = item.statusFlag === '5'
        }
        return flag && frequFlag && zhuangTai && item.selfBuy !== '4';
    })
})

// 医嘱选中的数据
export const selectedData = ref([])
// 获取医嘱的下标
export const getYzIndex = (key) => {
    let temp = tempYzData.value.findIndex(item => {
        return item.id == key
    })
    if (typeof temp === 'undefined') {
        return '没有找到序号'
    } else {
        return temp
    }
}

// 错误信息
export const errorMsg = ref({
    dialog: false,
    type: 1,
    data: {}
})

// 添加新的会诊申请
export const consultationApplication = ref(false)

// 添加手术申请
export const operationApplication = ref([])
// 添加检查申请
export const addCheckList = ref([])
// 添加检验申请
export const xuanZhongJianCha = ref({
    data: [],
    weiBianMa: [],
    daiXuanZhong: [],
})

// 检验树状图
export const jyTree = ref([])
// 检查树状图
export const jcTree = ref([])

/**
 * 具体的草药明细
 * @type {Ref<UnwrapRef<{weiYi: *[], list: *[]}>>}
 */

export const mingXi = ref({
    weiYi: [],
    list: [],
})

/**
 * 点击查询患者信息
 * @param patNo 住院号
 */
export const clickOnThePatient = (patNo) => {
    let str = ''
    if (stringNotBlank(yiZhuData.value.actOrderNo) && yiZhuData.value.statusFlag === '1') {
        if (yiZhuData.value.actOrderNo !== 'tempOrderNo') {
            str += "存在未保存的医嘱。"
        }
    }
    if (operationApplication.value.length > 0) {
        str += '存在未保存的手术申请。'
    }
    if (consultationApplication.value) {
        str += '存在未保存的会诊申请。'
    }
    if (addCheckList.value.length > 0) {
        str += '存在未保存的检查申请。'
    }
    if (xuanZhongJianCha.value.data.length > 0) {
        str += '存在未保存的检验申请。'
    }
    if (mingXi.value.list.length > 0) {
        str += '存在未保存的草药医嘱。'
    }

    if (stringIsBlank(huanZheXinXi.value.inpatientNo)) {
        getPatientInfo(patNo).then((res) => {
            huanZheXinXi.value = res
        });
    } else {
        if (stringNotBlank(str)) {
            BizException(ExceptionEnum.LOGICAL_ERROR, str);
        }
    }

    getPatientInfo(patNo).then((res) => {
        clearAssociate()
        huanZheXinXi.value = res
    });

}


export const currentPage = ref('')

// 是出院带药
export function isCydy() {
    return currentPage.value === 'takeMedicine';
}

export const associateOrders = ref({
    actOrderNo: null,
    associatedGroup: []
})

export const clearAssociate = () => {
    associateOrders.value = {
        actOrderNo: null,
        associatedGroup: []
    }
    for (let i = 0, len = yzData.value.length; i < len; i++) {
        let item = yzData.value[i]
        item.associationFlag = false
    }
}

export const drugManual = ref({
    dialog: false,
    code: '',
    open: (code, serial) => {
        drugManual.value.dialog = true
        drugManual.value.code = code + '_' + serial
    }
})

export const isOpenDualScreen = ref(false)
// 双屏模式的 src
export const dualScreenSrc = ref('')


export let tableHeader = [
    {label: '编码', prop: 'orderCode'},
    {label: '名称', prop: 'orderName', width: 220},
    {label: '规格', prop: 'drugSpecification'},
    {label: '描述', prop: 'discription'},
    {label: '库存', prop: 'stockAmount'},
    {label: '大包装', prop: 'specPack'},
    {label: '医保类型', prop: 'ybFlagNew'},
    {label: '医保编码', prop: 'nationalCode'},
    {label: '医保名称', prop: 'nationalName'},
    {label: '医保备注', prop: 'ybComment'},
    {label: '大输液', prop: 'infusionFlagName'},
    {label: '厂家', prop: 'manuName'},
    {label: '类型', prop: 'orderType'},
    {label: '毒麻类型', prop: 'drugFlagName'},
    {label: '药房', prop: 'groupName'},
]

export const addJcCheck = async (data) => {
    let temp = addCheckList.value.findIndex(item => {
        return item.orderCode === data.orderCode
    })
    if (temp > -1) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '请勿重复添加。')
    }
    data.startTime = await getServerDateApi()
    addCheckList.value.push(data)
}


