<template>
    <view class="diag-form">
        <!-- pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/western/western.wxml -->
        <mp-cells ext-class="my-cells">
            <mp-cell class="diag-form__cell" @tap.native="tapSelect">
                <view class="diag-form__line">
                    <view class="diag-form__label diag-form__label--required">
                        医嘱名称
                        <view class="redIcon" v-if="!(verification === 'N' || (searchSelect.medDesc && searchSelect.medDesc !== ''))">
                            <van-icon name="warning" color="red" />
                        </view>
                    </view>
                    <view class="diag-form__value">{{ searchSelect.medDesc || '请选择' }}</view>
                </view>
            </mp-cell>
            <mp-cell class="diag-form__cell">
                <view class="diag-form__line">
                    <view class="diag-form__label">备注</view>
                    <view class="diag-form__input-wrap">
                        <input class="diag-form__input" placeholder="请输入医嘱备注" :value="note" @input="bindnoteChange" @focus="inputFocus" @blur="inputBlur" />
                    </view>
                </view>
            </mp-cell>
            <picker
                @change="bindPickerChange9"
                :value="selectIndex9"
                :range="selectData9"
                range-key="xhDesc"
                @tap="tapselectData9"
                :disabled="selectData9.length < 2 || !searchSelect.medDesc || searchSelect.medDesc === ''"
            >
                <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                    <view class="diag-form__line">
                        <view class="diag-form__label">关联医嘱</view>
                        <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData9 && selectData9[selectIndex9] && selectData9[selectIndex9].xhDesc) || '请选择已保存未确认的医嘱') }}</view>
                    </view>
                </mp-cell>
            </picker>
            <mp-cell class="diag-form__cell" v-if="!(ordTypeCode === 'L' || ordTypeCode === 'E')">
                <view class="diag-form__line">
                    <view class="diag-form__label diag-form__label--required">
                        剂量
                        <view class="redIcon" v-if="!(verification === 'N' || (dose && dose !== ''))">
                            <van-icon name="warning" color="red" />
                        </view>
                    </view>
                    <view class="diag-form__input-wrap">
                        <input class="diag-form__input" placeholder="请输入剂量" :value="dose" @input="binddoseChange" type="digit" />
                    </view>
                </view>
            </mp-cell>
            <view v-if="!(ordTypeCode === 'L' || ordTypeCode === 'E')">
                <picker @change="bindPickerChange4" :value="selectIndex4" :range="selectData4" range-key="doseUnitDesc">
                    <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                        <view class="diag-form__line">
                            <view class="diag-form__label diag-form__label--required">
                                剂量单位
                                <view class="redIcon" v-if="!(verification === 'N' || (selectData4 && selectData4[selectIndex4] && selectData4[selectIndex4].doseUnitDesc))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData4 && selectData4[selectIndex4] && selectData4[selectIndex4].doseUnitDesc) || '请选择') }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </view>
            <view v-if="!(ordTypeCode === 'L' || ordTypeCode === 'E')" :class="dis === 'Y' ? 'dis' : ''">
                <picker @change="bindPickerChange2" :value="selectIndex2" :range="selectData2" range-key="descripts" :disabled="dis === 'Y' || pickersLocked">
                    <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                        <view class="diag-form__line">
                            <view class="diag-form__label diag-form__label--required">
                                频次
                                <view class="redIcon" v-if="!(verification === 'N' || (selectData2 && selectData2[selectIndex2] && selectData2[selectIndex2].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData2 && selectData2[selectIndex2] && selectData2[selectIndex2].descripts) || '请选择') }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </view>
            <view v-if="!(ordTypeCode === 'L' || ordTypeCode === 'E')" :class="dis === 'Y' ? 'dis' : ''">
                <picker @change="bindPickerChange3" :value="selectIndex3" :range="selectData3" range-key="descripts" :disabled="dis === 'Y' || pickersLocked">
                    <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                        <view class="diag-form__line">
                            <view class="diag-form__label diag-form__label--required">
                                用法
                                <view class="redIcon" v-if="!(verification === 'N' || (selectData3 && selectData3[selectIndex3] && selectData3[selectIndex3].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData3 && selectData3[selectIndex3] && selectData3[selectIndex3].descripts) || '请选择') }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </view>
            <view v-if="!(ordTypeCode === 'L' || ordTypeCode === 'E')" :class="(dis === 'Y' ? 'dis ' : '') + (pickersLocked ? 'diag-form__row--locked' : '')">
                <mp-cell class="diag-form__cell diag-form__cell--stepper">
                    <view class="diag-form__line diag-form__line--top">
                        <view class="diag-form__label diag-form__label--required">
                            疗程
                            <view class="redIcon" v-if="!(verification === 'N' || (stepper && stepper !== ''))">
                                <van-icon name="warning" color="red" />
                            </view>
                        </view>
                        <view class="diag-form__stepper-wrap diag-form__stepper-wrap--right">
                            <view class="diag-form__stepper" :class="{ 'is-disabled': dis === 'Y' }">
                                <text class="diag-form__stepper-btn" :class="{ 'is-disabled': Number(stepper) <= 0 }" @tap="onStepperMinus">−</text>
                                <input class="diag-form__stepper-input" type="number" :value="stepper" :disabled="dis === 'Y'" @input="onStepperInput" @blur="onStepperInput" />
                                <text class="diag-form__stepper-btn" @tap="onStepperPlus">+</text>
                            </view>
                            <text
                                :disabled="dis === 'Y'"
                                :class="'timebox ' + (timeSelect == index ? 'timeSelect' : '')"
                                @tap="tapTimebox"
                                :data-index="index"
                                v-for="(item, index) in arrayTime"
                                :key="index"
                            >
                                {{ item.descripts }}
                            </text>
                        </view>
                    </view>
                </mp-cell>
            </view>
            <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                <view class="diag-form__line">
                    <view class="diag-form__label diag-form__label--required">
                        数量
                        <view class="redIcon" v-if="!(verification === 'N' || (stepper2 && stepper2 !== ''))">
                            <van-icon name="warning" color="red" />
                        </view>
                    </view>
                    <view class="diag-form__stepper-wrap diag-form__stepper-wrap--right">
                        <view class="diag-form__stepper" :class="{ 'is-disabled': dis === 'Y' }">
                            <text class="diag-form__stepper-btn" :class="{ 'is-disabled': Number(stepper2) <= 0 }" @tap="onStepperMinus2">−</text>
                            <input class="diag-form__stepper-input" type="number" :value="stepper2" :disabled="dis === 'Y'" @input="onStepperInput2" @blur="onStepperInput2" />
                            <text class="diag-form__stepper-btn" @tap="onStepperPlus2">+</text>
                        </view>
                    </view>
                </view>
            </mp-cell>
            <picker @change="bindPickerChange5" :value="selectIndex5" :range="selectData5" range-key="unitDesc" :disabled="pickersLocked">
                <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                    <view class="diag-form__line">
                        <view class="diag-form__label diag-form__label--required">
                            数量单位
                            <view class="redIcon" v-if="!(verification === 'N' || (selectData5 && selectData5[selectIndex5] && selectData5[selectIndex5].unitDesc))">
                                <van-icon name="warning" color="red" />
                            </view>
                        </view>
                        <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData5 && selectData5[selectIndex5] && selectData5[selectIndex5].unitDesc) || '请选择') }}</view>
                    </view>
                </mp-cell>
            </picker>
            <view v-if="ordTypeCode === 'L'">
                <picker @change="bindPickerChange6" :value="selectIndex6" :range="selectData6" range-key="descripts">
                    <mp-cell class="diag-form__cell">
                        <view class="diag-form__line">
                            <view class="diag-form__label diag-form__label--required">
                                标本
                                <view class="redIcon" v-if="!(verification === 'N' || (selectData6 && selectData6[selectIndex6] && selectData6[selectIndex6].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (selectData6 && selectData6[selectIndex6] && selectData6[selectIndex6].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </view>
            <mp-cell class="diag-form__cell" v-if="ordSkinTestFlag !== 'N'">
                <view class="diag-form__line">
                    <view class="diag-form__label">是否皮试</view>
                    <switch class="diag-form__switch" :checked="switch1Checked" @change="switch1Change" />
                </view>
            </mp-cell>
            <view v-if="ordSkinTestFlag !== 'N'">
                <picker @change="bindPickerChange7" :value="selectIndex7" :range="selectData7" range-key="descripts" :disabled="pickersLocked">
                    <mp-cell class="diag-form__cell" :class="pickersLocked ? 'diag-form__row--locked' : ''">
                        <view class="diag-form__line">
                            <view class="diag-form__label">皮试备注</view>
                            <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData7 && selectData7[selectIndex7] && selectData7[selectIndex7].descripts) || '请选择') }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </view>
            <view :class="(dis === 'Y' ? 'dis ' : '') + (pickersLocked ? 'diag-form__row--locked' : '')">
                <picker @change="bindPickerChange8" :value="selectIndex8" :range="selectData8" range-key="recLocDesc" :disabled="dis === 'Y' || pickersLocked">
                    <mp-cell class="diag-form__cell">
                        <view class="diag-form__line">
                            <view class="diag-form__label diag-form__label--required">
                                执行科室
                                <view class="redIcon" v-if="!(verification === 'N' || (selectData8 && selectData8[selectIndex8] && selectData8[selectIndex8].recLocDesc))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ pickersLocked ? '未选择医嘱项' : ((selectData8 && selectData8[selectIndex8] && selectData8[selectIndex8].recLocDesc) || '请选择') }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </view>
            <picker @change="bindPickerChange1" :value="selectIndex1" :range="selectData1" range-key="descripts">
                <mp-cell class="diag-form__cell">
                    <view class="diag-form__line">
                        <view class="diag-form__label diag-form__label--required">
                            结算类型
                            <view class="redIcon" v-if="!(verification === 'N' || (selectData1 && selectData1[selectIndex1] && selectData1[selectIndex1].descripts))">
                                <van-icon name="warning" color="red" />
                            </view>
                        </view>
                        <view class="diag-form__picker">{{ (selectData1 && selectData1[selectIndex1] && selectData1[selectIndex1].descripts) || '请选择' }}</view>
                    </view>
                </mp-cell>
            </picker>
            <mp-cell class="diag-form__cell diag-form__cell--actions">
                <view class="diag-form__actions">
                    <button class="diag-form__action diag-form__action--plain" @tap="clearnbtn">清空</button>
                    <button class="diag-form__action diag-form__action--primary" @tap="addbtn" :disabled="isLoading">{{ isLoading ? '保存中' : '保存' }}</button>
                </view>
            </mp-cell>
        </mp-cells>
        <van-toast id="van-toast" />
        <van-dialog id="van-dialog" />
        <van-overlay :show="show">
            <view class="wrapper">
                <van-loading type="spinner" />
            </view>
        </van-overlay>
        <!--
            H5 端临时禁用：van-popup 在 H5 子组件作用域下未正确注册（与 van-stepper 同源问题），
            导致 :show=false 时也渲染出"快捷备注"字样。功能已暂时移除，避免误导用户。
            微信小程序端保留代码注释，待后续 change 评估。
        -->
        <van-popup
            v-if="false"
            :show="sheetShow"
            :custom-style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx) ;width:30%;'"
            position="left"
            :overlay="overlayFalse"
            @close="onClose"
        >
            <view>
                <view class="textCenter">快捷备注</view>
                <van-cell-group>
                    <van-cell @tap.native="tapPopupbox($event, { index })" :data-index="index" :title="item.descripts" v-for="(item, index) in ordNoteList" :key="index"></van-cell>
                </van-cell-group>
            </view>
        </van-popup>
    </view>
