<template>
    <view>
        <!-- pages/Entry/prescription/addPrescription/addPrescription.wxml -->
        <nav-bar :navbarData="navbarData"></nav-bar>
        <van-dialog id="van-dialog" />
        <view class="container addPrescription-page">
            <view class="diagnosticEntry plr20" :style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx)'">
                <!-- <view class="header-wrapper">
                    <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 !== 3 ? 'borderRight' : '')">{{ item.title }}</view>
                        </view>
                    </view>
                </view> -->
                <view>
                <view class="categoryTab">
                    <view
                        v-for="(item, idx) in objectArray"
                        :key="item.id"
                        class="categoryTabItem"
                        :class="active === idx ? 'active' : ''"
                        :data-index="idx"
                        @tap="()=> bindPickerChange(idx)"
                    >
                        {{ item.name }}
                    </view>
                </view>
                    <view class="fontS30 slectBox" v-if="!(select === 2 || select === 3)">
                        <picker @change="bindDiagPickerChange" :value="diagIndex" :range="diagList" range-key="diagDesc">
                            <view class="picker weui-select">
                                诊断：{{ (diagList[diagIndex] && diagList[diagIndex].diagDesc) || '请选择' }}
                                <mp-icon class="ml20" icon="arrow" color="black" :size="10"></mp-icon>
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="diagnosticcontent">
                    <view v-if="select === 0" class="addPres-subview">
                        <!-- 自定义处方 -->
                        <customDiagnostics
                            id="customDiagnostics"
                            ref="customDiagnostics"
                            :overlay="overlay"
                            :wListData="wList"
                            :gListcallData="callData"
                            :gListData="gList"
                            :active="active"
                            :editData="editData"
                            :diagData="currentDiag"
                            @addInfo="getAddInfo($event, { tagId: 'customDiagnostics' })"
                        ></customDiagnostics>
                    </view>
                    <view v-if="select === 1" class="addPres-subview">
                        <!-- 历史处方 -->
                        <historicalDiagnosis
                            id="historicalDiagnosis"
                            :addInfo="addInfo"
                            :active="active"
                            @changeSelect="changeSelect($event, { tagId: 'historicalDiagnosis' })"
                        ></historicalDiagnosis>
                    </view>
                    <view v-if="select === 2" class="addPres-subview">
                        <!-- 处方模板 -->
                        <templateDiagnostic
                            id="templateDiagnostic"
                            :addInfo="addInfo"
                            :active="active"
                            @changeSelect="changeSelect($event, { tagId: 'templateDiagnostic' })"
                        ></templateDiagnostic>
                    </view>
                    <view v-if="select === 3" class="addPres-subview">
                        <!-- 医嘱套 -->
                        <medicalOrderSet
                            id="medicalOrderSet"
                            :addInfo="addInfo"
                            :active="active"
                            @changeSelect="changeSelect($event, { tagId: 'medicalOrderSet' })"
                            @callDataPress="callDataPress($event, { tagId: 'medicalOrderSet' })"
                        ></medicalOrderSet>
                    </view>
                    <!-- </view>
				</view>
			</view> -->
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../../../../utils/cache';
import navBar from '@/pages/components/navbar/index';
import customDiagnostics from '@/pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/customDiagnostics';
import historicalDiagnosis from '@/pages/entryWrite/page/Entry/prescription/addPrescription/historicalDiagnosis/historicalDiagnosis';
import templateDiagnostic from '@/pages/entryWrite/page/Entry/prescription/addPrescription/templateDiagnostic/templateDiagnostic';
import medicalOrderSet from '@/pages/entryWrite/page/Entry/prescription/addPrescription/medicalOrderSet/medicalOrderSet';
// pages/Entry/prescription/addPrescription/addPrescription.js
// pages/entryWrite/page/Entry/prescription/addPrescription/1.js
const app = getApp();
import Dialog from '../../../../../../utils/dialog';
import { $http } from '../../../../../../config/https';
export default {
    components: {
        navBar,
        customDiagnostics,
        historicalDiagnosis,
        templateDiagnostic,
        medicalOrderSet
    },
    data() {
        return {
            select: 0,

            // 选中的值tabbox
            array: [
                {
                    title: '自定义医嘱'
                },
                {
                    title: '历史医嘱'
                },
                {
                    title: '医嘱模板'
                },
                {
                    title: '医嘱套'
                }
            ],

            // tab选项
            objectArray: [
                {
                    id: 0,
                    name: '西医及其他'
                },
                {
                    id: 1,
                    name: '草药'
                },
                // {
                //     id: 2,
                //     name: '检验检查'
                // },
                // {
                //     id: 3,
                //     name: '治疗'
                // }
            ],

            wList: [],

            // 西药数据
            gList: [],

            // 草药数据
            callData: {},

            // 草药数据
            active: 0,

            // 切换
            editData: {},

            // 回显数据
            addInfo: {},

            // 诊断列表
            diagList: [],

            // 选中的诊断下标
            diagIndex: 0,

            navbarData: {
                isGoBack: true,
                background: '',
                title: '添加医嘱',
                //导航栏 中间的标题
                bottom: false
            },

            height: app.globalData.height,

            // 西药草药是否有权限
            overlay: 'N',

            addText: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 接收wList
        this.optionsUrl(options);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        let { active } = this;
        // 验证是否有西药草药权限
        this.bindPickerChangeHttp(active);
        // 获取诊断列表
        this.getDiagList();
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.syncPageScrollLock();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.unlockPageScroll();
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.unlockPageScroll();
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    computed: {
        // 当前选中的诊断对象（含 id / diagCode / diagDesc）
        currentDiag: function () {
            return this.diagList[this.diagIndex] || {};
        }
    },
    methods: {
        syncPageScrollLock() {
            if (Number(this.active) === 2) {
                this.lockPageScroll();
            } else {
                this.unlockPageScroll();
            }
        },

        // H5 的页面根节点默认可滚动；检验检查页只允许内部 scroll-view 滚动。
        // 保存原值并在离开页面时恢复，避免影响其他页面。
        lockPageScroll() {
            if (typeof document === 'undefined' || this._pageScrollLockTargets) {
                return;
            }
            const targets = [document.documentElement, document.body, document.querySelector('uni-page'), document.querySelector('uni-page-body')].filter(Boolean);
            this._pageScrollLockTargets = targets.map((element) => ({
                element,
                overflow: element.style.overflow,
                overflowY: element.style.overflowY
            }));
            this._pageScrollLockTargets.forEach(({ element }) => {
                element.style.overflow = 'hidden';
                element.style.overflowY = 'hidden';
            });
            if (typeof window !== 'undefined' && typeof window.scrollTo === 'function') {
                window.scrollTo(0, 0);
            }
        },

        unlockPageScroll() {
            if (!this._pageScrollLockTargets) {
                return;
            }
            this._pageScrollLockTargets.forEach(({ element, overflow, overflowY }) => {
                element.style.overflow = overflow;
                element.style.overflowY = overflowY;
            });
            this._pageScrollLockTargets = null;
        },

        // 获取选中的select数据
        searchSelect: function (selectData) {
            // H5 + Vue3 下 zpSelectComponent 通过 vnode.data.attrs.id 查找子组件不稳定,
            // 优先使用 Vue $refs 进行子组件调用。
            let child = (this.$refs && this.$refs.customDiagnostics) || null;
            if (!child && typeof this.zpSelectComponent === 'function') {
                try {
                    child = this.zpSelectComponent('#customDiagnostics');
                } catch (e) {
                    child = null;
                }
            }
            if (child && typeof child.searchSelect === 'function') {
                child.searchSelect(selectData);
            } else {
                // 兜底:写入缓存,等子组件自取
                try {
                    Cache.set('searchSelect', selectData);
                } catch (e) {}
            }
        },

        // 点击切换
        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 // 添加按钮名称
                },
                () => {
                    this.templateDiagnostic = this.zpSelectComponent('#templateDiagnostic');
                    this.historicalDiagnosis = this.zpSelectComponent('#historicalDiagnosis');
                    this.customDiagnostics = this.zpSelectComponent('#customDiagnostics');
                    this.medicalOrderSet = this.zpSelectComponent('#medicalOrderSet');
                }
            );
        },

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

        // 接收 url传参
        optionsUrl: function (options) {
            let wList = JSON.parse(options.wList); //解析得到对象
            let active = JSON.parse(options.active); //解析得到对象
            let editData = options.editData ? JSON.parse(options.editData) : {}; //解析得到对象
            this.setData({
                wList,
                active,
                editData
            });
        },

        // 回调执行
        callDataFun: function (data) {
            this.setData({
                gList: data
            });
        },

        // 转发 grassPush 页面保存回传的 gList 给 grass 子组件
        // grassPush 是独立 page，navigateBack 后回到本页面，通过本方法把草药明细写回 grass 组件
        setGListPush: function (newGList) {
            let child = (this.$refs && this.$refs.customDiagnostics) || null;
            if (!child && typeof this.zpSelectComponent === 'function') {
                try {
                    child = this.zpSelectComponent('#customDiagnostics');
                } catch (e) {
                    child = null;
                }
            }
            if (child && typeof child.setGListPush === 'function') {
                child.setGListPush(newGList);
            }
        },

        // 转发 grassOrderSet 页面保存回传的 gList 给 grass 子组件
        // grassOrderSet 是独立 page，navigateBack 后回到本页面，通过本方法把医嘱套选中的草药明细写回 grass 组件
        setOrderSetPush: function (newGList) {
            let child = (this.$refs && this.$refs.customDiagnostics) || null;
            if (!child && typeof this.zpSelectComponent === 'function') {
                try {
                    child = this.zpSelectComponent('#customDiagnostics');
                } catch (e) {
                    child = null;
                }
            }
            if (child && typeof child.setGListPush === 'function') {
                child.setGListPush(newGList);
            }
        },

        // 获取子组件参数
        getAddInfo(e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            var obj = e.detail;
            console.log('[getAddInfo] 收到子组件 addInfo', { active: this.active, obj });
            // var obj = Object.assign(addInfo, e.detail);
            //  合并
            this.setData({
                addInfo: obj
            });
            // 关键修复：子组件保存成功后，把新医嘱 push 到本页面 wList/gList，并通知祖父页面 Entry.vue
            // 链路：Entry.vue (祖父 page) → prescription (祖父的子组件，含 callData 同步 + handlePageShow → wListPush)
            let { active, wList, gList } = this;
            if (active === 0) {
                // 西医
                if (obj && obj.medID) {
                    wList.unshift(obj);
                    console.log('[getAddInfo] 西医写入 wList, 当前长度=', wList.length, 'wList[0]=', wList[0]);
                    this.setData({ wList });
                }
            } else if (active === 1) {
                // 草药
                if (obj && obj.medID) {
                    gList.push({ gList: [obj] });
                    console.log('[getAddInfo] 草药写入 gList, 当前长度=', gList.length);
                    this.setData({ gList });
                }
            }
            // 通知祖父 Entry.vue：通过 callDataFun 把数据写入 Entry.vue 的 callData (data 字段)，
            // props 同步到 prescription.vue → watch callData → callDataClone，
            // 用户返回 Entry.vue 时 onShow 触发 pageLifetimes mixin → prescription.handlePageShow()
            // → 读 callDataClone 数组 → wListPush(item) / gListPush(item) 写 wList / gList。
            try {
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2];
                console.log('[getAddInfo] prevPage=', prevPage && prevPage.route, 'has callDataFun=', prevPage && typeof prevPage.callDataFun, 'has callData2Fun=', prevPage && typeof prevPage.callData2Fun, 'has wListPush=', prevPage && typeof prevPage.wListPush, 'has gListPush=', prevPage && typeof prevPage.gListPush);
                if (prevPage && typeof prevPage.callDataFun === 'function') {
                    // callDataFun 接收 data：草药路径下要求 data 是含 {medID, ordDesc, ordDose, ...} 的数组（gList 形态），
                    // 西药路径下是 [obj]（数组包一个 western obj）→ 走 prescription.handlePageShow 的数组分支 → wListPush
                    prevPage.callDataFun([obj]);
                    console.log('[getAddInfo] 已调 prevPage.callDataFun([obj])');
                } else if (prevPage && typeof prevPage.callData2Fun === 'function') {
                    // 草药兜底
                    prevPage.callData2Fun({ gList: [obj] });
                    console.log('[getAddInfo] 已调 prevPage.callData2Fun({gList:[obj]})');
                } else if (prevPage && typeof prevPage.wListPush === 'function') {
                    // 老链路兜底
                    prevPage.wListPush(obj, 'N');
                    console.log('[getAddInfo] 已调 prevPage.wListPush (兜底)');
                } else if (prevPage && typeof prevPage.gListPush === 'function') {
                    prevPage.gListPush(obj);
                    console.log('[getAddInfo] 已调 prevPage.gListPush (兜底)');
                }
            } catch (e) {
                console.warn('[getAddInfo] 通知父页面失败:', e);
            }
        },

        // 切换
        bindPickerChange: function (active) {
            const tabFn = () => {
                this.setData(
                    {
                        active: active,
                    },
                    () => {
                        this.syncPageScrollLock();
                        this.bindPickerChangeHttp(active); // 验证是否有西药草药权限
                        let { select } = this;
                        if (select === 1) {
                            this.historicalDiagnosis.childFun(); // 历史处方
                        }

                        if (select === 2) {
                            this.templateDiagnostic.childFun(); // 处方模板
                        }

                        if (select === 3) {
                            this.medicalOrderSet.childFun(); // 医嘱套
                        }
                    }
                );
            }
            if(this.$refs.customDiagnostics.unSaveData()){
                Dialog.confirm({
                    title: '提示',
                    message: '有未保存的医嘱，是否继续？',
                    context: this
                }).then(() => {
                    tabFn();
                }).catch(() => {
                    // 取消
                });
                return;
            }
            tabFn();
        },

        // 获取诊断列表（03050033）
        getDiagList: function () {
            let patientData = Cache.get('patientData');
            let { admID, patID } = patientData;
            $http.post('urlDeault', this, {
                code: '03050033',
                data: {
                    params: [
                        {
                            admID: admID,
                            patID: patID,
                            historyFlag: 'N',
                            historyType: 'O',
                            syFlag: 'N'
                        }
                    ]
                },
                success: function (res) {
                    if (res.errorCode === '0') {
                        let diagList = (res.result && res.result.diagList) || [];
                        // 编辑回显：根据 editData 中的 diagID 恢复诊断选中项
                        let diagIndex = 0;
                        let { editData } = this;
                        if (editData && editData.diagID && diagList.length) {
                            for (let i = 0; i < diagList.length; i++) {
                                if (diagList[i].id === editData.diagID) {
                                    diagIndex = i;
                                    break;
                                }
                            }
                        }
                        this.setData({
                            diagList: diagList,
                            diagIndex: diagIndex
                        });
                    }
                }
            });
        },

        // 切换诊断
        bindDiagPickerChange: function (e) {
            this.setData({
                diagIndex: e.detail.value
            });
        },

        // 验证是否有西药草药权限
        bindPickerChangeHttp: function (type) {
            // 检验检查无需西药/草药权限校验
            if (type == 2) {
                this.setData({
                    overlay: 'N'
                });
                return;
            }
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { userID, locID, hospID } = userData;
            let { admID } = patientData;
            $http.post('urlDeault', this, {
                code: '03050229',
                data: {
                    params: [
                        {
                            admID: admID,
                            //就诊记录ID
                            userID: userID,
                            //用户id
                            locID: locID,
                            //科室id
                            hospID: hospID,
                            //医院id
                            cmFlag: type == 1 ? 'Y' : '' //草药录入标志
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode == '0') {
                        let { select } = this;
                        if (select == 0) {
                            this.setData({
                                overlay: 'N'
                            });
                        }
                    }
                },
                fail: function (res) {
                    let { select } = this;
                    if (select == 0) {
                        Dialog.alert({
                            title: '提示',
                            message: res.errorMessage,
                            context: this
                        }).then(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                        });
                    }
                }
            });
        },

        changeSelect: function (obj, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(obj, _dataset);
            /* ---处理dataset end--- */
            var data = obj.detail.data;
            console.log('chuandi', data);
            let errStr = '';
            var newArr = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i].hasOwnProperty('invalid')) {
                    if (errStr) {
                        errStr = errStr + ',' + data[i].invalid;
                    } else {
                        errStr = data[i].invalid;
                    }
                } else {
                    var newObj = {
                        searchSelect: {
                            medDesc: data[i].ordDesc,
                            medID: data[i].medID,
                            medPrice: data[i].price ? data[i].price : data[i].qtyUnitList[0].price
                        },
                        typeList: {
                            unitDesc: data[i].ordDoseUnitDesc,
                            unitID: data[i].ordDoseUnitID
                        },
                        jl: data[i].ordDose,
                        comPrinciple: {
                            id: data[i].comPrincipleID,
                            descripts: data[i].comPrincipleDesc
                        },
                        decoctMethod: {
                            id: data[i].decoctMethodID,
                            descripts: data[i].decoctMethodDesc
                        }
                    };
                    newArr.push(newObj);
                }
            }
            if (errStr) {
                Dialog.alert({
                    title: '提示',
                    message: errStr + '为无效药',
                    context: this
                });
            }
            this.setData({
                select: obj.detail.select,
                gList: newArr
            });
        },

        callDataPress: function (obj, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(obj, _dataset);
            /* ---处理dataset end--- */
            var data = obj.detail.data;
            this.setData(
                {
                    callData: data
                },
                () => {
                    setTimeout(() => {
                        this.setData({
                            callData: {}
                        });
                    }, 1000);
                }
            );
        }
    }
};
</script>
<style>
/* pages/Entry/prescription/addPrescription/addPrescription.wxss */
/* 注：使用非 scoped 顶层样式，scoped 会给类名加 [data-v-xxx] 哈希，
   而 weui-cell 在子组件 mp-cell 内，scoped 不会穿透，命中失败。
   与 addDiagnostic.vue 不同的是：本页面外层父容器类名(.diagnosticEntry)
   可能会与全局同名类冲突，所以使用更具体的选择器（如 .addPrescription-page）
   限定作用域。 */
