<template>
    <view>
        <view class="diagnostic-wrapper">
            <view style="background: #fff">
                <!-- <view class="row">
                    <mp-cell class="fontS30">
                        <view class="BaseInfo">基本信息</view>
                        <view class="row boxcontentBox">
                            <view class="baseinfo1">{{ baseInfo.patAge }}</view>
                            <view class="baseinfo1 borderright">{{ baseInfo.patSexDesc }}</view>
                            <view class="baseinfo1 borderright">{{ baseInfo.patName }}</view>
                        </view>
                    </mp-cell>
                </view> -->
                <view style="border-top: 8rpx solid #eee;" v-if="patientData.changeDataFlag != 'N'">
                    <picker v-if="historyRecordList.length > 0" @change="bindHistoryRecordChange" :value="historyRecordIndex" :range="historyRecordList" range-key="name">
                        <mp-cell class="diag-form__cell">
                            <view class="diag-form__line">
                                <view class="diag-form__label">历史病历</view>
                                <view class="diag-form__picker">
                                    {{ selectedHistoryRecord.name || (historyRecordList[historyRecordIndex] && historyRecordList[historyRecordIndex].name) || '请选择' }}
                                </view>
                            </view>
                        </mp-cell>
                    </picker>
                    <mp-cell v-else class="diag-form__cell" @tap="showNoHistoryRecord">
                        <view class="diag-form__line">
                            <view class="diag-form__label">历史病历</view>
                            <view class="diag-form__picker empty-history-record">
                                {{ historyRecordLoading ? '加载中...' : '暂无可引用病历' }}
                            </view>
                        </view>
                    </mp-cell>
                </view>
            </view>
            <view style="padding-bottom: 60rpx;">
                <mp-cells ext-class="my-cells">
                    <view class="row" v-for="(item, index) in admList" :key="index">
                        <van-cell
                            value-class="leftFont"
                            title-width="120rpx"
                            class="fontS30"
                            v-if="item.IEMRTempElementCode == 'DE05.01.025.00' && item.elementTypeCode == 'Labelarea'"
                            is-link
                            center
                            clickable
                            use-label-slot
                            :url="item.IEMRTempElementLinkAddress"
                        >
                            <view slot="title">
                                <view :class="'van-cell-text ' + (item.IEMRTempElementRequired == 'Y' ? 'required' : '') + ' '">{{ item.IEMRTempElementDesc }}</view>
                            </view>
                            <block v-for="(item, index1) in diagnoseObj" :key="index1">
                                <view :id="'goods-' + item.gid">{{ index + 1 }}、{{ item.ICDDesc }}</view>
                            </block>
                        </van-cell>

                        <van-cell
                            value-class="leftFont"
                            class="fontS30"
                            title-width="120rpx"
                            :title="item.IEMRTempElementDesc"
                            v-if="item.IEMRTempElementCode == 'DE06.00.289.00' && item.elementTypeCode == 'Labelarea'"
                            is-link
                            center
                            clickable
                            use-label-slot
                            :url="item.IEMRTempElementLinkAddress"
                        >
                            <view class="chufang-box">
                                <block v-for="(itemName, index1) in orderPresc" :key="index1">
                                    <view class="chufang2">
                                        <!-- <view class="item-aside"></view> -->
                                        <view class="item-main">
                                            <view class="onebox">
                                                <view class="one">
                                                    <view class="left">
                                                        <!-- 中药 -->
                                                        <view class="name" v-if="itemName.prescTypeCode == 'CM'" style="display: flex">
                                                            <view style="flex: 0 0 auto">{{ index + 1 }}、</view>
                                                            <view style="flex: 1 1 auto">
                                                                <block v-for="(itemName, index2) in itemName.comPresc" :key="index2">
                                                                    <view class="herbstemp">
                                                                        <view
                                                                            class="herbs-item-comPrincipletemp"
                                                                            :style="
                                                                                'background-color:' +
                                                                                (itemName.comPrinciple == '君'
                                                                                    ? '#FFA23E'
                                                                                    : itemName.comPrinciple == '臣'
                                                                                    ? '#39D1D1'
                                                                                    : itemName.comPrinciple == '佐'
                                                                                    ? '#FA5AB2'
                                                                                    : itemName.comPrinciple == '使'
                                                                                    ? '#AA71F9'
                                                                                    : '')
                                                                            "
                                                                        >
                                                                            {{ itemName.comPrinciple + '药' }}
                                                                        </view>
                                                                        <view class="herbs-item-medItemMed">{{ itemName.ordDesc }} {{ itemName.spec }}</view>
                                                                        <view class="herbs-item-decoctMethodMed">{{ itemName.comMark }}</view>
                                                                    </view>
                                                                </block>
                                                                <view class="child2">
                                                                    <text>
                                                                        用法：{{ itemName.comPresc[0].durStr }}，{{ itemName.comPresc[0].frequenceDesc }}，
                                                                        {{ itemName.prescDoseQty }}，{{ itemName.prescUsageExplainDesc }} ， {{ itemName.prescUsageDesc }}
                                                                    </text>
                                                                </view>
                                                            </view>
                                                        </view>
                                                    </view>
                                                </view>
                                            </view>
                                        </view>
                                    </view>

                                    <!-- 西药 -->

                                    <block v-if="itemName.prescTypeCode == 'PT'">
                                        <view v-if="itemName.childOrd.length > 0">
                                            <view>{{ index + 1 }}、 {{ itemName.ordDesc }}</view>
                                            <view class="chufang1">
                                                <view class="item-aside"></view>
                                                <view class="item-main">
                                                    <view class="onebox">
                                                        <view class="one">
                                                            <view class="left">
                                                                <view class="name">
                                                                    <!-- <text>{{val.ordDesc}}</text> -->
                                                                </view>
                                                                <view class="yaopinguige flex-row">
                                                                    <view class="guige">
                                                                        <text>{{ itemName.spec }}</text>
                                                                    </view>
                                                                    <view class="num">
                                                                        x
                                                                        <text>{{ itemName.qtyUomStr }}</text>
                                                                    </view>
                                                                    <view class="ke">{{ itemName.doseUnitStr }}</view>
                                                                </view>
                                                            </view>
                                                            <view class="right">
                                                                x
                                                                <text>{{ itemName.durStr }}</text>
                                                            </view>
                                                        </view>
                                                    </view>
                                                </view>
                                            </view>

                                            <view v-for="(val, idx) in itemName.childOrd" :key="idx">
                                                <view class="chufang1">
                                                    <view class="item-aside"></view>
                                                    <view class="item-main">
                                                        <view class="onebox">
                                                            <view class="one">
                                                                <view class="left">
                                                                    <view class="name">
                                                                        <text>{{ val.ordDesc }}</text>
                                                                    </view>
                                                                    <view class="yaopinguige flex-row">
                                                                        <view class="guige">
                                                                            <text>{{ val.spec }}</text>
                                                                        </view>
                                                                        <view class="num">
                                                                            x
                                                                            <text>{{ val.qtyUomStr }}</text>
                                                                        </view>
                                                                        <view class="ke">{{ val.doseUnitStr }}</view>
                                                                    </view>
                                                                </view>
                                                                <view class="right">
                                                                    x
                                                                    <text>{{ val.durStr }}</text>
                                                                </view>
                                                            </view>
                                                        </view>
                                                    </view>
                                                </view>

                                                <!-- <view>{{val.ordDesc}}</view> -->
                                            </view>
                                            <view class="use">用法：{{ itemName.frequenceDesc }}，{{ itemName.usageDesc }}</view>
                                        </view>
                                        <view v-if="itemName.childOrd.length == 0">
                                            <view>{{ index + 1 }}、{{ itemName.ordDesc }} {{ itemName.spec }} {{ itemName.qtyUomStr }}</view>
                                            <view class="use">
                                                用法：{{ itemName.frequenceDesc }}，{{ itemName.usageDesc }}，{{ '每次' + itemName.doseUnitStr }}，{{ itemName.durStr }}
                                            </view>
                                        </view>
                                    </block>
                                </block>
                            </view>
                        </van-cell>

                        <view slot="title" v-if="item.elementTypeCode == 'RadioBox'">
                            <view
                                style="font-size: 30rpx; text-align: left !important; margin-left: 30rpx"
                                :class="'van-cell-text ' + (item.IEMRTempElementRequired == 'Y' ? 'required' : '') + ' '"
                            >
                                {{ item.IEMRTempElementDesc }}
                            </view>
                            <van-radio-group
                                group
                                :value="item.IEMRTempElementData"
                                :data-name="item.IEMRTempElementDesc"
                                @change="onChangeCheckBox($event, { name: item.IEMRTempElementDesc })"
                            >
                                <van-cell title-width="100px">
                                    <van-radio style="font-size: 30rpx" :name="elementDataset.id" v-for="(elementDataset, index1) in item.elementDataset" :key="elementDataset.id">
                                        {{ elementDataset.descripts }}
                                    </van-radio>
                                </van-cell>
                                <!-- <van-radio style="font-size: 30rpx;" wx:for-item="elementDataset" wx:key="{{elementDataset.id}}" wx:for="{{item.elementDataset}}" name="{{elementDataset.id}}">
							{{elementDataset.descripts}}
						</van-radio> -->
                            </van-radio-group>
                        </view>

                        <view v-else>
                            <van-cell-group>
                                <van-cell
                                    title-width="120rpx"
                                    class="fontS30"
                                    value-class="leftFont"
                                    :value="!item.IEMRTempElementData || item.IEMRTempElementData == '' ? ' ' : item.IEMRTempElementData"
                                    is-link
                                    center
                                    clickable
                                    use-label-slot
                                    :data-value="item.IEMRTempElementData"
                                    :data-tempCode="item.elementTypeCode"
                                    :data-name="item.IEMRTempElementDesc"
                                    :data-id="item.IEMRTempElementID"
                                    v-if="item.elementTypeCode !== 'Labelarea'"
                                    @tap.native="
                                        tapSelect($event, {
                                            value: item.IEMRTempElementData,
                                            tempCode: item.elementTypeCode,
                                            name: item.IEMRTempElementDesc,
                                            id: item.IEMRTempElementID
                                        })
                                    "
                                    style="flex: 1 1 auto"
                                >
                                    <view slot="title" v-if="item.elementTypeCode != 'RadioBox'">
                                        <view :class="'van-cell-text ' + (item.IEMRTempElementRequired == 'Y' ? 'required' : '') + ' '">{{ item.IEMRTempElementDesc }}</view>
                                    </view>
                                </van-cell>
                            </van-cell-group>
                        </view>
                    </view>
                </mp-cells>
                <!-- 信息采集表单 -->
                <view class="info-collection" v-if="formData.length > 0">
                    <view class="info-item" v-for="(item, index) in formData" :key="index">
                        <view class="info-label" :class="{'required': item.state && item.state.includes('required')}">{{ item.label }}</view>
                        <view class="info-control" :class="{'info-readonly': isReadonlyField(item)}">
                            <!-- 下拉选择 -->
                            <picker
                                v-if="item.type === 'select' || item.type === 'checkbox'"
                                mode="selector"
                                :range="item.datas"
                                range-key="label"
                                :value="getSelectIndex(item.key)"
                                :data-key="item.key"
                                :data-ranges="item.datas"
                                :disabled="isReadonlyField(item)"
                                @change="pickerChange"
                            >
                                <view class="info-value" :class="{ 'info-placeholder': !dataKeyObj[item.key] }">
                                    {{ dataKeyObj[item.key] || '请选择' }}
                                </view>
                            </picker>
                            <!-- 单选 -->
                            <radio-group
                                v-else-if="item.type === 'radio'"
                                class="info-radio-group"
                                :data-key="item.key"
                                :disabled="isReadonlyField(item)"
                                @change="pickerChange"
                            >
                                <label class="info-radio-label" v-for="(option, idx) in item.datas" :key="idx">
                                    <radio :value="String(option.value)" :checked="String(dataKeyObj[item.key + 'code']) === String(option.value)" :disabled="isReadonlyField(item)" color="#1890ff" />{{ option.label }}
                                </label>
                            </radio-group>
                            <!-- 日期选择 -->
                            <picker
                                v-else-if="item.type === 'date'"
                                mode="date"
                                :value="dataKeyObj[item.key]"
                                :data-key="item.key"
                                :disabled="isReadonlyField(item)"
                                @change="pickerChange"
                            >
                                <view class="info-value" :class="{ 'info-placeholder': !dataKeyObj[item.key] }">
                                    {{ dataKeyObj[item.key] || '请选择日期' }}
                                </view>
                            </picker>
                            <!-- 多行文本 -->
                            <textarea
                                v-else-if="item.type === 'textarea'"
                                class="info-textarea"
                                :value="dataKeyObj[item.key] || ''"
                                :data-key="item.key"
                                :disabled="isReadonlyField(item)"
                                @input="inputChange"
                                placeholder="请输入"
                            />
                            <!-- 图片（支持单张/多张，多张可删除） -->
                            <view v-else-if="item.type === 'casepluginimage'" class="info-image-box">
                                <block v-if="getImageList(item.key).length > 0">
                                    <view
                                        class="info-image-item"
                                        v-for="(imgUrl, imgIdx) in getImageList(item.key)"
                                        :key="imgIdx"
                                    >
                                        <image
                                            class="info-image"
                                            :src="urlImage(imgUrl)"
                                            mode="aspectFill"
                                            @error="onImageError(item.key, imgIdx)"
                                            @tap="previewImage(item.key, imgIdx)"
                                        />
                                        <view
                                            class="info-image-del"
                                            v-if="!isReadonlyField(item)"
                                            @tap.stop="removeImage(item.key, imgIdx)"
                                        >×</view>
                                    </view>
                                </block>
                                <view v-else class="info-image-empty">暂无图片</view>
                            </view>
                            <!-- 单行文本 -->
                            <input
                                v-else
                                class="info-input"
                                :value="dataKeyObj[item.key] || ''"
                                :data-key="item.key"
                                :disabled="isReadonlyField(item)"
                                @input="inputChange"
                                placeholder="请输入"
                            />
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 保存按钮固定底部 -->
        <view class="fixed-save-bar">
            <button
                v-if="patientData.changeDataFlag != 'N'"
                class="multiBtn-right"
                :disabled="formData.length > 0 ? isInfoSubmitting : isLoading"
                @tap="formData.length > 0 ? formSubmit() : add()"
            >
                {{ formData.length > 0 ? (isInfoSubmitting ? '提交中...' : '保存') : (isLoading ? '保存中' : '保存') }}
            </button>
        </view>
    </view>