</template>

<script>
import Cache from '../../../../../../../../utils/cache';
// pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/western/western.js
const app = getApp();
import { $http } from '../../../../../../../../config/https';
import util from '../../../../../../../../utils/util';
import Dialog from '../../../../../../../../utils/dialog';
import Toast from '../../../../../../../../utils/toast';
export default {
    components: {},
    data() {
        return {
            selectIndex1: '',
            selectData1: [],

            //结算类型加载数据
            selectIndex2: '',

            selectData2: [],

            //频次下拉
            selectIndex3: '',

            selectData3: [],

            //用法下拉
            selectIndex4: '',

            selectData4: [],

            //单位下拉
            selectIndex5: '',

            selectData5: [],

            //数量单位
            selectIndex6: '',

            selectData6: [],

            //标本下拉
            selectIndex7: '',

            selectData7: [],

            //皮试备注下拉
            selectIndex8: '',

            selectData8: [],

            //执行科室下拉
            selectIndex9: '',

            selectData9: [],

            //关联医嘱下拉
            medID: '',

            //医嘱项id
            ordSetID: '',

            //医嘱套id
            stepper: '0',

            // 疗程值
            stepper2: '0',

            // 项目数量值
            timeSelect: '',

            // 时间选中
            dose: '',

            // 剂量
            note: '',

            // 备注
            arrayTime: [],

            searchSelect: {
                medID: '',
                medDesc: '',
                medCode: '',
                medPrice: '',
                medSubCatDesc: ''
            },

            //   选中的医嘱名称
            switch1Checked: false,

            // 派生 picker 锁态：未先选医嘱项时全部派生字段不可交互
            pickersLocked: true,

            // 皮试
            ordPriorityID: '',

            // 医嘱优先级
            guge: '',

            // 频次默认ID（selectData2Fun 异步加载后用于回填 selectIndex2）
            ordFreqID: '',

            // 用法默认ID（selectData3Fun 异步加载后用于回填 selectIndex3）
            ordUsageID: '',

            // 结算类型默认ID
            ordAdmReasonID: '',

            // 规格
            ordSkinTestFlag: 'Y',

            // 皮试是否显示
            ordTypeCode: '',

            // 检查检验
            ordToalCountO: '',

            // 计算总剂量
            ordToalCountI: '',

            // 计算总剂量
            dis: 'N',

            // 不可编辑
            show: true,

            // 遮罩层
            show1: true,

            // 遮罩层条件一
            show2: true,

            // 遮罩层条件二
            show3: true,

            // 遮罩层条件三
            errmessage: '',

            // 错误提示
            verification: 'N',

            // 验证
            sheetShow: false,

            overlayFalse: false,
            ordNoteList: [],
            height: app.globalData.height,
            isLoading: false,
            xhDesc: false,
            doseUnitDesc: '',
            descripts: '',
            unitDesc: '',
            recLocDesc: '',
            editDataClone: {}
        };
    },
    /**
     * 可以使用全局样式
     */
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {
        wListData: {
            type: Array,
            //类型
            default: () => [] //默认值
        },

        editData: {
            type: Object,
            //类型
            default: () => ({}) //默认值
        },

        diagData: {
            type: Object,
            //诊断对象（含 id / diagCode / diagDesc）
            default: () => ({}) //默认值
        }
    },
    created: function () {},
    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
        this.addInfo(); //组件值外传
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    moved: function () {
        // 在组件实例被移动到节点树另一个位置时执行
    },
    /**
     * 组件的方法列表
     */
    methods: {
        ready: function (options) {
            // 在组件在视图层布局完成后执行

            let { wListData, editDataClone: editData } = this;
            // 如果带 editData 回显（来自历史医嘱/医嘱套/医嘱模板），直接解锁派生 picker
            const hasEditData = JSON.stringify(editData) != '{}' && editData.medID;
            this.setData(
                {
                    //医嘱项id  // 有回显数据
                    medID: hasEditData ? editData.medID : '',
                    // 解锁派生 picker（即时反馈，避免 selectDataSome 异步期间仍显示"未选择医嘱项"）
                    pickersLocked: !hasEditData
                },
                () => {
                    this.selectData1Fun(); // 结算类型加载数据
                    this.selectData2Fun(); // 频次下拉
                    this.selectData3Fun(); // 用法下拉
                    this.selectDataSome(); //  获取医嘱项信息
                }
            );

            wListData.map((item, i) => {
                item.xhDesc = '序号' + item.xh + ':' + item.searchSelect.medDesc;
            });
            wListData.unshift({
                xhDesc: '请选择'
            });
            this.setData({
                // 关联序号
                selectData9:
                    JSON.stringify(editData) != '{}'
                        ? wListData.filter((item, i) => {
                              return item.xh !== editData.xh;
                          })
                        : wListData
            });
        },

        attached: function () {},

        // 获取选中的select数据
        searchSelectFun: function (selectData) {
            // TODO 刷新数据方法
            // 获取 医嘱名称
            let searchSelect = selectData;
            if (searchSelect) {
                // 兼容多种字段名：后端 03050019 接口可能用 id / medID / ordID 等命名
                const medID = searchSelect.medID || searchSelect.medId || searchSelect.ordID || searchSelect.id || '';
                console.log('[searchSelectFun] 选中药品:', { medID, medDesc: searchSelect.medDesc, searchSelect });
                // 关键修复：使用嵌套 key 路径 setData（uniapp H5 下对嵌套对象的支持更好）
                // 之前直接 setData({ searchSelect: newObj }) 在 H5 下整个对象替换有时不触发 render
                this.setData({
                    'searchSelect.medID': medID,
                    'searchSelect.medDesc': searchSelect.medDesc || '',
                    'searchSelect.medCode': searchSelect.medCode || '',
                    'searchSelect.medPrice': searchSelect.medPrice || '',
                    medID: medID,
                    ordSetID: searchSelect.ordSetID || searchSelect.ordSetId || '',
                    pickersLocked: false
                });
                // 清除Storage
                try {
                    Cache.remove('searchSelect');
                } catch (e) {}
                // 同步发起数据请求（不依赖 setData callback）
                this.selectData1Fun();
                this.selectData2Fun();
                this.selectData3Fun();
                this.selectDataSome();
            }
        },

        // 组件值外传
        addInfo: function () {
            let obj = this.objadd(); //要传给父组件的参数
            obj.WGType = 'W';
            this.$emit('addInfo', {
                detail: obj
            }); //通过triggerEvent将参数传给父组件
        },

        // 回显数据
        editDataFun: function (editData) {
            if (JSON.stringify(editData) != '{}') {
                if (editData.gList) {
                    //  不是西药回显
                    return false;
                }
                console.log(editData);
                this.setData({
                    selectIndex1: this.picakIndex('id', editData.selectIndex1.id, this.selectData1),
                    selectIndex2: this.picakIndex('id', editData.selectIndex2.id, this.selectData2),
                    selectIndex3: this.picakIndex('id', editData.selectIndex3.id, this.selectData3),
                    selectIndex4: this.picakIndex('doseUnitID', editData.selectIndex4.doseUnitID, this.selectData4),
                    selectIndex5: this.picakIndex('unitID', editData.selectIndex5.unitID, this.selectData5),
                    selectIndex6: this.picakIndex('id', editData.selectIndex6.id, this.selectData6),
                    selectIndex7: this.picakIndex('id', editData.selectIndex7.id, this.selectData7),
                    selectIndex8: this.picakIndex('recLocID', editData.selectIndex8.recLocID, this.selectData8),
                    selectIndex9: this.picakIndex('xh', editData.selectIndex9.xh, this.selectData9),
                    medID: editData.medID,
                    //医嘱项id
                    ordSetID: editData.ordSetID,
                    //医嘱套id
                    stepper: editData.stepper || '0',
                    // 疗程值
                    stepper2: editData.stepper2 || '0',
                    // 项目数量值
                    timeSelect: editData.timeSelect,
                    // 时间选中
                    dose: editData.dose,
                    // 剂量
                    note: editData.note,
                    // 备注
                    searchSelect: editData.searchSelect || {},
                    //   选中的医嘱名称
                    switch1Checked: editData.switch1Checked || false,
                    // 皮试
                    ordPriorityID: editData.ordPriorityID, // 医嘱优先级
                    // 修复：从历史医嘱/医嘱套跳进来时解锁派生 picker
                    pickersLocked: false
                });
            }
        },

        // 结算类型加载数据
        selectData1Fun: function (e) {
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { hospID } = userData;
            let { patID, admID } = patientData;
            $http.post('urlDeault', this, {
                code: '03100048',
                data: {
                    params: [
                        {
                            admID: admID || '',
                            // admID
                            patID: patID || '',
                            //患者id
                            hospID: hospID || '' //医院id
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                selectData1: res.result || [] // 结算类型
                            },
                            () => {
                                // 修复：原代码 `let { selectData1Fun: selectData1 } = this` 取的是方法 selectData1Fun，
                                // 改为直接访问 data 中的 selectData1 数组。
                                let { selectData1 } = this;
                                if (!Array.isArray(selectData1)) {
                                    return;
                                }
                                let hasDefault = false;
                                selectData1.map((item, i) => {
                                    if (item.defaultFlag === 'Y') {
                                        hasDefault = true;
                                        this.setData(
                                            {
                                                selectIndex1: this.picakIndex('id', item.id, selectData1),
                                                show1: false // 遮罩层条件1
                                            },
                                            () => {
                                                this.showFun(); // 遮罩层
                                            }
                                        );
                                    }
                                });
                                // 兜底：无 defaultFlag === 'Y' 时默认选第一个
                                if (!hasDefault) {
                                    this.setData(
                                        {
                                            selectIndex1: 0,
                                            show1: false
                                        },
                                        () => {
                                            this.showFun(); // 遮罩层
                                        }
                                    );
                                }
                            }
                        );
                    }
                }
            });
        },

        // 频次下拉
        selectData2Fun: function (e) {
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { hospID } = userData;
            let { admID } = patientData;
            let { medID } = this;
            $http.post('urlDeault', this, {
                code: '03050143',
                data: {
                    params: [
                        {
                            medID: medID || '',
                            //医嘱项id
                            admID: admID || '',
                            //就诊id
                            hospID: hospID || '' //医院id
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode == '0') {
                        this.setData(
                            {
                                selectData2: res.result || [],
                                // 频次下拉
                                selectIndex2: this.picakIndex('id', this.ordFreqID, res.result || []),
                                // 频次默认选中（修复：selectDataSome 中读 selectData2 时它还是 []，这里补救）
                                show2: false // 遮罩层条件2
                            },
                            () => {
                                this.showFun(); // 遮罩层
                            }
                        );
                    }
                }
            });
        },

        // 用法下拉
        selectData3Fun: function (e) {
            let userData = Cache.get('userData');
            let { hospID } = userData;
            let { medID } = this;
            $http.post('urlDeault', this, {
                code: '01040065',
                data: {
                    params: [
                        {
                            medID: medID || '',
                            //医嘱项id
                            hospID: hospID || '' //医院id
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode == '0') {
                        this.setData(
                            {
                                selectData3: res.data || [],
                                // 用法下拉
                                selectIndex3: this.picakIndex('id', this.ordUsageID, res.data || []),
                                // 用法默认选中（修复：selectDataSome 中读 selectData3 时它还是 []，这里补救）
                                show3: false // 遮罩层条件3
                            },
                            () => {
                                this.showFun(); // 遮罩层
                            }
                        );
                    }
                }
            });
        },

        // 获取医嘱项信息
        selectDataSome: function () {
            let patientData = Cache.get('patientData');
            let { admID } = patientData;
            let { medID, ordSetID } = this;
            if (!medID || medID === '') {
                return;
            }
            $http.post('urlDeault', this, {
                code: '03050020',
                data: {
                    params: [
                        {
                            admID: admID || '',
                            //就诊id
                            orders: [
                                {
                                    medID: medID || '',
                                    //医嘱项id
                                    ordSetID: ordSetID || '' //医嘱套id
                                }
                            ]
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    let errorData = res.errorData[0];
                    // 调试日志：诊断派生 picker 数据是否为空
                    if (res && res.data && res.data[0] && res.data[0].dataList) {
                        const dl = res.data[0].dataList;
                        console.log('[selectDataSome] 03050020 dataList:', {
                            doseUnitList: (dl.doseUnitList || []).length,
                            qtyUnitList: (dl.qtyUnitList || []).length,
                            specList: (dl.specList || []).length,
                            skinTestWayList: (dl.skinTestWayList || []).length,
                            recLocList: (dl.recLocList || []).length,
                            errorCode
                        });
                    } else {
                        console.warn('[selectDataSome] 03050020 异常响应:', JSON.stringify(res).slice(0, 200));
                    }
                    if (errorCode === '0') {
                        if (errorData) {
                            Dialog.alert({
                                title: '提示',
                                message: errorData.errorMessage,
                                context: this
                            });
                            this.setData({
                                searchSelect: {} //   选中的医嘱名称
                            });

                            return false;
                        }
                        let dataList = res.data[0].dataList;
                        let defaultData = res.data[0].defaultData;
                        let { durationList } = dataList;
                        let newDurationList = [durationList[0]]; // 需要只要天 不要周 月 pc需要 所以前端截取
                        // 修复：原代码 `let { searchSelectFun: searchSelect } = this` 取的是方法 searchSelectFun
                        // 改为直接访问 data.searchSelect 的 medPrice 字段（用嵌套 key 路径 setData）
                        // 同时不直接改 data.searchSelect 引用，避免覆盖前面 setData 的 medID/medDesc
                        // 缓存 defaultData 关键 ID，供 selectData2/3/1Fun 异步加载后回填 selectIndex
                        // 修复：selectDataSome 中读 this.selectData2/3/1 时它们还是 []，导致 picakIndex 返回 false
                        this.ordFreqID = defaultData.ordFreqID || '';
                        this.ordUsageID = defaultData.ordUsageID || '';
                        this.ordAdmReasonID = defaultData.ordAdmReasonID || '';
                        this.setData(
                            {
                                selectData4: dataList.doseUnitList || [],
                                // 单位下拉
                                selectData5: dataList.qtyUnitList || [],
                                // 数量单位
                                selectData6: dataList.specList || [],
                                // 标本下拉
                                selectData7: dataList.skinTestWayList || [],
                                //皮试备注下拉
                                selectData8: dataList.recLocList || [],
                                //执行科室下拉
                                arrayTime: newDurationList || [],
                                //疗程
                                ordNoteList: dataList.ordNoteList,
                                // 快捷内容
                                //  设置默认值
                                medID: defaultData.medID,
                                //医嘱项id
                                stepper: defaultData.ordDurQty || '1',
                                // 疗程值
                                stepper2: defaultData.ordQty || '1',
                                // 项目数量值
                                timeSelect: this.picakIndex('id', defaultData.ordDurationID, dataList.durationList),
                                // 时间选中
                                dose: defaultData.ordDose,
                                // 剂量
                                selectIndex1: this.picakIndex('id', defaultData.ordAdmReasonID, this.selectData1),
                                // 结算类型
                                selectIndex2: this.picakIndex('id', defaultData.ordFreqID, this.selectData2),
                                // 频次
                                selectIndex3: this.picakIndex('id', defaultData.ordUsageID, this.selectData3),
                                // 用法
                                selectIndex4: this.picakIndex('doseUnitID', defaultData.ordDoseUnitID, dataList.doseUnitList),
                                // 剂量单位
                                selectIndex5: this.picakIndex('unitID', defaultData.ordQtyUomID, dataList.qtyUnitList),
                                //数量单位
                                selectIndex6: this.picakIndex('id', defaultData.ordSpecID, dataList.specList),
                                //标本
                                selectIndex7: this.picakIndex('id', defaultData.ordSkinTestUsageID, dataList.skinTestWayList),
                                //皮试
                                selectIndex8: this.picakIndex('recLocID', defaultData.ordRecLocID, dataList.recLocList),
                                //执行科室
                                switch1Checked: defaultData.ordSkinTestFlagValue === 'Y' ? true : false,
                                //皮试
                                ordPriorityID: defaultData.ordPriorityID,
                                //医嘱优先级id
                                guge: defaultData.spec,
                                //规格

                                ordToalCountO: defaultData.ordToalCountO,
                                // 计算总剂量
                                ordToalCountI: defaultData.ordToalCountI,
                                // 计算总剂量

                                // 是否显示
                                ordSkinTestFlag: defaultData.ordSkinTestFlag,
                                // 皮试是否
                                ordTypeCode: defaultData.ordTypeCode,
                                // 检查检验
                                'searchSelect.medPrice': defaultData.ordPrice,
                                // 修复：原代码 `searchSelect: searchSelect` 把 searchSelectFun 方法对象赋给 data.searchSelect
                                // 改用嵌套 key 路径只更新价格字段，保留前面 searchSelectFun 设的 medID/medDesc
                                // 解锁派生 picker
                                pickersLocked: false
                            },
                            () => {
                                // 调试：列出当前所有 selectIndex 状态
                                console.log('[selectDataSome] callback: selectIndex1-8 重新计算前', {
                                    selectIndex1: this.selectIndex1,
                                    selectIndex2: this.selectIndex2,
                                    selectIndex3: this.selectIndex3,
                                    selectIndex4: this.selectIndex4,
                                    selectIndex5: this.selectIndex5,
                                    selectIndex8: this.selectIndex8,
                                    ordFreqID: this.ordFreqID,
                                    ordUsageID: this.ordUsageID,
                                    ordAdmReasonID: this.ordAdmReasonID,
                                    selectData1Len: (this.selectData1 || []).length,
                                    selectData2Len: (this.selectData2 || []).length,
                                    selectData4Len: (this.selectData4 || []).length,
                                    selectData5Len: (this.selectData5 || []).length,
                                    selectData8Len: (this.selectData8 || []).length
                                });
                                // 关键修复：selectData2/3Fun 早于 selectDataSome 启动时，
                                // selectData2/3 数组已就绪，但 this.ordFreqID/ordUsageID 还是空字符串，
                                // 导致 selectIndex2/3 默认选中失败（picakIndex 返回 false），
                                // 派生 picker 显示空、obj.selectIndex2/3 为空对象、save 时校验失败。
                                // 方案 1：用 defaultData.ordFreqID/ordUsageID 重新计算 selectIndex2/3（不依赖第二次 HTTP）
                                if (this.selectData2 && this.selectData2.length && this.ordFreqID) {
                                    this.setData({
                                        selectIndex2: this.picakIndex('id', this.ordFreqID, this.selectData2)
                                    });
                                }
                                if (this.selectData3 && this.selectData3.length && this.ordUsageID) {
                                    this.setData({
                                        selectIndex3: this.picakIndex('id', this.ordUsageID, this.selectData3)
                                    });
                                }
                                // 关键修复 2：setData 同步代码中 this.selectData4/5/8 仍是旧值（setData 是异步更新），
                                // 上一组 picakIndex 用的是 dataList.doseUnitList 等新数组算的（line 805-813），
                                // 但 dataList 字段名 / 结构可能与 setData 后 this 访问的数组不匹配。
                                // callback 中 this.selectData4/5/8 已就绪，用 defaultData 关键 ID 重新算 selectIndex4/5/8/6/7
                                const { defaultData: dd2 } = res.data[0];
                                if (this.selectData4 && this.selectData4.length && dd2 && dd2.ordDoseUnitID) {
                                    this.setData({
                                        selectIndex4: this.picakIndex('doseUnitID', dd2.ordDoseUnitID, this.selectData4)
                                    });
                                }
                                if (this.selectData5 && this.selectData5.length && dd2 && dd2.ordQtyUomID) {
                                    this.setData({
                                        selectIndex5: this.picakIndex('unitID', dd2.ordQtyUomID, this.selectData5)
                                    });
                                }
                                if (this.selectData6 && this.selectData6.length && dd2 && dd2.ordSpecID) {
                                    this.setData({
                                        selectIndex6: this.picakIndex('id', dd2.ordSpecID, this.selectData6)
                                    });
                                }
                                if (this.selectData7 && this.selectData7.length && dd2 && dd2.ordSkinTestUsageID) {
                                    this.setData({
                                        selectIndex7: this.picakIndex('id', dd2.ordSkinTestUsageID, this.selectData7)
                                    });
                                }
                                if (this.selectData8 && this.selectData8.length && dd2 && dd2.ordRecLocID) {
                                    this.setData({
                                        selectIndex8: this.picakIndex('recLocID', dd2.ordRecLocID, this.selectData8)
                                    });
                                }
                                // 结算类型 1：selectData1Fun 的 callback 用 defaultFlag === 'Y' 选默认项；
                                // 若接口没有 defaultFlag === 'Y' 的项，用 defaultData.ordAdmReasonID 重算
                                if (this.selectData1 && this.selectData1.length && this.ordAdmReasonID) {
                                    this.setData({
                                        selectIndex1: this.picakIndex('id', this.ordAdmReasonID, this.selectData1)
                                    });
                                }
                                // 方案 2：兜底再调一次 selectData2/3Fun（确保二次刷新默认值）
                                this.selectData2Fun();
                                this.selectData3Fun();
                                // 兜底：必填下拉在数据已加载但未匹配到默认值时，均选第一个
                                // 非必填项（selectIndex7 皮试备注）不设默认值
                                const fallbackIndex = (indexVal, list) => {
                                    return (indexVal === '' || indexVal === false || indexVal === null || indexVal === undefined) && list && list.length ? 0 : indexVal;
                                };
                                const sdi = {};
                                sdi.selectIndex1 = fallbackIndex(this.selectIndex1, this.selectData1);
                                sdi.selectIndex2 = fallbackIndex(this.selectIndex2, this.selectData2);
                                sdi.selectIndex3 = fallbackIndex(this.selectIndex3, this.selectData3);
                                sdi.selectIndex4 = fallbackIndex(this.selectIndex4, this.selectData4);
                                sdi.selectIndex5 = fallbackIndex(this.selectIndex5, this.selectData5);
                                sdi.selectIndex6 = fallbackIndex(this.selectIndex6, this.selectData6);
                                sdi.selectIndex8 = fallbackIndex(this.selectIndex8, this.selectData8);
                                this.setData(sdi);
                                let { editDataClone: editData } = this;
                                this.editDataFun(editData); // 回显数据
                                this.showFun(); // 遮罩层
                            }
                        );
                    }
                }
            });
        },

        // 结算类型切换
        bindPickerChange1: function (e) {
            this.setData({
                selectIndex1: e.detail.value
            });
        },

        // 频次切换
        bindPickerChange2: function (e) {
            this.setData(
                {
                    selectIndex2: e.detail.value
                },
                () => {
                    this.sumCount();
                }
            );
        },

        // 用法切换
        bindPickerChange3: function (e) {
            this.setData({
                selectIndex3: e.detail.value
            });
        },

        // 单位切换
        bindPickerChange4: function (e) {
            this.setData(
                {
                    selectIndex4: e.detail.value
                },
                () => {
                    this.sumCount();
                }
            );
        },

        // 数量切换
        bindPickerChange5: function (e) {
            this.setData(
                {
                    selectIndex5: e.detail.value
                },
                () => {
                    this.sumCount();
                }
            );
        },

        // 标本切换
        bindPickerChange6: function (e) {
            this.setData({
                selectIndex6: e.detail.value
            });
        },

        // 皮试切换
        bindPickerChange7: function (e) {
            this.setData({
                selectIndex7: e.detail.value
            });
        },

        //执行科室切换
        bindPickerChange8: function (e) {
            this.setData({
                selectIndex8: e.detail.value
            });
        },

        //关联医嘱切换
        bindPickerChange9: function (e) {
            this.setData(
                {
                    selectIndex9: e.detail.value
                },
                () => {
                    // 关联医嘱  关联后子医嘱的频次、用法、疗程、疗程单位、执行科室都不允许修改，并且与主医嘱保持一致
                    this.bindPickerChange9Edit();
                }
            );
        },

        // 医嘱名称跳转select
        tapSelect: function (e) {
            uni.navigateTo({
                //目的页面地址
                url: '/pages/components/searchSelect/searchSelect?code=03050019',
                success: function (res) {}
            });
        },

        // 疗程步进器
        onChangeStepper: function (e) {
            this.setData(
                {
                    stepper: e.detail
                },
                () => {
                    this.sumCount();
                }
            );
        },

        // 项目数量步进器
        onChangeStepper2: function (e) {
            this.setData({
                stepper2: e.detail
            });
        },

        // 原生 stepper - 疗程
        onStepperMinus: function () {
            const current = Number(this.stepper) || 0;
            if (current <= 0) return;
            const next = String(Math.max(0, current - 1));
            this.setData({ stepper: next }, () => this.onChangeStepper({ detail: next }));
        },

        onStepperPlus: function () {
            const current = Number(this.stepper) || 0;
            const next = String(Math.min(999, current + 1));
            this.setData({ stepper: next }, () => this.onChangeStepper({ detail: next }));
        },

        onStepperInput: function (e) {
            let raw = e && e.detail ? e.detail.value : '';
            if (raw === '' || raw === null || raw === undefined) {
                this.setData({ stepper: '0' }, () => this.onChangeStepper({ detail: '0' }));
                return;
            }
            // 过滤非数字(保留 0-9)
            raw = String(raw).replace(/[^0-9]/g, '');
            let n = parseInt(raw || '0', 10);
            if (isNaN(n)) n = 0;
            n = Math.max(0, Math.min(999, n));
            const next = String(n);
            this.setData({ stepper: next }, () => this.onChangeStepper({ detail: next }));
        },

        // 原生 stepper - 数量
        onStepperMinus2: function () {
            const current = Number(this.stepper2) || 0;
            if (current <= 0) return;
            const next = String(Math.max(0, current - 1));
            this.setData({ stepper2: next }, () => this.onChangeStepper2({ detail: next }));
        },

        onStepperPlus2: function () {
            const current = Number(this.stepper2) || 0;
            const next = String(Math.min(999, current + 1));
            this.setData({ stepper2: next }, () => this.onChangeStepper2({ detail: next }));
        },

        onStepperInput2: function (e) {
            let raw = e && e.detail ? e.detail.value : '';
            if (raw === '' || raw === null || raw === undefined) {
                this.setData({ stepper2: '0' }, () => this.onChangeStepper2({ detail: '0' }));
                return;
            }
            raw = String(raw).replace(/[^0-9]/g, '');
            let n = parseInt(raw || '0', 10);
            if (isNaN(n)) n = 0;
            n = Math.max(0, Math.min(999, n));
            const next = String(n);
            this.setData({ stepper2: next }, () => this.onChangeStepper2({ detail: next }));
        },

        // 锁态 picker 点击兜底（pointer-events: none 已阻止，正常不会触发）
        onLockedToast: function () {
            if (this.pickersLocked) {
                Dialog.alert({
                    title: '提示',
                    message: '请先选择医嘱项',
                    context: this
                });
            }
        },

        // 剂量变化
        binddoseChange: function (e) {
            this.setData(
                {
                    dose: e.detail.value
                },
                () => {
                    this.sumCount();
                }
            );
        },

        // 备注变化
        bindnoteChange: function (e) {
            this.setData({
                note: e.detail.value
            });
        },

        // 备注获取焦点
        inputFocus: function (e) {
            if (this.ordNoteList.length > 0) {
                this.setData({
                    sheetShow: true
                });
            }
        },

        // 备注失去焦点
        inputBlur: function (e) {
            if (this.ordNoteList.length > 0) {
                this.setData({
                    sheetShow: true
                });
            }
        },

        // 皮试切换
        switch1Change: function (e) {
            this.setData({
                switch1Checked: e.detail.value
            });
        },

        // 项目数量步进器
        tapTimebox: function (event) {
            let { dis } = this;
            let { currentTarget } = event;
            let { dataset } = currentTarget;
            if (dis === 'Y') {
                return false;
            }
            this.setData(
                {
                    timeSelect: dataset.index
                },
                () => {
                    this.sumCount();
                }
            );
        },

        // 清空
        clearnbtn: function (event) {
            this.setData({
                selectIndex1: '',
                selectIndex2: '',
                selectIndex3: '',
                selectIndex4: '',
                selectIndex5: '',
                selectIndex6: '',
                selectIndex7: '',
                selectIndex8: '',
                selectIndex9: '',
                medID: '',
                //医嘱项id
                ordSetID: '',
                //医嘱套id
                stepper: '0',
                // 疗程值
                stepper2: '0',
                // 项目数量值
                timeSelect: '',
                // 时间选中
                dose: '',
                // 剂量
                note: '',
                // 备注
                searchSelect: {},
                //   选中的医嘱名称
                switch1Checked: false,
                // 皮试
                ordPriorityID: '',
                // 医嘱优先级
                guge: '',
                // 规格
                ordToalCountO: '',
                // 计算总剂量
                ordToalCountI: '',
                // 计算总剂量
                dis: 'N',
                // 不可编辑
                errmessage: '',
                // 错误提示
                verification: 'N',
                // 验证
                sheetShow: false,
                overlayFalse: false,
                ordNoteList: []
            });
        },

        // 保存
        objadd: function (event) {
            // 前端传过去的新增对象
            // 修复：原代码 `selectDataXFun: selectDataX` 把方法误当作 data 数组，导致 selectData1[selectIndex1] 取到 undefined
            // 改为直接解构 data 中的 selectDataX 字段
            let {
                selectData1,
                //结算类型加载数据
                selectData2,
                //频次下拉
                selectData3,
                //用法下拉
                selectData4,
                //单位下拉
                selectData5,
                //数量单位
                selectData6,
                //标本下拉
                selectData7,
                //皮试备注下拉
                selectData8,
                //执行科室下拉
                selectData9,
                //关联医嘱下拉
                selectIndex1,
                selectIndex2,
                selectIndex3,
                selectIndex4,
                selectIndex5,
                selectIndex6,
                selectIndex7,
                selectIndex8,
                selectIndex9,
                medID,
                ordSetID,
                stepper,
                stepper2,
                timeSelect,
                searchSelect,
                arrayTime,
                dose,
                note,
                switch1Checked,
                ordPriorityID,
                editDataClone: editData,
                guge
            } = this;
            let obj = {
                selectIndex1: selectData1[selectIndex1] || {},
                selectIndex2: selectData2[selectIndex2] || {},
                selectIndex3: selectData3[selectIndex3] || {},
                selectIndex4: selectData4[selectIndex4] || {},
                selectIndex5: selectData5[selectIndex5] || {},
                selectIndex6: selectData6[selectIndex6] || {},
                selectIndex7: selectData7[selectIndex7] || {},
                selectIndex8: selectData8[selectIndex8] || {},
                selectIndex9: selectData9[selectIndex9] || {},
                medID: medID,
                //医嘱项id
                ordSetID: ordSetID,
                //医嘱套id
                stepper: stepper,
                // 疗程值
                stepper2: stepper2,
                // 项目数量值
                timeSelect: timeSelect,
                // 时间选中
                searchSelect: searchSelect,
                //   选中的医嘱名称
                arrayTime: arrayTime || [],
                //   时间
                ordDurationDesc: arrayTime[timeSelect] && arrayTime[timeSelect].descripts,
                ordDurationID: arrayTime[timeSelect] && arrayTime[timeSelect].id,
                dose: dose,
                //   剂量
                note: note,
                //   备注
                switch1Checked: switch1Checked,
                //   皮试
                ordPriorityID: ordPriorityID,
                //   医嘱优先级
                guge: guge,
                // 规格
                xh: editData.xh ? editData.xh : '', // 序号
                // 诊断信息（保存时由 prescription.vue 组装进 extvalue）
                diagID: (this.diagData && this.diagData.id) || '',
                diagCode: (this.diagData && this.diagData.diagCode) || ''
            };

            return obj;
        },

        // 保存
        addbtn: util.debounce(function (event) {
            this.setData({
                isLoading: true
            });
            // 修复：原代码 `let { searchSelectFun: searchSelect } = this` 把方法 searchSelectFun 误当作 data.searchSelect
            // 正确应该是解构 data 中的 searchSelect
            let { searchSelect, ordTypeCode, ordSkinTestFlag } = this;
            let obj = this.objadd();
            let requireData = [
                {
                    message: '医嘱名称不能为空',
                    value: searchSelect.medDesc
                },
                {
                    message: '结算类型不能为空',
                    value: obj.selectIndex1
                },
                {
                    message: '数量单位不能为空',
                    value: obj.selectIndex5
                },
                {
                    message: '执行科室不能为空',
                    value: obj.selectIndex8
                }
            ];
            if (ordTypeCode === 'L') {
                // 【检验项目】---无需用法用量等，需要标本
                requireData.push({
                    message: '标本不能为空',
                    value: obj.selectIndex6
                });
            }
            if (ordTypeCode !== 'L' || ordTypeCode !== 'E') {
                //【检验项目】---无需用法用量等，需要标本 【检查项目】--无需用法用量等
                requireData.push(
                    {
                        message: '用法不能为空',
                        value: obj.selectIndex3
                    },
                    {
                        message: '剂量不能为空',
                        value: obj.dose
                    },
                    {
                        message: '单位不能为空',
                        value: obj.selectIndex4
                    },
                    {
                        message: '频次不能为空',
                        value: obj.selectIndex2
                    }
                );
            }
            if (ordSkinTestFlag !== 'N') {
                //【非皮试药品】----无需皮试选项
                requireData.push({
                    message: '皮试备注不能为空',
                    value: obj.selectIndex7
                });
            }
            util.formRequire(requireData, (data) => {
                if (data && data.length > 0) {
                    this.setData({
                        isLoading: false
                    });
                    this.setData({
                        errmessage: data[0].message || '',
                        verification: 'Y'
                    });
                    Toast({
                        type: 'fail',
                        message: data[0].message,
                        context: this
                    });
                } else {
                    this.setData({
                        isLoading: false
                    });
                    // 修复：保存成功后应当通过 $emit('addInfo') 把数据传给 addPrescription 的 customDiagnostics，
                    // addPrescription 的 @addInfo="getAddInfo" 监听后会把数据写入 wList/gList，
                    // 并通知祖父页面 prescription.vue
                    this.addInfo();
                    uni.navigateBack({
                        delta: 1
                    });
                }
            });
        }),

        // 获取索引值picker
        picakIndex: function (name, id, arr) {
            // 修复：原实现在 arr 为空/找不到匹配项时返回 false 或 NaN，
            // 会导致 <picker :value="selectIndexN"> 渲染异常（NaN/false 在 H5 端会被转为 undefined/字符串），
            // 从而出现：默认选中第一项后点击"完成"无法回显、模板 selectDataN[selectIndexN] 一直为 undefined 的问题。
            // 兜底：找不到匹配项时返回 0（第一项），且始终返回数字类型。
            if (!arr || !arr.length) {
                return 0;
            }
            // id 为空/undefined 时也走默认 0
            if (id === '' || id === null || id === undefined) {
                return 0;
            }
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] && arr[i][name] == id) {
                    return parseInt(i, 10);
                }
            }
            return 0;
        },

        // 关联医嘱提示
        tapselectData9: function () {
            // 修复：原代码 `let { selectData9, searchSelectFun: searchSelect } = this` 取的是方法 searchSelectFun
            // 改为直接解构 data 中的 searchSelect
            let { selectData9, searchSelect } = this;
            if (!searchSelect.medDesc || searchSelect.medDesc === '') {
                Toast({
                    type: 'fail',
                    message: '请先选择医嘱',
                    context: this
                });
                return false;
            }
            if (selectData9.length < 2) {
                Toast({
                    type: 'fail',
                    message: '暂无可关联的医嘱',
                    context: this
                });
                return false;
            }
        },

        // 计算项目数量
        sumCount: function () {
            /* 
    1.总次数
    factor疗程单位下拉框数据,frequency/cycleDays/intervalDays 频次下拉框数据
    if cycleDays!=""{
      (疗程数*factor*frequency)/cycleDays
    } 
    else {
      (疗程数*factor*frequency)/intervalDays
    }
    向上取整
    2.总剂量
    ordToalCountO/ordToalCountI 默认数据中返回,molecule/denominator 剂量单位下拉框数据
    门诊
    if (ordToalCountO=="Y") {
      总剂量=(单次剂量*总次数*molecule)/denominator
      向上取整
    }else {
      剂量=(单次剂量*molecule)/denominator 向上取整
      总剂量=剂量*总次数
    }
    住院
    if (ordToalCountI=="Y") {
      总剂量=(单次剂量*总次数*molecule)/denominator
      向上取整
    }else {
      剂量=(单次剂量*molecule)/denominator 向上取整
      总剂量=剂量*总次数
    }
    3.总数量
    molecule/denominator 数量单位下拉框数据
    总数量=(总剂量*molecule)/denominator*/

            let jl = 1; // 总剂量
            let cs = 1; // 总次数
            let sum = 1; // 总数量
            let {
                arrayTime,
                timeSelect,
                // 修复：原代码 `selectData2Fun: selectData2` 把方法误当作 data 数组，
                // 改为直接访问 data 中的 selectData2
                selectData2,
                selectIndex2,
                selectData4,
                selectIndex4,
                selectData5,
                selectIndex5,
                stepper,
                ordToalCountO,
                ordToalCountI,
                dose
            } = this;
            let factor = arrayTime[timeSelect] && arrayTime[timeSelect].factor;
            let frequency = selectData2[selectIndex2] && selectData2[selectIndex2].frequency;
            let cycleDays = selectData2[selectIndex2] && selectData2[selectIndex2].cycleDays;
            let intervalDays = selectData2[selectIndex2] && selectData2[selectIndex2].intervalDays;

            // 剂量
            let molecule = selectData4[selectIndex4] && selectData4[selectIndex4].molecule;
            let denominator = selectData4[selectIndex4] && selectData4[selectIndex4].denominator;

            // 数量
            let molecule2 = selectData5[selectIndex5] && selectData5[selectIndex5].molecule;
            let denominator2 = selectData5[selectIndex5] && selectData5[selectIndex5].denominator;

            // 总次数
            if (cycleDays != '') {
                cs = (this.sumChange(stepper) * this.sumChange(factor) * this.sumChange(frequency)) / this.sumChange(cycleDays); // 总次数
            } else {
                cs = (this.sumChange(stepper) * this.sumChange(factor) * this.sumChange(frequency)) / this.sumChange(intervalDays); // 总次数
            }

            // 总剂量
            if (ordToalCountO == 'Y') {
                jl = (this.sumChange(dose) * this.sumChange(cs) * this.sumChange(molecule)) / this.sumChange(denominator);
            } else {
                var j = (this.sumChange(dose) * this.sumChange(molecule)) / this.sumChange(denominator);
                jl = this.sumChange(j) * this.sumChange(cs);
            }

            //总数量
            sum = (this.sumChange(jl) * this.sumChange(molecule2)) / this.sumChange(denominator2);
            this.setData({
                stepper2: Math.ceil(sum) // 数量 向上取整
            });
        },

        // 数量转换
        sumChange: function (sum) {
            if (sum == 0 || sum == '' || !sum) {
                sum = 1;
            }
            return parseFloat(sum);
        },

        // 关联医嘱  关联后子医嘱的频次、用法、疗程、疗程单位、执行科室都不允许修改，并且与主医嘱保持一致
        bindPickerChange9Edit: function () {
            let { selectData9, selectIndex9 } = this;
            let Edit = selectData9[selectIndex9];
            console.log(selectData9);
            if (selectData9[selectIndex9].xhDesc === '请选择') {
                this.setData({
                    selectIndex9: '',
                    dis: 'N' // 不可编辑
                });

                return false;
            }

            // 子医嘱不能再次被关联
            if (selectData9[selectIndex9].selectIndex9 && JSON.stringify(selectData9[selectIndex9].selectIndex9) != '{}') {
                Toast({
                    type: 'fail',
                    message: '该医嘱已关联其他医嘱',
                    context: this
                });
                this.setData({
                    selectIndex9: '',
                    dis: 'N' // 不可编辑
                });

                return false;
            }
            if (Edit) {
                this.setData({
                    selectIndex2: this.picakIndex('id', Edit.selectIndex2.id, this.selectData2),
                    //频次下拉
                    selectIndex3: this.picakIndex('id', Edit.selectIndex3.id, this.selectData3),
                    //用法下拉
                    timeSelect: Edit.timeSelect,
                    //疗程单位下拉
                    selectIndex8: this.picakIndex('recLocID', Edit.selectIndex8.recLocID, this.selectData8),
                    //执行科室下拉
                    stepper: Edit.stepper,
                    // 疗程
                    stepper2: Edit.stepper2,
                    // 数量
                    dis: 'Y' // 不可编辑
                });
            }
        },

        // 去掉遮罩层
        showFun: function () {
            let { show1, show2, show3 } = this;
            if (!show1 && !show2 && !show3) {
                this.setData({
                    show: false
                });
            }
        },

        // 快捷输入
        tapPopupbox: function (event, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(event, _dataset);
            /* ---处理dataset end--- */
            let { ordNoteList, note } = this;
            let { dataset } = event.currentTarget;
            let index = dataset.index;
            console.log(index);
            console.log(ordNoteList);
            note = note + ordNoteList[index].descripts;
            console.log(note);
            this.setData({
                note
            });
        },

        onClose() {
            console.log('占位：函数 onClose 未声明');
        }
    },
    watch: {
        editData: {
            handler: function (newVal, oldVal) {
                // 防御：newVal 可能为 undefined，deep watch 遍历时会访问 undefined.editData 抛错
                if (newVal && typeof newVal === 'object') {
                    this.editDataClone = newVal;
                }
            },

            immediate: true,
            deep: true
        },
        // 关键修复：监听 searchSelect 变化，自动同步 pickersLocked
        // 原因：setData({ pickersLocked: false }) 在某些路径（如 ready 钩子的 callback）下
        // 可能未生效到 render，watch 是更可靠的方式。
        'searchSelect.medDesc': {
            handler: function (newVal, oldVal) {
                const hasMedDesc = !!(newVal && newVal !== '');
                if (hasMedDesc && this.pickersLocked) {
                    this.setData({ pickersLocked: false });
                }
            }
        },
        // 调试：监听整个 searchSelect 对象被重置/清空
        searchSelect: {
            handler: function (newVal, oldVal) {
                console.log('[watch searchSelect]', {
                    old: oldVal,
                    new: newVal,
                    oldMedDesc: oldVal && oldVal.medDesc,
                    newMedDesc: newVal && newVal.medDesc
                });
            },
            deep: true
        }
    }
};
</script>
<style>
/* @import '../../../../diagnostic/addDiagnostic/customDiagnostics/customDiagnostics.css'; */
/* @import '../../../../diagnostic/diagnostic.css'; */
/* @import '../../../../Entry.css'; */