.plr20 {
    padding: 0 24rpx;
    box-sizing: border-box;
}

.container {
    width: 100%;
    height: 100%;
    background: #f4f7fb;
}

/*
 * 此页的导航栏为 fixed，内容区需要自己的明确高度。
 * 不能只用 100%，因为其祖先是 min-height，会在检验检查目录较长时被内容撑开，
 * 进而出现页面整体滚动并遮住“医嘱类别”。
 */
.addPrescription-page {
    height: 100vh;
    min-height: 0;
    overflow: hidden;
}

.diagnosticEntry {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}

.header-wrapper {
    flex-shrink: 0;
    margin: 0 0 8rpx;
    border-radius: 6rpx;
    overflow: hidden;
    background: #fff;
}

.diagnosticheader {
    display: flex;
    height: 88rpx;
    background-color: #fff;
    align-items: center;
    box-shadow: none;
}

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

.diagnosticheaderBox {
    font-size: 26rpx;
    height: 88rpx;
    line-height: 88rpx;
    color: #4b5563;
}

.select {
    color: #1687ff;
    font-weight: 600;
    position: relative;
}

.select::after {
    content: '';
    position: absolute;
    width: 36rpx;
    height: 3rpx;
    background: #1687ff;
    border-radius: 2rpx;
    left: 50%;
    transform: translateX(-50%);
    bottom: 6rpx;
}

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