</template>

<script>
import Cache from '../../../../../utils/cache';
// pages/diagnosticEntry/medicalRecord/medicalRecord.js
import { $http } from '../../../../../config/https';
import Util from '../../../../../utils/util.js';
import commonUtil from '../../../../../utils/common.js';
const app = getApp();
export default {
    components: {},
    data() {
        return {
            imgHost: 'https://hlwyy.scsmysgkyy.cn',
            // 图片加载失败的 key 集合，用于隐藏加载失败的图片
            imageLoadError: {},
            // hasSave:false, //是否保存完成,true是保存后,默认false
            diagTypeIndex: 0,

            //门诊
            diagType: [],

            //门诊
            admList: [],

            userName: '',

            baseInfo: {
                patAge: '',
                patSexDesc: '',
                patName: ''
            },

            diagnoseObj: [],
            orderPresc: [],
            childOrd: [],
            selectShow: false,
            height: app.globalData.height,
            editData: [],
            requiredData: [6, 7, 22, 8, 10, 12],

            patientData: {
                changeDataFlag: ''
            },

            isLoading: false,
            result: '',
            elementDataset: [],
            dataSource: [],
            entryedText: '',
            calldiagnoseObj: '',
            callorderPresc: '',
            name: '',

            val: {
                ordDesc: '',
                spec: '',
                qtyUomStr: '',
                doseUnitStr: '',
                durStr: ''
            },
            // 信息采集表单相关
            TempHtmlObj: {}, //病历模板信息OBJ
            TempHtmlStr: '', //病历模板HTML原始字符串（用于兜底解析默认值）
            formDataSource: [], //病历解析后的表单内容（原始）
            formData: [], //病历解析后的表单内容（下拉菜单数组调整为一维数组）
            dataKeyObj: {}, //存值对象
            birthDate: '', //出生日期
            admID: '', //就诊ID
            isInfoSubmitting: false, //信息采集提交中
            recordDetailList: [], //病历已填值列表
            hisDataMap: {}, //HIS默认值映射（以code为key，值为dataInfo）
            historyRecordIndex: -1, // 历史病历当前选中的索引
            historyRecordList: [], // 历史病历列表数据
            selectedHistoryRecord: {}, // 当前选中的历史病历
            historyRecordLoading: false // 历史病历列表加载状态
        };
    },
    /**
     * 可以使用全局样式
     */
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {},
    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    /**
     * 组件的方法列表
     */
    methods: {
        urlImage(url) {
            if(url && !url.startsWith('http://') && !url.startsWith('https://')) {
              return this.imgHost + url;
            }
            return url;
        },
        // 将 dataKeyObj[key] 统一转成图片URL数组（兼容字符串、数组、逗号分隔字符串）
        getImageList(key) {
            let val = this.dataKeyObj[key];
            if (!val) return [];
            let arr = [];
            if (Array.isArray(val)) {
                arr = val.slice();
            } else if (typeof val === 'string') {
                // 兼容逗号分隔的多图字符串
                arr = val.split(',').map(function(s) { return s.trim(); }).filter(Boolean);
            } else {
                arr = [val];
            }
            // 过滤掉加载失败的图片
            let errorMap = this.imageLoadError[key] || {};
            return arr.filter(function(url, idx) { return !errorMap[idx]; });
        },
        // 删除某张图片
        removeImage(key, idx) {
            let val = this.dataKeyObj[key];
            let arr = [];
            if (Array.isArray(val)) {
                arr = val.slice();
            } else if (typeof val === 'string') {
                arr = val.split(',').map(function(s) { return s.trim(); }).filter(Boolean);
            } else if (val !== null && val !== undefined) {
                arr = [val];
            }
            if (idx < 0 || idx >= arr.length) return;
            arr.splice(idx, 1);
            // 同步清理 imageLoadError 索引
            let errorMap = this.imageLoadError[key] || {};
            let newErrorMap = {};
            Object.keys(errorMap).forEach(function(oldIdx) {
                let i = parseInt(oldIdx, 10);
                if (i < idx) {
                    newErrorMap[i] = errorMap[oldIdx];
                } else if (i > idx) {
                    newErrorMap[i - 1] = errorMap[oldIdx];
                }
            });
            this.$set(this.imageLoadError, key, newErrorMap);
            // 保存回 dataKeyObj：保持原格式（原数组则用数组，原字符串则用逗号拼接）
            let newVal;
            if (Array.isArray(val)) {
                newVal = arr;
            } else {
                newVal = arr.join(',');
            }
            let newDataKeyObj = Object.assign({}, this.dataKeyObj);
            newDataKeyObj[key] = newVal;
            this.dataKeyObj = newDataKeyObj;
        },
        // 预览图片
        previewImage(key, idx) {
            let urls = this.getImageList(key).map((u) => this.urlImage(u));
            if (urls.length === 0) return;
            uni.previewImage({
                current: urls[idx] || urls[0],
                urls: urls
            });
        },
        // 图片加载失败时标记对应索引（兼容单张/多张）
        onImageError(key, idx) {
            idx = idx || 0;
            let errorMap = this.imageLoadError[key] || {};
            errorMap[idx] = true;
            this.$set(this.imageLoadError, key, Object.assign({}, errorMap));
        },
        ready: function () {
            // this.getHistory();
            // 在组件在视图层布局完成后执行
            this.getTempHtml(); // 获取 下拉框数据
            this.getFind(); // 获取 下拉框数据
            let userData = Cache.get('userData');
            let { userName } = userData;
            this.setData({
                userName: userName
            });
            let that = this;
            commonUtil.canChangeFlag('', (res) => {
                that.setData({
                    patientData: Cache.get('patientData')
                });
            });
        },

        attached: function () {},
        handlePageShow() {},

        userNameFun: function (e) {
            this.setData({
                userName: e.detail.value
            });
        },

        onChangeCheckBox(e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            var value = e.detail;
            var desc = e.currentTarget.dataset.name;
            let _this = this;
            let newadmlist = _this.admList;
            newadmlist.map((el) => {
                if (el.IEMRTempElementDesc == desc) {
                    if (el.IEMRTempElementData == value) {
                        el.IEMRTempElementData = '';
                    } else {
                        el.IEMRTempElementData = value;
                    }
                }
            });
            _this.setData({
                admList: newadmlist
            });
            // if(event.detail == this.data.radio) {
            //   this.setData({
            //     result: '',
            //   });
            //   return;
            // }
            // this.setData({
            //   result: event.detail,
            // });
        },

        onClick(event) {
            const { name } = event.currentTarget.dataset;
            if (name == this.result) {
                this.setData({
                    result: ''
                });
                return;
            }
            this.setData({
                result: name
            });
        },

        //门诊
        bindPickerChange2: function (e) {
            // console.log('e', e)
            this.setData(
                {
                    diagTypeIndex: e.detail.value
                },
                () => this.getSearch(this.diagType[e.detail.value].IEMRTemplateID)
            );
        },

        selectData3: function () {
            this.setData({
                selectShow: true
            });
        },

        onClose() {
            this.setData({
                selectShow: false
            });
        },

        onSelect(event) {
            // console.log('event', event);
            this.setData(
                {
                    diagTypeIndex: event.detail.key,
                    selectShow: false
                },
                () => {
                    this.getSearch(event.detail.IEMRTemplateID);
                }
            );
        },

        // 主诉
        tapSelect: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            let that = e.currentTarget.value;
            if (e.currentTarget.dataset.tempcode == 'RadioBox') {
                return;
            }
            // console.log('tapSelect-e', e)
            let _this = this;
            uni.navigateTo({
                //目的页面地址
                url:
                    '/pages/components/mesicalRcordSelect/mesicalRcordSelect?content=' +
                    (e.currentTarget.dataset.value ? e.currentTarget.dataset.value : '') +
                    '&name=' +
                    (e.currentTarget.dataset.name ? e.currentTarget.dataset.name : '') +
                    '&ID=' +
                    e.currentTarget.dataset.id,
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    acceptDataFromOpenedPage: function (data) {
                        // console.log('acceptDataFromOpenedPage', data, _this.data.admList)
                        let newadmlist = _this.admList;
                        newadmlist.map((el) => {
                            if (el.IEMRTempElementDesc == e.currentTarget.dataset.name) {
                                el.IEMRTempElementData = data.data;
                            }
                        });
                        _this.setData({
                            admList: newadmlist
                        });
                    }
                    // someEvent: function(data) {
                    //   console.log('someEvent', data)
                    // }
                },

                success: function (res) {
                    // console.log('tapSelect-s', res)
                    // 通过eventChannel向被打开页面传送数据
                    // res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test-跳转' })
                }
            });
        },
  // 获取页面有哪些组件及配置
  getPageItems (url = 'daeccc6d0cd17de4a07af3d6cf62c701.html') {
    let that = this;
    // #ifdef H5
    let baseUrl = '';
    // #endif
    // #ifndef H5
    let baseUrl = 'https://hlwyy.scsmysgkyy.cn';
    // #endif
    uni.request({
      // todo html模板链接
      url: baseUrl + '/EMRFile/download/emr_html/' + url,
      method: 'GET',
      dataType: 'text',
      timeout: 15000,
      success: function (res) {
        const htmlStr = res.data;
        // 保存原始HTML字符串，用于initFormValues兜底从HTML中解析默认值
        that.TempHtmlStr = htmlStr;
        const regex = /<span[^>]*data-obj="([^"]*)"/ig;
        let match;
        let dataObjs = [];
        while ((match = regex.exec(htmlStr)) !== null) {
          const dataObjStr = match[1];
          const decodedDataObjStr = decodeURIComponent(dataObjStr);
          try {
            const dataObj = JSON.parse(decodedDataObjStr);
            dataObjs.push(dataObj);
          } catch (error) {
            console.error('JSON解析错误:', error);
          }
        }
        let newDataObjs = JSON.parse(JSON.stringify(dataObjs));
        newDataObjs = that.setSelectRange(newDataObjs);
        that.formDataSource = dataObjs;
        that.formData = newDataObjs;
        // 回显默认值：recordDetail优先，其次hisData，最后从html中获取
        that.initFormValues();
      },
      fail: function (error) {
        console.error("请求远程HTML文件失败：", error);
      }
    });
  },
 //调整选择项数组内容
  setSelectRange (datas) {
    let newDatas = datas;
    for(let i=0;i<newDatas.length;i++){
      let newItems = newDatas[i].datas;
      if(newDatas[i].type === "select" || newDatas[i].type === "radio" || newDatas[i].type === "checkbox"){
        let newAry = [];
        for(let j=0;j<newItems.length;j++){
          newAry.push({
            label: newItems[j].label,
            value: newItems[j].value,
          })
        }
        newDatas[i].datas = newAry;
      }
    }
    return newDatas;
  },

  //去除首尾空格
  trimSpace(str) {
    if (str === null || str === undefined) return '';
    return String(str).replace(/^\s+|\s+$/g, '');
  },

  //回显表单默认值：recordDetail优先，其次hisData，最后从html中获取
  initFormValues() {
    let that = this;
    let formDataSource = this.formDataSource;
    let recordDetailList = this.recordDetailList;
    let hisDataMap = this.hisDataMap;
    // 将recordDetail转成以uniqueCode为key的映射
    let recordMap = {};
    recordDetailList.forEach(function (item) {
      let key = item.uniqueCode || item.metaDataCode;
      if (key) {
        recordMap[key] = item;
      }
    });
    // 将hisData中所有dataInfo字段扁平化（以字段名为key）
    let hisFlatMap = {};
    Object.keys(hisDataMap).forEach(function (code) {
      let dataInfo = hisDataMap[code];
      if (dataInfo && typeof dataInfo === 'object') {
        Object.keys(dataInfo).forEach(function (field) {
          // 不覆盖已有值
          if (!(field in hisFlatMap)) {
            hisFlatMap[field] = dataInfo[field];
          }
        });
      }
    });
    // 预解析HTML中每个组件的默认值（兜底数据源）
    let htmlValueMap = this.parseHtmlDefaultValues();
    let newDataKeyObj = {};
    for (let i = 0; i < formDataSource.length; i++) {
      let item = formDataSource[i];
      let key = item.key;
      if (!key) continue;
      let filedText = '';
      let filedCode = '';
      // 1.优先从recordDetail取值
      if (recordMap[key]) {
        filedText = that.trimSpace(recordMap[key].filedText);
        filedCode = that.trimSpace(recordMap[key].filedCode);
      }
      // 2.recordDetail无值时，从hisData取值
      if (!filedText && !filedCode) {
        // 优先按dataObj的baseHisData配置取值
        if (item.baseHisData && item.baseHisData.interfaceId && item.baseHisData.paramName) {
          let interfaceId = item.baseHisData.interfaceId;
          let paramName = item.baseHisData.paramName;
          if (hisDataMap[interfaceId] && hisDataMap[interfaceId][paramName]) {
            let val = that.trimSpace(hisDataMap[interfaceId][paramName]);
            filedText = val;
            filedCode = val;
          }
        }
        // 兜底：用key直接在hisData扁平化字段中查找
        if (!filedText && hisFlatMap[key]) {
          let val = that.trimSpace(hisFlatMap[key]);
          filedText = val;
          filedCode = val;
        }
      }
      // 3.recordDetail和hisData都无值时，从HTML中解析默认值
      if ((!filedText && !filedCode) && htmlValueMap[key]) {
        let htmlVal = htmlValueMap[key];
        filedText = that.trimSpace(htmlVal.text || '');
        filedCode = that.trimSpace(htmlVal.code || '');
      }
      if (!filedText && !filedCode) continue;
      // 根据表单类型设置dataKeyObj
      if (item.type === 'select' || item.type === 'radio' || item.type === 'checkbox') {
        let datas = item.datas || [];
        let selectedItem = null;
        // 优先用filedCode匹配value
        if (filedCode) {
          for (let j = 0; j < datas.length; j++) {
            if (String(datas[j].value) == String(filedCode)) {
              selectedItem = datas[j];
              break;
            }
          }
        }
        // 未匹配到再用filedText匹配label
        if (!selectedItem && filedText) {
          for (let j = 0; j < datas.length; j++) {
            if (datas[j].label === filedText) {
              selectedItem = datas[j];
              break;
            }
          }
        }
        if (selectedItem) {
          // 用匹配到的选项值回显，避免filedCode为空时radio无法回显
          newDataKeyObj[key + 'code'] = String(selectedItem.value);
          newDataKeyObj[key] = selectedItem.label;
        } else if (filedText || filedCode) {
          newDataKeyObj[key + 'code'] = filedCode;
          newDataKeyObj[key] = filedText || filedCode;
        }
      } else if (item.type === 'casepluginimage') {
        // 图片类型：text可能是逗号分隔的多图字符串
        let imgStr = filedText || filedCode || '';
        if (imgStr) {
          newDataKeyObj[key] = imgStr;
          newDataKeyObj[key + 'code'] = '';
        }
      } else {
        // input/date/textarea等直接存值
        newDataKeyObj[key] = filedText || filedCode;
        newDataKeyObj[key + 'code'] = filedCode;
      }
    }
    this.dataKeyObj = Object.assign({}, this.dataKeyObj, newDataKeyObj);
  },

  // 从病历模板HTML中解析每个组件的默认值（兜底数据源）
  // 参考PC端从DOM解析值的方法，以组件key为索引返回 { text, code }
  parseHtmlDefaultValues() {
    let htmlStr = this.TempHtmlStr;
    let result = {};
    if (!htmlStr) return result;
    // 将HTML字符串转成DOM元素以便查询
    let container = document.createElement('div');
    container.innerHTML = htmlStr;
    // 每个组件外层span带有data-obj属性，里面包含key和type
    let spanList = container.querySelectorAll('span[data-obj]');
    for (let i = 0; i < spanList.length; i++) {
      let caseDom = spanList[i];
      let dataObjStr = caseDom.getAttribute('data-obj') || '';
      let config = null;
      try {
        config = JSON.parse(decodeURIComponent(dataObjStr));
      } catch (e) {
        continue;
      }
      if (!config || !config.key) continue;
      let key = config.key;
      let val = this.parseCaseDomValue(caseDom, config);
      if (val && (val.text || val.code)) {
        result[key] = val;
      }
    }
    return result;
  },

  // 解析单个组件DOM的值（参考PC端getCasePluginValue方法）
  parseCaseDomValue(caseDom, config) {
    let type = config.type;
    let res = {};
    let valueDom = null;
    let codes = [];
    let texts = [];
    let tmpDom = document.createElement('div');
    switch (type) {
      case 'input':
      case 'region':
        valueDom = caseDom.querySelector('.caseplugin-value');
        if (valueDom) {
          if (type == 'input' && caseDom.querySelector('.caseplugin-placeholder')) {
            tmpDom.innerHTML = valueDom.innerHTML;
            let ph = tmpDom.querySelector('.caseplugin-placeholder');
            if (ph) ph.remove();
            res.text = tmpDom.innerText;
          } else {
            res.text = valueDom.innerText;
          }
          res.hasBrNum = valueDom.querySelectorAll('br').length || 0;
          res.html = valueDom.innerHTML;
        } else {
          res.text = '';
          res.html = '';
          res.hasBrNum = 0;
        }
        break;
      case 'radio':
      case 'checkbox':
        valueDom = caseDom.querySelectorAll('label.checked');
        for (let i = 0; i < valueDom.length; i++) {
          let dom = valueDom[i];
          codes.push(dom.getAttribute('data-value'));
          texts.push(dom.innerText);
        }
        res.code = codes.join(',');
        res.text = texts.join(',');
        break;
      case 'select':
        valueDom = caseDom.querySelector('.plugin-select') ? caseDom.querySelector('.plugin-select').querySelectorAll('.checked') : [];
        for (let i = 0; i < valueDom.length; i++) {
          let dom = valueDom[i];
          codes.push(dom.getAttribute('data-value'));
          texts.push(dom.innerText);
        }
        if (codes.length > 0) {
          res.code = codes.join(',');
          res.text = texts.join(',');
        } else {
          if (caseDom.querySelector('.caseplugin-placeholder')) {
            res.code = '';
            res.text = '';
            let div = document.createElement('div');
            let valNode = caseDom.querySelector('.caseplugin-value');
            if (valNode) div.appendChild(valNode.cloneNode(true));
            let ph = div.querySelector('.caseplugin-placeholder');
            if (ph) ph.remove();
            res.hasBrNum = (div.querySelector('.caseplugin-value') && div.querySelector('.caseplugin-value').innerText && div.querySelector('.caseplugin-value').innerText.length) || 0;
          } else {
            res.code = '';
            let valNode = caseDom.querySelector('.caseplugin-value');
            res.text = (valNode && valNode.innerText) || '';
            res.hasBrNum = res.text.length;
          }
        }
        let selValNode = caseDom.querySelector('.caseplugin-value');
        res.html = (selValNode && selValNode.innerHTML) || '';
        break;
      case 'datetimeinput':
        valueDom = caseDom.querySelector('.plugin-datetimeinput');
        res.text = (valueDom && valueDom.innerText) || '';
        res.html = (valueDom && valueDom.innerHTML) || '';
        break;
      case 'signimage':
      case 'casepluginimage':
        valueDom = caseDom ? caseDom.querySelectorAll('img') : [];
        Array.from(valueDom).forEach(function (v) {
          if (v.getAttribute('data-src')) {
            texts.push(v.getAttribute('data-src'));
          }
        });
        res.code = '';
        res.text = texts.join(',');
        let imgValNode = caseDom.querySelector('.caseplugin-value');
        res.html = texts.length > 0 ? ((imgValNode && imgValNode.innerHTML) || '') : '';
        break;
    }
    res.text = res.text ? this.trimSpace(res.text) : '';
    return res;
  },
  //根据key获取select类型的当前索引（用于picker绑定）
  getSelectIndex(key) {
    let value = this.dataKeyObj[key];
    let code = this.dataKeyObj[key + 'code'];
    if (!value && !code) return -1;
    let item = this.formDataSource.find(function (i) { return i.key === key; });
    if (!item || !item.datas || !item.datas.length) return -1;
    for (let idx = 0; idx < item.datas.length; idx++) {
      if (item.datas[idx].label === value) return idx;
    }
    for (let idx = 0; idx < item.datas.length; idx++) {
      if (String(item.datas[idx].value) === String(value) || String(item.datas[idx].value) === String(code)) return idx;
    }
    return -1;
  },

  //根据key获取select/radio类型的显示label（兼容dataKeyObj[key]是label或value）
  getSelectLabel(key) {
    let value = this.dataKeyObj[key];
    if (!value) return '';
    let item = this.formDataSource.find(function (i) { return i.key === key; });
    if (!item || !item.datas || !item.datas.length) return value;
    // 优先匹配label
    for (let idx = 0; idx < item.datas.length; idx++) {
      if (item.datas[idx].label === value) return item.datas[idx].label;
    }
    // 再匹配value
    for (let idx = 0; idx < item.datas.length; idx++) {
      if (String(item.datas[idx].value) == String(value)) return item.datas[idx].label;
    }
    return value;
  },
  getTempHtml() {
    let that = this;
    let patientData = Cache.get('patientData');
    let data = {
      params: [{
        admID: patientData.admID,
      }]
    };
    $http.post('urlS', this, {
      code: '06010115',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          that.TempHtmlObj = res.result;
          // 保存已填值和HIS默认值，用于表单回显
          that.recordDetailList = (res.result && res.result.recordDetail) || [];
          let hisData = (res.result && res.result.hisData && res.result.hisData.data) || [];
          let hisMap = {};
          hisData.forEach(function (item) {
            if (item.ID && item.dataInfo) {
              hisMap[item.ID] = item.dataInfo;
            }
          });
          that.hisDataMap = hisMap;
          that.getPageItems(res.result.templateHtmlUrl);
          that.getHistoryRecordList();
        } else {
          uni.showToast({ title: '请求异常：' + res.errorCode + res.errorMessage, icon: 'none' });
        }
      }
    });
  },

  //根据身份证号解析出生日期
  parseBirthDate() {
    let userData = Cache.get('userData');
    let idCard = userData.idCardNo;
    if (!idCard || idCard.length < 14) return;
    let birthDate = idCard.substring(6, 14);
    let year = birthDate.substring(0, 4);
    let month = birthDate.substring(4, 6);
    let day = birthDate.substring(6, 8);
    this.birthDate = year + '-' + month + '-' + day;
  },

  // 判断字段是否只读（state 数组包含 readonly 时，只能查看，不可编辑）
  isReadonlyField(item) {
    return item && item.state && item.state.includes && item.state.includes('readonly');
  },

  //picker选择器选择事件监听
  pickerChange(e) {
    let key = e.currentTarget.dataset.key;
    let ranges = e.currentTarget.dataset.ranges;
    let value = e.detail.value;
    let newDataKeyObj = Object.assign({}, this.dataKeyObj);
    // 优先从 formDataSource 查找对应数据源，避免 data-ranges 被序列化后丢失结构
    let item = this.formDataSource.find(function (i) { return i.key === key; });
    let datas = (item && item.datas) || [];
    let targetObj = null;
    if (datas.length > 0 && typeof datas[0] === 'object') {
      targetObj = datas[value];
    }
    if (targetObj) {
      // select/checkbox：value是索引，从对象数组中取label/value
      newDataKeyObj[key + 'code'] = String(targetObj.value);
      newDataKeyObj[key] = targetObj.label;
    } else if (ranges && Array.isArray(ranges) && ranges.length > 0 && typeof ranges[0] === 'object') {
      newDataKeyObj[key + 'code'] = String(ranges[value].value);
      newDataKeyObj[key] = ranges[value].label;
    } else if (ranges && Array.isArray(ranges)) {
      // 兼容旧格式：数组元素为字符串
      newDataKeyObj[key + 'code'] = ranges[value];
      newDataKeyObj[key] = ranges[value];
    } else {
      // radio/date：value直接是值
      newDataKeyObj[key + 'code'] = String(value);
      newDataKeyObj[key] = value;
    }
    this.dataKeyObj = newDataKeyObj;
  },

  //input/textarea输入事件监听
  inputChange(e) {
    let key = e.currentTarget.dataset.key;
    let value = e.detail.value;
    let newDataKeyObj = Object.assign({}, this.dataKeyObj);
    newDataKeyObj[key] = value;
    newDataKeyObj[key + 'code'] = '';
    this.dataKeyObj = newDataKeyObj;
  },

  //信息采集表单提交
  formSubmit() {
    const formDataSource = this.formDataSource;
    const dataKeyObj = this.dataKeyObj;
    // 必填校验：item.state 数组包含 required 时，对应值不能为空（readonly 字段跳过校验）
    for (let i = 0; i < this.formData.length; i++) {
      let item = this.formData[i];
      if (item.state && item.state.includes && item.state.includes('required') && !this.isReadonlyField(item)) {
        let value = '';
        if (item.type === 'select' || item.type === 'radio' || item.type === 'checkbox') {
          value = dataKeyObj[item.key + 'code'];
        } else {
          value = dataKeyObj[item.key];
        }
        let isEmpty = false;
        if (value === null || value === undefined) {
          isEmpty = true;
        } else if (Array.isArray(value)) {
          isEmpty = value.length === 0;
        } else {
          isEmpty = String(value).trim() === '';
        }
        if (isEmpty) {
          uni.showToast({ title: '请填写' + (item.label || '必填项'), icon: 'none' });
          return;
        }
      }
    }
    let submitObjAry = [];
    for (let i = 0; i < formDataSource.length; i++) {
      let item = formDataSource[i];
      let obj = {};
      obj.metaDataCode = item.key;
      obj.filedType = item.type;
      obj.value = item.id;
      obj.uniqueID = item.id;
      obj.label = item.label;
      if (item.type === 'select' || item.type === 'radio' || item.type === 'checkbox') {
        let selectedText = dataKeyObj[item.key + 'text'] || dataKeyObj[item.key];
        let selectedValue = dataKeyObj[item.key + 'code'];
        let targetObj = [];
        if (selectedText) {
          targetObj = item.datas.filter(function (d) { return d.label === selectedText; });
        }
        if (targetObj.length === 0 && selectedValue) {
          targetObj = item.datas.filter(function (d) { return String(d.value) == String(selectedValue); });
        }
        if (targetObj.length > 0) {
          obj.filedCode = targetObj[0].value + '';
          obj.filedText = targetObj[0].label;
          obj.filedHtml = item.type === 'select' ? targetObj[0].label : '';
        } else {
          obj.filedText = selectedText || selectedValue || '';
          obj.filedHtml = selectedText || selectedValue || '';
        }
      } else {
        let val = dataKeyObj[item.key];
        // 图片类型：数组时按逗号拼接成字符串提交，保持与后端一致
        if (item.type === 'casepluginimage' && Array.isArray(val)) {
          let str = val.filter(function(u) { return !!u; }).join(',');
          obj.filedText = str;
          obj.filedHtml = str;
        } else {
          obj.filedText = val || '';
          obj.filedHtml = val || '';
        }
      }
      submitObjAry.push(obj);
    }
    this.creatEmrRecord(submitObjAry);
  },

  //创建病历
  creatEmrRecord(submitObjAry) {
    let TempObj = this.TempHtmlObj;
    let userData = Cache.get('userData');
    let patientData = Cache.get('patientData');
    let that = this;
    this.isInfoSubmitting = true;
    let data = {
      params: [{
        courseList: [],
        admID: patientData.admID,
        templateID: TempObj.templateID || 1,
        templateVersionID: TempObj.templateVersionID,
        patID: userData.patID,
        patName: userData.patDesc,
        courseRecordID: '',
        data: submitObjAry,
        recordID: TempObj.recordID,
      }]
    };
    $http.post('urlS', this, {
      code: '06010116',
      namespace: 'Y',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          uni.showToast({ title: '保存成功' , icon: 'success' });
          that.isInfoSubmitting = false;
        } else {
          that.isInfoSubmitting = false;
          uni.showToast({ title: '请求异常：' + res.errorCode + res.errorMessage, icon: 'none' });
        }
      },
      fail: function () {
        that.isInfoSubmitting = false;
      }
    });
  },

        // clearn 清空
        // clearn: function () {
        //   // console.log(1111111111)
        //   this.setData({
        //     diagTypeIndex: 0, //门诊
        //   }, () => this.getSearch(this.data.diagType[0].IEMRTemplateID))
        // },
        // 查询病历模板默认信息
        getFind: function () {
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { admID } = patientData;
            $http.post('urlDeault', this, {
                code: '10020004',
                data: {
                    params: [
                        {
                            admID: admID,
                            hospID: userData.hospID
                        }
                    ]
                },
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                baseInfo: res.result.baseInfo,
                                diagnoseObj: res.result.diagnoseObj,
                                orderPresc: res.result.orderPresc,
                                childOrd: res.result.childOrd
                            },
                            () => {
                                let { calldiagnoseObj, callorderPresc } = this;
                                if (calldiagnoseObj) {
                                    this.setData({
                                        diagnoseObj: calldiagnoseObj
                                    });
                                }
                                if (callorderPresc) {
                                    this.setData({
                                        orderPresc: callorderPresc
                                    });
                                }
                            }
                        );
                    }
                }
            });
        },

        //查询遍历接口
        getSearch: function (IEMRTemplateID) {
            let patientData = Cache.get('patientData');
            $http.post('urlDeault', this, {
                code: '10020002',
                data: {
                    params: [
                        {
                            admID: patientData.admID,
                            patID: patientData.patID,
                            IEMRTemplateID //病历模板元素表记录ID
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                admList: res.result,
                                elementDataset: res.result.elementDataset
                            },
                            () => {
                                let { editDataFun: editData, admList } = this;
                                if (editData.length > 0) {
                                    this.editDataFun(admList);
                                }
                                this.getFind();
                            }
                        );
                    }
                }
            });
        },

        //add 保存
        add: function () {
            this.setData({
                isLoading: true
            });
            // var that=this;
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { admID, patID } = patientData;
            let { userID } = userData;
            // console.log(admID, patID, userID, this.data.admList)
            let detailArr = [];
            this.admList.map((el) => {
                detailArr.push({
                    IEMRTempElementID: el.IEMRTempElementID,
                    IEMRTempElementData: el.IEMRTempElementData
                });
            });
            // console.log('detailArr', detailArr)

            let params = {
                params: [
                    {
                        IEMRTemplateID: this.diagType[this.diagTypeIndex].IEMRTemplateID,
                        //患者病历主记录ID
                        admID: admID || '',
                        // 就诊ID session 中获取
                        patID: patID || '',
                        // 病人ID session 中获取
                        updateUserID: userID || '',
                        // 用户ID session 中获取
                        // detailData
                        detailData: detailArr
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '10020003',
                data: params,
                success: function (res) {
                    this.setData({
                        isLoading: false
                    });
                    // console.log('res', res)
                    if (res.errorCode == '0') {
                        uni.showToast({
                            title: res.errorMessage,
                            icon: 'none'
                        });
                        this.getTempHtml();
                        this.getFind();
                    }
                },
                fail: function () {
                    this.setData({
                        isLoading: false
                    });
                }
            });
        },

        // 历史病历选择 - 查询历史病历列表
        getHistoryRecordList() {
            let patientData = Cache.get('patientData');
            let that = this;
            this.setData({ historyRecordLoading: true });
            $http.post('urlS', this, {
                code: '06010117',
                data: {
                    emrCode: '18060019',
                    params: [{
                        patID: patientData.patID,
                        templateId: this.TempHtmlObj.templateID || 1
                    }]
                },
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let list = (res.result && res.result) || [];
                        let mappedList = list.map(function(item) {
                            return {
                                name: item.patientName + ' ' + item.dateTime,
                                ...item
                            };
                        });
                        that.setData({
                            historyRecordList: mappedList,
                            historyRecordLoading: false
                        });
                    } else {
                        that.setData({
                            historyRecordList: [],
                            historyRecordLoading: false
                        });
                        uni.showToast({ title: '请求异常：' + res.errorCode + res.errorMessage, icon: 'none' });
                    }
                },
                fail: function () {
                    that.setData({
                        historyRecordList: [],
                        historyRecordLoading: false
                    });
                }
            });
        },

        // 无可用历史病历时不打开空白 picker，给出明确提示
        showNoHistoryRecord() {
            if (this.historyRecordLoading) return;
            uni.showToast({ title: '暂无可引用病历', icon: 'none' });
        },

        // 历史病历 picker 选择事件
        bindHistoryRecordChange(e) {
            let index = e.detail.value;
            let selected = this.historyRecordList[index];
            this.setData({
                historyRecordIndex: index,
                selectedHistoryRecord: selected
            });
            if (selected && selected.recordId) {
                this.loadHistoryRecordDetail(selected.recordId);
            }
        },

        // 查询历史病历详情并回显表单
        loadHistoryRecordDetail(recordId) {
            let that = this;
            $http.post('urlS', this, {
                code: '06010117',
                data: {
                    emrCode: '18060011',
                    params: [{
                        recordID: recordId
                    }]
                },
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let detailData = (res.result && res.result.data) || [];
                        // 清空 HIS 默认数据映射，避免历史病历数据被覆盖
                        that.setData({
                            hisDataMap: {},
                            recordDetailList: detailData
                        });
                        that.initFormValues();
                    } else {
                        uni.showToast({ title: '请求异常：' + res.errorCode + res.errorMessage, icon: 'none' });
                    }
                }
            });
        },

        // 历史病历
        historyTreatment: function (e) {
            // 历史病历
            uni.navigateTo({
                //目的页面地址
                url: '/pages/myConsultRoom/page/historyTreatment/historyTreatment?Type=2' // 历史病历,
            });
        },

        callDataEdit: function (obj) {
            let { diagType } = this;
            let { select, data, diagnoseObj, orderPresc } = obj;
            let IEMRTemplateID = select.IEMRTemplateID;
            this.setData(
                {
                    diagTypeIndex: this.picakIndex('IEMRTemplateID', IEMRTemplateID, diagType),
                    editData: data,
                    calldiagnoseObj: diagnoseObj,
                    callorderPresc: orderPresc
                },
                () => {
                    this.getSearch(IEMRTemplateID);
                }
            );
        },

        // 回显
        editDataFun: function (data) {
            let { editDataFun: editData } = this;
            for (let i = 0; i < editData.length; i++) {
                for (let j = 0; j < data.length; j++) {
                    if (data[j].IEMRTempElementID === editData[i].IEMRTempElementID) {
                        data[j].IEMRTempElementData = editData[i].IEMRTempElementData || editData[i].IEMRMoudleElementData;
                    }
                }
            }
            this.setData(
                {
                    admList: data
                },
                () => {
                    this.setData({
                        editData: []
                    });
                }
            );
        },

        // 获取索引值picker
        picakIndex: function (name, id, arr) {
            let index = '';
            if (!arr) {
                return false;
            }
            arr.map((item, i) => {
                if (item[name] == id) {
                    index = i;
                }
            });
            return parseFloat(index);
        },

        requiredDataFun: function (str) {
            let { requiredData } = this;
            if (requiredData.includes(str)) {
                return true;
            } else {
                return false;
            }
        }
    },
    created: function () {}
};
</script>
<style>
/* @import '../diagnostic/addDiagnostic/addDiagnostic.css'; */