.diag-form {
    margin: 0 4rpx 12rpx;
}

.my-cells {
    display: block;
    margin: 0;
    border-radius: 14rpx;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 6rpx 18rpx rgba(15, 23, 42, 0.04);
}

.diag-form .weui-cell {
    min-height: 88rpx;
    padding: 16rpx 24rpx;
    align-items: center;
    box-sizing: border-box;
    position: relative;
}

.diag-form .weui-cell:after {
    content: "";
    position: absolute;
    left: 24rpx;
    right: 24rpx;
    bottom: 0;
    height: 1rpx;
    background: #f0f2f5;
    transform: scaleY(0.5);
    pointer-events: none;
}

.diag-form .weui-cell:last-child:after,
.diag-form .diag-form__cell--actions:after {
    display: none;
}

.diag-form .weui-cell__bd {
    width: 100%;
    min-width: 0;
}

.diag-form .weui-cell__ft {
    display: none;
}

.diag-form .weui-cell__ft:after {
    display: none;
}

.diag-form .diag-form__cell--actions .weui-cell__bd {
    width: 100%;
}

.diag-form__cell {
    font-size: 28rpx !important;
    color: #1f2937;
}

.diag-form__cell--stepper .weui-cell {
    padding-top: 20rpx;
    padding-bottom: 20rpx;
}

