<template>
    <xc-table-v2 :data="tempYzData"
                 @rowClick="rowClick"
                 :width="getWindowSize.w - 160"
                 row-key="actOrderNo"
                 @contextmenu="contextmenuItem"
                 :height="getWindowSize.h  - (yzHeaderSize) - 180  "
                 @dbRowClick="setDefaultStopTime"
                 ref="tableRef"
                 :row-class="rowClass"
                 :columns="header"/>
    <right-click-menu :mouse-position="mousePosition" :config="opt"/>
</template>


<script setup name='Test' lang="jsx">
import {onMounted, ref} from 'vue'
import XcTableV2 from "@/components/xiao-chan/xc-table-v2/XcTableV2.vue";
import {stringIsBlank} from "@/utils/blank-utils";
import {getFormatDatetime} from "@/utils/date";
import {getServerDateApi} from '@/api/public-api'
import {getWindowSize} from "@/utils/window-size";
import {
    tempYzData,
    yiZhuData,
    associateOrders,
    clearAssociate,
    drugManual,
    yzHeaderSize,
    yzMitt,
} from "@/views/hospitalization/zhu-yuan-yi-sheng/public-js/zhu-yuan-yi-sheng";
import sleep from "@/utils/sleep";
import RightClickMenu from "@/components/menu-item/RightClickMenu.vue";
import {nullToEmpty} from "@/utils/public";
import {ElIcon} from "element-plus";
import {DocumentCopy} from "@element-plus/icons-vue";

const emits = defineEmits(['rowClick', 'clickAssociate', 'voidOrders'])

const tableRef = ref(null)

const header = [
    {type: 'selected', width: 20},
    {width: 30, type: 'index'},
    {width: 20, code: 'orderGroup', name: '组'},
    {
        width: 20, code: 'statusFlag', cellRenderer: ({cellData}) => {
            return getYiZhuFlag(cellData)
        }
    },
    {
        width: 70, code: 'actOrderNo', name: '医嘱号', cellRenderer: ({data}) => {
            if (data.error) {
                return h('span', {
                    style: {
                        color: 'red'
                    },
                    class: () => orderNoClass(data)
                }, data.actOrderNo)
            } else {
                return h('span', {
                    class: orderNoClass(data)
                }, data.actOrderNo)
            }

        }
    },
    {width: 225, code: 'orderName', name: '医嘱名称'},
    {
        code: 'dose', name: '剂量', width: 75, cellRenderer: ({data}) => {
            return h('span', {}, nullToEmpty(data.dose) + ' ' + nullToEmpty(data.doseUnitName))
        }
    },
    {code: 'frequCode', name: '频率', width: 75},
    {code: 'supplyCodeName', name: '给药方式', width: 60},
    {
        code: 'startTime', name: '开始时间', width: 95, cellRenderer: ({data}) => {
            return h('span', {}, timeFomat(data.startTime)) //  (<span>{timeFomat(data.startTime)}</span>)
        }
    },
    {
        code: 'endTime', name: '结束时间', width: 160, cellRenderer: ({data, index}) => {
            if (stringIsBlank(data.endTime) && stringIsBlank(data.parentNo) && data.frequCode !== 'ONCE') {
                return h('input', {
                    type: 'datetime-local',
                    style: endDateStyle(data),
                    value: data.endTimeTemp,
                    onInput: (event) => {
                        data.endTimeTemp = event.target.value
                    },
                    onclick: (event) => {
                        event.stopPropagation()
                    },
                    onContextmenu: (event) => {
                        event.stopPropagation()
                        event.preventDefault();
                        cancelStopTime(data, index)
                    }
                }, null)
            }
            return h('span', null, timeFomat(data.endTime))
        }
    },
    {
        code: 'emergencyFlag', name: '紧急', cellRenderer: ({cellData}) => {
            return h('span', null, cellData === '1' ? '√' : '')
        },
        width: 30
    },
    {
        code: 'ybSelfFlag', name: '自费', cellRenderer: ({cellData}) => {
            return h('span', null, cellData === '1' ? '√' : '')
        },
        width: 30
    },
    {code: 'physicianName', name: '医生', width: 65},
    {code: 'selfBuyName', name: '费用标志', width: 60},
    {code: 'execUnitName', name: '执行科室', width: 80},
    {
        code: 'drugQuan', name: '领量', cellRenderer: ({data}) => {
            return h('span', null, nullToEmpty(data.drugQuan) + nullToEmpty(data.miniUnitName))
        },
        width: 30
    },
    {code: 'groupNoName', name: '药房', width: 91},
    {code: 'serial', name: '序号', width: 35},
    {code: 'instruction', name: '嘱托', width: 150},
    {
        name: '操作', width: 100, fixed: 'right', cellRenderer: ({data}) => {
            return h('div', {
                class: 'yz_button',
                onclick: (e) => {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    emits('voidOrders', data)
                }
            }, [hToVoidNode(data), hDeleteNode(data)])
        }
    }
];

