<template>
    <view>
        <!-- pages/diagnosticEntry.wxml -->
        <nav-bar :navbarData="navbarData"></nav-bar>
        <mp-dialog title="提醒" style="top: 40%" :show="showEndMessage" @buttontap="tapDialogButton" :buttons="endButtonArr">
            <view :style="'color:' + endItem.colour" v-if="endItem.flag == 'Y' && endItem.code == '2' && endItem.prompt != ''">
                <icon class="icon-box-img" type="warn" size="20"></icon>
                {{ endItem.prompt }}
            </view>

            <view>{{ endItem.descripts }}</view>
        </mp-dialog>
        <van-notify id="van-notify" />
        <view class="container">
            <view class="diagnosticEntry" :style="'margin-top: ' + (height * 2 - 2) + 'rpx; height: calc(100vh - ' + (height * 1.5 - 2) + 'rpx)'">
                <view class="header-wrapper">
                    <van-row>
                        <van-col span="17">
                            <view class="diagnosticheader">
                                <view class="header-flex" :data-index="index" @tap="tapChange" v-for="(item, index) in array" :key="index">
                                    <view :class="'diagnosticheaderBox ' + (select === index ? 'select' : '') + ' ' + (index !== 2 ? 'borderRight' : '')">
                                        {{ item.title }}
                                    </view>
                                </view>
                            </view>
                        </van-col>
                        <van-col span="6">
                            <view>
                                <van-button
                                    v-if="patientData.statusCode != 'F'"
                                    custom-class="roundBtn"
                                    @tap.native="finish"
                                    round
                                    :icon="imgDomain + '/images/icon/doctor/finishservice.png'"
                                >
                                    结束服务
                                </van-button>
                                <van-button
                                    v-if="patientData.statusCode == 'F'"
                                    custom-class="roundBtn"
                                    @tap.native="cancelFinish"
                                    round
                                    :icon="imgDomain + '/images/icon/doctor/finishservice.png'"
                                >
                                    取消结束
                                </van-button>
                            </view>
                        </van-col>
                    </van-row>
                </view>
                <view class="diagnosticcontent">
                    <view v-if="select === 0" style="height: 100%">
                        <!-- 病历 -->
                        <medicalRecord id="medicalRecord" @resetSelect="resetSelect($event, { tagId: 'medicalRecord' })"></medicalRecord>
                    </view>
                    <view v-if="select === 1" style="height: 100%">
                        <!-- 诊断 -->
                        <diagnostic ref="diagnostic" id="diagnostic" @resetSelect="resetSelect($event, { tagId: 'diagnostic' })"></diagnostic>
                    </view>
                    <view v-if="select === 2" style="height: 100%;">
                        <!-- 处方 -->
                        <prescription id="prescription" ref="prescription" @resetSelect="resetSelect" :callData="callData" :callData2="callData2"></prescription>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../../utils/cache';