/* @import "../Entry/diagnostic/addDiagnostic/addDiagnostic.css"; */

.diagnosticcontent {
    background: #fff;
}

.diagnostic-wrapper {
    overflow: hidden;
    height: 100%;
}

.item {
    width: 100%;
    display: flex;
    height: 80rpx;
    justify-content: space-between;
    /* align-items: center; */
    text-align: right;
}

.already {
    color: #f00;
}

.BaseInfo {
    float: left;
    width: 25%;
}

.boxcontentBox {
    padding: 0px 0px 0px 7px;
    margin-left: 30rpx;
    height: 40rpx;
    line-height: 40rpx;
}

.baseinfo1 {
    /* display:inline; */
    float: right;
    text-align: center;
    padding: 0 20rpx;
}

.borderright {
    border-right: 1px solid var(--weui-FG-3);
}

.btn {
    margin-left: 10rpx;
    width: 30% !important;
    display: inline-block;
    font-size: 35rpx;
    color: #fff;
    border: none;
    border-radius: 8rpx;
    font-weight: normal;
    padding: 0 10px !important;
    height: 80rpx !important;
    line-height: 80rpx !important;
    margin-top: 60rpx;
}

.clearnbtn {
    background: #fff;
    color: #000;
    border: 2rpx solid #eee;
    margin-right: 30rpx !important;
}