.diagnosticcontent {
    /* 改为 flex 自然布局：父容器 .diagnosticEntry 是 flex column，
       header-wrapper 与 slectBox 流式占位，diagnosticcontent 用 flex:1 占据剩余空间，
       不再 absolute + 硬算 top，避免和 slectBox 重叠 */
    flex: 1;
    min-height: 0;
    overflow: hidden;
    /* padding: 8rpx 12rpx 0; */
    position: relative;
    display: flex;
    flex-direction: column;
}

/* 子组件外层包装 view：撑满父容器高度，使子组件内的
   absolute 定位的 .diagnostic-wrapper 能正常展开 */
.addPres-subview {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.slectBox {
    background: #fff;
    margin: 0 0 8rpx;
    border-radius: 6rpx;
    overflow: hidden;
}

.weui-select {
    display: flex;
    align-items: center;
    height: 58rpx;
    min-height: 58rpx;
    line-height: 58rpx;
    padding: 0 20rpx;
    color: #1f2937;
    font-size: 24rpx;
    border-bottom: 0;
}

/* 核心：重写 weui-cell 默认 padding 32rpx → 20rpx，修复左右 80rpx 留白
   使用 .addPrescription-page 限定作用域，避免污染其他页面 */
.addPrescription-page .diagnosticEntry .weui-cell {
    padding: 16rpx 20rpx;
}
.categoryTab{
    display: flex;
    flex-direction: row;
    justify-content: space-between; 
    background-color: #fff;
    border-bottom: 1px solid #edf1f6;
    font-weight: 700;
    color: #222;
}
.categoryTab .categoryTabItem{
    flex: 1;
    padding: 20rpx;
    box-sizing: border-box;
    font-size: 30rpx;
    text-align: center;
}
.categoryTab .categoryTabItem.active{
    color: #1687ff;
    border-bottom: 2px solid #1687ff;
}
</style>