import diagnostic from './diagnostic/diagnostic';
import medicalRecord from './medicalRecord/medicalRecord';
import prescription from './prescription/prescription';
import navBar from '@/pages/components/navbar/index';
// pages/diagnosticEntry.js
import { $http } from '../../../../config/https';
import { httpconfig } from '../../../../config/httpconfig';
import messageUtil from '../../../../utils/message.js';
import Util from '../../../../utils/util.js';
import commonUtil from '../../../../utils/common.js';
const app = getApp();
import Dialog from '../../../../utils/dialog';
export default {
    components: {
        diagnostic,
        medicalRecord,
        prescription,
        navBar
    },
    data() {
        return {
            imgDomain: httpconfig.imgDomain,
            oldselect: 0,
            select: 0,

            // 选中的值tabbox
            array: [
                {
                    title: '病历录入'
                },
                {
                    title: '诊断录入'
                },
                {
                    title: '医嘱录入'
                }
            ],

            // tab选项
            callData: {},

            // 处方添加过来的data 西药
            callData2: {},

            // 处方添加过来的data 草药
            navbarData: {
                isGoBack: true,
                background: '',
                title: '诊断录入',
                //导航栏 中间的标题
                bottom: false
            },

            height: app.globalData.height,
            flag: '',
            endButtonArr: [],

            endItem: {
                colour: '',
                flag: '',
                code: '',
                prompt: '',
                descripts: ''
            },

            showEndMessage: false,
            toURL: '',

            patientData: {
                statusCode: ''
            },

            changeDataFlag: 'Y',
            editData: {},
            addText: '',
            refreshing: false
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.select) {
            this.setData(
                {
                    select: +options.select,
                    addText: options.addText,
                    oldselect: +options.select
                },
                () => {
                    let { select } = this;
                    this.navigationBarTitleText(select); //自定义导航栏切换
                }
            );
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let { select, oldselect } = this;
        if (select == '-1') {
            this.setData({
                select: oldselect
            });
        }
        this.setData({
            patientData: Cache.get('patientData')
        });
       
        this.canChangeFlag();
        // 检验检查直接提交后端后，刷新处方已确认数据
        try {
            if (Cache.get('inspectionExamineSaved')) {
                Cache.remove('inspectionExamineSaved');
                let child = (this.$refs && this.$refs.prescription) || null;
                if (child && typeof child.arrList === 'function') {
                    child.arrList(2);
                }
            }
        } catch (e) {}
        // 草药直接保存后，刷新处方数据
        try {
            if (Cache.get('herbalSaved')) {
                Cache.remove('herbalSaved');
                let child = (this.$refs && this.$refs.prescription) || null;
                if (child && typeof child.arrList === 'function') {
                    child.arrList(0);
                }
            }
        } catch (e) {}
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 点击切换
        tapChange: function (event) {
            let { currentTarget } = event;
            let { array } = this;
            let dataset = currentTarget.dataset;
            this.navigationBarTitleText(dataset.index); //自定义导航栏切换
            this.setData({
                select: dataset.index,
                // 选中的tab
                addText: array[dataset.index].addText,
                // 添加按钮名称
                oldselect: dataset.index
            });
        },

        // 自定义导航栏切换
        navigationBarTitleText: function (i) {
            let { navbarData, array } = this;
            navbarData.title = array[i].title;
            this.setData({
                navbarData
            });
        },

        resetSelect: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            //移除当前显示组件。用于重新进入刷新用
            this.setData({
                select: -1
            });
        },

        // 路由回显的回调 西药
        callDataFun: function (data) {
            if (!Array.isArray(data)) {
                var arr = [];
                arr.push(data);
                data = arr;
            }
            let errStr = '';
            let newData = [];
            data.map((item, index) => {
                if (item.hasOwnProperty('invalid')) {
                    if (errStr) {
                        errStr = errStr + ',' + item.invalid;
                    } else {
                        errStr = item.invalid;
                    }
                } else {
                    newData.push(item);
                }
            });
            if (errStr) {
                Dialog.alert({
                    title: '提示',
                    message: errStr + '为无效药',
                    context: this
                });
            }
            this.setData(
                {
                    callData: newData
                },
                () => {
                    // 关键修复：setData 后 props 会同步到 prescription.vue.callData，
                    // 但 watch callData → callDataClone 是 nextTick 异步触发的，
                    // 依赖用户返回 Entry.vue 时 onShow → pageLifetimes mixin → handlePageShow 路径。
                    // H5 + Vue3 下该路径不稳定（pageLifetimes mixin 在某些情况下 $children 为空），
                    // 主动用 zpSelectComponent 找 prescription 子组件并直接调 wListPush 兜底。
                    try {
                        let child = null;
                        if (typeof this.zpSelectComponent === 'function') {
                            child = this.zpSelectComponent('#prescription');
                        }
                        if (!child && this.$refs && this.$refs.prescription) {
                            child = this.$refs.prescription;
                        }
                        console.log('[Entry.callDataFun] prescription 子组件=', child, 'newData.length=', newData.length);
                        if (child && typeof child.wListPush === 'function') {
                            newData.forEach((item) => {
                                child.wListPush(item, 'N');
                            });
                            console.log('[Entry.callDataFun] 已直接调 prescription.wListPush');
                        }
                    } catch (e) {
                        console.warn('[Entry.callDataFun] 主动 push 失败:', e);
                    }
                }
            );
        },

        // 路由回显的回调 草药
        callData2Fun: function (data) {
            this.setData({
                callData2: data
            });
        },

        //病历保存 edit
        callData3: function () {
            this.medicalRecord = this.zpSelectComponent('#medicalRecord');
            this.medicalRecord.add(); // 历史处方
        },

        //病历回显
        callDataEdit: function (obj) {
            this.medicalRecord = this.zpSelectComponent('#medicalRecord');
            this.medicalRecord.callDataEdit(obj); // 历史处方
        },

        tapDialogButton: function (e) {
            console.log(e);
            var item = e.detail.item;
            if (item.code == '2') {
                this.finishStatus('Y');
                return;
            }
            if (item.code == '3') {
                messageUtil.handleSendMessage('F', '医生已结束问诊,请您评价!');
                let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
                let prevPage = pages[pages.length - 2];
                prevPage.setData(
                    {
                        // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
                        refreshing: true
                    },
                    () => {
                        uni.reLaunch({
                            url: this.toURL
                        });
                        // wx.navigateBack({
                        //   delta: 2,
                        // })
                    }
                );
            }

            this.setData({
                showEndMessage: false
            });
        },

        endServer: function (e) {
            const patientData = Cache.get('patientData');
            const userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        admID: patientData.admID,
                        userID: userData.userID
                    }
                ]
            };
            // 结束服务
            $http.post('urlDeault', this, {
                code: '03100061',
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode == '0') {
                        this.setData({
                            toURL: res.result.toURL
                        });
                    }
                }
            });
        },

        //结束服务
        finish: function () {
            let that = this;
            let patientData = Cache.get('patientData');
            commonUtil.getOrders(patientData.admID, (res) => {
                if (res.errorCode == '0') {
                    if (res.result.flag == 'N') {
                        that.finishStatus();
                    } else {
                        uni.showModal({
                            title: '提示',
                            content: res.result.message,
                            confirmText: '确认',
                            success(res) {
                                if (res.confirm) {
                                    that.finishStatus();
                                }
                            }
                        });
                    }
                } else {
                    uni.showModal({
                        title: '提示',
                        content: res.errorMessage,
                        showCancel: false,
                        confirmText: '我知道了',
                        success(res) {}
                    });
                }
            });
        },

        /**取消结束 */
        cancelFinish: Util.debounce(function () {
            let { patientData } = this;
            commonUtil.cancelFinish(patientData.admID, (res) => {
                if (res.errorCode == '0') {
                    patientData.statusCode = 'A';
                    patientData.status = '接诊中';
                    let _this = this;
                    this.setData(
                        {
                            select: '-1',
                            patientData
                        },
                        () => {
                            setTimeout(() => {
                                _this.setData({
                                    select: _this.oldselect
                                });
                            }, 100);
                        }
                    );
                    Cache.set('patientData', patientData);
                }
            });
        }),

        canChangeFlag: function () {
            commonUtil.canChangeFlag('', (res) => {
                if (res.result == 'N') {
                    uni.showModal({
                        title: '提示',
                        content: '该患者已经结束服务,如需修改病历等信息，请先取消结束',
                        showCancel: false,
                        confirmText: '我知道了',
                        success(res) {}
                    });
                }
                this.setData({
                    patientData: Cache.get('patientData')
                });
            });
        },

        finishStatus: function (flag) {
            var that = this;
            const patientData = Cache.get('patientData');
            let data = {
                params: [
                    {
                        admID: patientData.admID,
                        flag: flag || 'N'
                    }
                ]
            };
            // 结束服务
            $http.post('urlDeault', this, {
                code: '03100116',
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode == '0') {
                        var endItem = res.result;
                        endItem.flag = flag;
                        // var knowButton = [{
                        //   text: '知道了',
                        //   code: '1^2^3'
                        // }]
                        // var signaButton = [{
                        //   text: '暂不签名',
                        //   code: '4^'
                        // }, {
                        //   text: '完成签名',
                        //   code: '2'
                        // }]
                        // var endButton = [{
                        //   text: '不操作',
                        //   code: '5^'
                        // }, {
                        //   text: '返回诊室',
                        //   code: '3'
                        // }]
                        var endButtonArr = endItem.button;
                        if (res.result.code == 3) {
                            that.endServer();
                        }
                        // if (res.result.code == 1) {
                        //   endButtonArr = knowButton
                        // } else if (res.result.code == 2) {
                        //   endButtonArr = signaButton
                        // } else if (res.result.code == 3) {
                        //   that.endServer()
                        //   endButtonArr = endButton
                        // }
                        this.setData({
                            endItem: endItem,
                            showEndMessage: true,
                            endButtonArr: endButtonArr
                        });
                    }
                }
            });
        },

        // 获取选中的select数据
        searchSelect: function (selectData) {
            console.log('Entry searchSelect callback', selectData);
            // H5 + Vue2 下 zpSelectComponent 通过 vnode.data.attrs.id 查找子组件不稳定,
            // 且 traverse 遇到无 $children 的节点会直接崩溃。优先用 Vue $refs。
            let child = (this.$refs && this.$refs.diagnostic) || null;
            if (!child && typeof this.zpSelectComponent === 'function') {
                try {
                    child = this.zpSelectComponent('#diagnostic');
                } catch (e) {
                    child = null;
                }
            }
            if (child && typeof child.searchSelect === 'function') {
                child.searchSelect(selectData);
            } else {
                // 兜底:写入缓存,等子组件 handlePageShow 时自取
                try {
                    Cache.set('searchSelect', selectData);
                } catch (e) {}
            }
        }
    }
};
</script>
<style>
/* pages/diagnosticEntry.wxss */
.diagnosticEntry {
    width: 100%;
    box-sizing: border-box;
    position: absolute;
    height: calc(100vh - 59px);
    background: #f4f7fb;
}