.addbtn {
    background: #0ac062;
    border: 2rpx solid #0ac062;
}

.pre_item {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.pre_item_inner {
    width: 100%;
    flex: 9;
}

.pre_item_info {
    width: 100%;
    display: flex;
}

.pre_item_info view {
    width: 100%;
}

.pre_right {
    width: 100%;
    flex: 2;
    margin-left: 20rpx;
    border-left: 1px solid #000;
}

.chufang-box {
    margin: 0;
    /* border-top:1px solid #ccc; */
    /* color:var(--weui-FG-1); */
}

/* .chufang1,.chufang2 {border-top:1px solid var(--weui-FG-3)} */

.chufang1 {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: flex-start;
    padding-bottom: 20rpx;
}

.chufang1 .item-aside {
    padding-top: 20rpx;
    flex: 0 0 auto;
    width: 40rpx;
}

.chufang1 .item-main {
    flex: 1 1 auto;
}

/*一个药品*/

.chufang1 .one {
    margin-top: 20rpx;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: flex-start;
}

.chufang1 .one .left {
    flex: 1 1 auto;
    border-right: 1px solid #ccc;
}

.chufang1 .one .right {
    flex: 0 0 140rpx;
    text-align: center;
    align-self: center;
}

.chufang1 .yaopinguige {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: flex-start;
}

.chufang1 .yaopinguige .guige {
    flex: 1 1 60%;
}

.chufang1 .yaopinguige .num {
    flex: 1 1 20%;
    text-align: center;
}

.chufang1 .yaopinguige .ke {
    flex: 1 1 20%;
    text-align: center;
}

.chufang2 {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: flex-start;
    padding-bottom: 10rpx;
}

.chufang2 .item-aside {
    padding-top: 20rpx;
    flex: 0 0 auto;
    width: 40rpx;
}

.chufang2 .item-main {
    flex: 1 1 auto;
    /* border-top: 1px solid var(--weui-FG-3); */
}

.chufang2 .one {
    margin-top: 20rpx;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: flex-start;
}

.chufang2 .one .left {
    flex: 1 1 auto;
    /* border-right:1px solid #ccc; */
}

.chufang2 .one .right {
    flex: 0 0 140rpx;
    text-align: center;
    align-self: center;
}

.chufang2 .yaopinguige {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: flex-start;
}

.chufang2 .yaopinguige .guige {
    flex: 1 1 60%;
}

.chufang2 .yaopinguige .num {
    flex: 1 1 20%;
    text-align: center;
}

.chufang2 .yaopinguige .ke {
    flex: 1 1 20%;
    text-align: center;
}

/* .flex */

.custombutton {
    height: 80rpx;
    font-size: 30rpx;
    color: #fff;
    padding: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 10px 10px;
    display: flex;
}

.custom-btnleft {
    flex: 1;
    margin: 0 10rpx;
    align-items: center;
    justify-content: center;
    display: flex;
}

.custom-btnright {
    flex: 1;
    margin: 0 10rpx;
    align-items: center;
    justify-content: center;
    display: flex;
    background-color: #1890ff;
    color: #fff;
}

.fixedTop {
    overflow: auto;
}

.herbstemp {
    display: flex;
    background-color: #fff;
    /* padding-left: 10rpx; */
    padding-bottom: 12rpx;
}

.herbs-item-comPrincipletemp {
    font-size: 24rpx;
    height: 40rpx;
    width: 72rpx;
    padding-top: 6rpx;
    text-align: center;
    color: #fff;
}

.herbs-item-medItemMed {
    font-size: 28rpx;
    margin-left: 25rpx;
}

.herbs-item-decoctMethodMed {
    margin-left: 25rpx;
}

.use {
    margin-left: 42rpx;
    margin-bottom: 10rpx;
}

/* .usetemp{
  margin-left: 42rpx;
} */

.child2 {
    margin-left: 2rpx;
    margin-top: -20rpx;
}

.leftFont {
    text-align: left !important;
}

/* 信息采集表单 */
.info-collection {
    background: #fff;
    padding: 20rpx 30rpx;
    margin-top: 20rpx;
    min-height: calc(100vh - 330rpx - 100rpx);
    padding-bottom: 140rpx;
}

.info-item {
    display: flex;
    align-items: flex-start;
    padding: 20rpx 0;
}

.info-label {
    flex: 0 0 40%;
    max-width: 40%;
    font-size: 30rpx;
    color: #333;
    line-height: 56rpx;
    box-sizing: border-box;
    padding-right: 20rpx;
    word-break: break-all;
}

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

.info-value {
    font-size: 30rpx;
    color: #333;
    min-height: 56rpx;
    line-height: 56rpx;
    text-align: right;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
}

.info-placeholder {
    color: #999;
}

.info-input {
    font-size: 30rpx;
    width: 100%;
    min-height: 56rpx;
    height: 56rpx;
    text-align: right;
}

.info-textarea {
    font-size: 30rpx;
    width: 100%;
    min-height: 120rpx;
    padding: 10rpx 0;
    text-align: right;
    box-sizing: border-box;
}

.info-radio-group {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    width: 100%;
}

.info-radio-label {
    display: inline-flex;
    align-items: center;
    margin-right: 40rpx;
    font-size: 30rpx;
    line-height: 56rpx;
}

/* 只读字段：文本文字置灰 */
.info-readonly .info-value,
.info-readonly .info-input,
.info-readonly .info-textarea,
.info-readonly .info-radio-label {
    color: #999;
}

/* 图片采集 */
.info-image-box {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 100%;
}

.info-image-item {
    position: relative;
    width: 100%;
    margin-bottom: 20rpx;
    /* 确保删除按钮（位于图片右上角）不被父容器裁剪 */
    overflow: visible;
}

.info-image {
    width: 100%;
    height: 240rpx;
    display: block;
    border-radius: 8rpx;
    background: #f5f5f5;
    /* object-fit 由 <image mode="aspectFill"> 实现，避免部分手机 WebView 不支持 */
}

.info-image-del {
    position: absolute;
    /* 改为正偏移，避免被外层 overflow:hidden 的容器裁剪导致不可见 */
    top: 8rpx;
    right: 8rpx;
    width: 40rpx;
    height: 40rpx;
    line-height: 36rpx;
    text-align: center;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
    border-radius: 50%;
    font-size: 28rpx;
    z-index: 10;
}

.info-image-empty {
    color: #999;
    font-size: 28rpx;
    line-height: 56rpx;
}

/* 保存按钮固定底部 */
.fixed-save-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    background: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
}

.fixed-save-bar .multiBtn-right {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    color: #fff;
    background: #1890ff;
    border-radius: 8rpx;
}

.fixed-save-bar .multiBtn-right[disabled] {
    background: #a0cfff;
    color: #fff;
}

/* diag-form 历史病历选择 */
.diag-form__cell {
    font-size: 28rpx !important;
    color: #1f2937;
}

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

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

.diag-form__picker {
    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;
    white-space: nowrap;
}

.empty-history-record {
    color: #9ca3af;
}
</style>