const hToVoidNode = (data) => {
    return h('div', {
        class: 'toVoid',
        onclick: (e) => {
            e.preventDefault();
            e.stopImmediatePropagation();
            emits('voidOrders', data)
        }
    }, {default: () => '作废'})
}

const hDeleteNode = (data) => {
    return h('div', {
        class: 'delete',
        onclick: (e) => {
            e.preventDefault();
            e.stopImmediatePropagation();
            yzMitt.emit('deleteAnOrderByOrderNo', data, false)
        }
    }, {default: () => '删除'})
}


const orderNoClass = (data) => {
    let c = ''
    if (data.newOrderFlag > 0) {
        c = 'new_order'
    }
    return c
}

const timeFomat = (val) => {
    return getFormatDatetime(val, 'YY-MM-DD HH:mm')
}

function getYiZhuFlag(val) {
    if (stringIsBlank(val)) {
        return val
    }
    switch (val) {
        case '1':
            return h('span', {style: {color: '#05ff00'}}, 'R') // (<span style="color: #05ff00">R</span>)
        case '2':
            return h('span', {style: {color: '#0000fb'}}, 'Q')//(<span style="color: #0000fb">Q</span>)
        case '3':
            return h('span', {style: {color: '#ff07f3'}}, 'Z')// (<span style="color: #ff07f3">Z</span>)
        case '4':
            return h('span', {style: {color: '#ff07f3'}}, 'Z')// (<span style="color:  #ff07f3">Z</span>)
        case '5':
            return h('span', {style: {color: 'red'}}, 'T')// (<span style="color: red">T</span>)
        case '-1':
            return h('span', {style: {color: '#00ffe0'}}, 'D') // (<span style="color: #00ffe0">D</span>)
        default:
            return 'warning'
    }
}

const endDateStyle = (item) => {
    if (item.endTimeTemp && item.$selected) {
        return {
            width: '140px',
            color: 'white',
            backgroundColor: 'red',
            border: 0,
        }
    } else {
        return {
            width: '140px',
            border: 0,
        }
    }
}

const rowClick = (data) => {
    emits('rowClick', data)
}

const rowClass = (data) => {
    if (typeof twinkleList.value[data.actOrderNo] !== 'undefined') {
        sleep(3000).then(() => {
            delete twinkleList.value[data.actOrderNo]
        })
        return 'animation_hzfirst'


    } else if (typeof twinkleList.value[data.parentNo] !== 'undefined') {
        return 'animation_hzfirst'
    }

    // 父级
    if (data.associationFlag) {
        return 'parent_level'
    }

    // 子级
    if (associateOrders.value.actOrderNo === data.actOrderNo) {
        return 'child_level'
    }

    if (data.actOrderNo === yiZhuData.value.actOrderNo) {
        return 'activation'
    }
}

const setDefaultStopTime = async ({data, index}) => {
    if (stringIsBlank(data.endTime) && stringIsBlank(data.parentNo) && data.frequCode !== 'ONCE') {
        data.endTimeTemp = getFormatDatetime(await getServerDateApi(), 'YYYY-MM-DDTHH:mm')
        clickSelected(true, data, index)
    }
}