.header-wrapper {
    height: 74rpx;
    margin: 8rpx 16rpx;
    border-radius: 12rpx;
    overflow: hidden;
    background: #fff;
}

.diagnosticheader {
    display: flex;
    height: 74rpx;
    background-color: #ffffff;
    align-items: center;
}

.header-flex {
    flex: 1;
    text-align: center;
}

.diagnosticheaderBox {
    font-size: 28rpx;
    height: 74rpx;
    line-height: 74rpx;
}

.select {
    color: #1890ff;
    font-weight: 600;
}

.borderRight {
    border-right: 1rpx solid #eeeeee;
}

.diagnosticcontent {
    padding: 0 12rpx;
    position: absolute;
    top: 90rpx;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: auto;
}

.t200 {
    top: calc(40px + 100rpx);
}

.diagnostic-wrapper {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    overflow: auto;
}

.diagnostibutton {
    background: #1890ff;
    font-size: 30rpx;
    color: #fff;
    padding: 0;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100rpx;
    line-height: 100rpx;
    border-radius: 0px;
}

.multiBtn-content {
    height: 100rpx;
    font-size: 30rpx;
    color: #fff;
    padding: 0;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
}

.multiBtn-left {
    flex: 1;
    align-items: center;
    justify-content: center;
    display: flex;
    border-radius: 0 !important;
}