.diag-form__line {
    width: 100%;
    min-height: 66rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.diag-form__line--column {
    flex-direction: column;
    align-items: stretch;
    gap: 12rpx;
}

.diag-form__line--top {
    align-items: flex-start;
}

.diag-form__label {
    flex: 0 0 40%;
    max-width: 40%;
    color: #1f2937;
    font-size: 28rpx;
    font-weight: 500;
    line-height: 42rpx;
    text-align: left;
    box-sizing: border-box;
    padding-right: 20rpx;
    display: flex;
    align-items: center;
}

.diag-form__line--column .diag-form__label {
    flex: none;
    max-width: 100%;
    padding-right: 0;
}

.diag-form__line--top .diag-form__label {
    padding-top: 6rpx;
}

.diag-form__label--required:before {
    content: "*";
    color: #ef4444;
    margin-right: 4rpx;
}

.diag-form__picker,
.diag-form__value {
    flex: 0 0 60%;
    max-width: 60%;
    color: #3f4a5a;
    min-height: 42rpx;
    line-height: 42rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: right;
    word-break: break-all;
}

.diag-form__picker {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.diag-form__value {
    display: block;
    white-space: normal;
}

.diag-form__input-wrap {
    flex: 0 0 60%;
    max-width: 60%;
    min-height: 56rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.diag-form__input {
    width: 100%;
    min-height: 56rpx;
    line-height: 56rpx;
    text-align: right;
    color: #3f4a5a;
    font-size: 28rpx;
}

.diag-form__switch {
    margin-left: auto;
    transform: scale(0.86);
    transform-origin: right center;
}

.diag-form__stepper-wrap {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10rpx;
}

.diag-form__stepper-wrap--right {
    flex: 0 0 60%;
    max-width: 60%;
    justify-content: flex-end;
}

.diag-form__cell--stepper .diag-form__stepper-wrap--right {
    justify-content: flex-end;
    row-gap: 10rpx;
}

.diag-form__cell--actions {
    padding-top: 8rpx;
}

.diag-form__actions {
    width: 100%;
    min-height: 76rpx;
    display: flex;
    align-items: center;
    gap: 14rpx;
    box-sizing: border-box;
}

.diag-form__action {
    flex: 1;
    height: 72rpx;
    line-height: 72rpx;
    border-radius: 999rpx !important;
    font-size: 28rpx;
    padding: 0;
    margin: 0;
    font-weight: normal;
}

.diag-form__action--plain {
    border: 1rpx solid #e5e7eb;
    background: #fff;
    color: #4b5563;
}

.diag-form__action--primary {
    background-color: #1890ff;
    color: #ffffff;
    border: 0;
}

.diag-form__action:after {
    border: initial;
}

.timebox {
    position: relative;
    display: inline-block;
    box-sizing: border-box;
    vertical-align: middle;
    border: 0;
    background-color: #f4f6f8;
    color: #4b5563;
    padding: 4rpx 16rpx;
    border-radius: 4rpx;
    font-size: 24rpx;
    line-height: 32rpx;
}

.timeSelect {
    color: #fff;
    background-color: #1687ff;
}

.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.redIcon {
    display: inline-block;
    vertical-align: middle;
    margin-left: 6rpx;
}

/* 原生 stepper 样式（替代 van-stepper） */
.diag-form__stepper {
    display: inline-flex;
    align-items: center;
    border: 1rpx solid #e5e7eb;
    border-radius: 4rpx;
    overflow: hidden;
    background: #fff;
    height: 52rpx;
}

.diag-form__stepper.is-disabled {
    opacity: 0.5;
    pointer-events: none;
}

.diag-form__stepper-btn {
    width: 52rpx;
    height: 52rpx;
    line-height: 52rpx;
    text-align: center;
    font-size: 28rpx;
    color: #4b5563;
    background: #f4f6f8;
    flex-shrink: 0;
}

.diag-form__stepper-btn.is-disabled {
    opacity: 0.4;
    pointer-events: none;
}

.diag-form__stepper-input {
    width: 80rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    font-size: 28rpx;
    border: none;
    outline: none;
    background: #fff;
    color: #1f2937;
    flex-shrink: 0;
    box-sizing: border-box;
    padding: 0;
}

/* 派生 picker 锁态 */
.diag-form__row--locked {
    opacity: 0.55;
    pointer-events: none;
}

.diag-form__row--locked .diag-form__picker,
.diag-form__row--locked .diag-form__value {
    color: #cbd5e1;
}
</style>