const cancelStopTime = (val, index) => {
    if (val.parentNo) return
    val.endTimeTemp = ''
    clickSelected(false, val, index)
}

const clickSelected = (isSelected, data, index) => {
    tableRef.value.selectedRow(isSelected, data, index)
}

const twinkleList = ref({})
const scrollTo = (key) => {
    twinkleList.value[key] = true
    let index = tableRef.value.scrollToByKey(key)
    if (index < 0) {
        scrollToEnd()
    }
}

const scrollToEnd = () => {
    tableRef.value.scrollTo(tempYzData.value.length)
}

const mousePosition = ref()
const opt = [
    {
        name: '医嘱费用', click: (data) => {
            yzMitt.emit('queryFeeByOrderNo', data)
        }
    },
    {
        name: '复制', click: (data) => {
            yzMitt.emit('copy', data.actOrderNo, data.frequCode)
        },
        icon: h(ElIcon, null, () => h(DocumentCopy))
    },
    {
        name: '粘贴', click: (data) => {
            yzMitt.emit('paste')
        },
        validator: () => {
            return yzMitt.emit('allowReplication')
        },
        icon: h('i', {
            class: 'iconfont icon-zhantie'
        })
    },
    {
        name: '关联', click: (data, index) => {
            emits('clickAssociate', data)
        }
    }, {
        name: '退出关联', click: () => {
            clearAssociate()
        }
    }, {
        name: '说明书', click: (data) => {
            if (data.groupNo !== '00') {
                drugManual.value.open(data.orderCode, data.serial);
            }
        }
    }, {
        name: '停止医嘱', click: (data, index) => {
            if (data.$selected) {
                cancelStopTime({data, index})
            } else {
                setDefaultStopTime({data, index})
            }
        },
        validator: (data) => {
            return !data.parentNo;
        }
    }, {
        name: '作废', click: (data) => {
            emits('voidOrders', data)
        }
    }
];

const contextmenuItem = (data, index, event) => {
    mousePosition.value = {
        event,
        data: data,
        index
    }
}

const getSelectedData = () => {
    return tableRef.value.getSelectedData()
}

const clearSelected = () => {
    tableRef.value.clearSelected()
}

const callTemplate = (list) => {
    twinkleList.value = list
    scrollToEnd()
}

onMounted(() => {
    yzMitt.on('tableScroll', (val) => {
        tableRef.value.scrollTo(val)
    })

    yzMitt.on('clearSelected', () => {
        clearSelected()
    })

    yzMitt.on('scrollEndAndTwinkle', async (val) => {
        twinkleList.value = val;
        await nextTick()
        scrollToEnd()
    });
})

watch(() => tempYzData.value.length, () => {
    tableRef.value.scrollTo(0)
})

defineExpose({
    scrollTo,
    scrollToEnd,
    getSelectedData,
    clearSelected,
    callTemplate
})

</script>

<style lang="scss">

.new_order {
  position: relative;

  &:before {
    position: absolute;
    right: -6px;
    font-size: 15px;
    top: -5px;
    content: "*";
    color: red;
  }
}

@keyframes hzfirst {
  from {
    background-color: #95d475
  }
  to {
    background-color: white;
  }
}

.yz_button {
  width: 100%;
  cursor: pointer;
  padding: 0 5px;
  display: flex;
  justify-content: space-between;

  div {
    width: max-content;
    margin: 0 5px;
  }

  .toVoid {
    color: #E6A23C;
    background-color: inherit;
  }

  .delete {
    color: #F56C6C;
    background-color: inherit;
  }
}

.animation_hzfirst {
  .cell {
    animation: hzfirst 1s linear infinite
  }
}

.activation {
  background-color: rgba(0, 58, 241) !important;
  color: white;
}

.parent_level {
  background-color: red;
  color: white;
}

.child_level {
  background-color: rgba(3, 255, 15);
  color: black;
}

</style>