.multiBtn-right {
    flex: 1;
    align-items: center;
    justify-content: center;
    display: flex;
    background-color: #1890ff;
    color: #ffffff;
    border-radius: 0 !important;
}

/* header */
.templateHeader {
    background-color: #ffffff;
    display: flex;
    height: 80rpx;
}

.header-left {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
}

.header-center {
    flex: 1;
}

.header-right {
    flex: 2;
}

.header-left label {
    color: #666666;
    font-size: 32rpx;
}

.icon-style {
    transform: rotate(90deg);
    -webkit-transform: rotate(90deg);
    display: inline-block;
    margin-left: 5px;
}

/* content */
.page-content {
    background-color: #ffffff;
    /* height: 100%; */
    display: flex;
    border-top: 1rpx solid #f5f4f4;
    position: absolute;
    top: 80rpx;
    bottom: 0;
    left: 0;
    right: 0;
}

.left-wrap {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
}

.content-left {
    flex: 1;
    border-right: 3rpx solid #f5f4f4;
    position: relative;
}

.content-right {
    flex: 2;
    position: relative;
}

.right-wrap {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
}

.van-search {
    padding: 0 !important;
    height: 100%;
    margin: 0 5rpx;
}

.diagnosticEntry .weui-cell {
    padding: 18rpx 24rpx;
}

.roundBtn {
    padding: 0 !important;
    width: 100%;
    border-radius: 10rpx !important;
    margin-left: 10rpx !important;
    background: #fff !important;
    color: red !important;
    font-size: 30rpx !important;
    height: 74rpx !important;
    line-height: 74rpx !important;
}

.log {
    padding: 40rpx;
}

.dalong .weui-dialog {
    margin-top: -200rpx;
}
</style>
