<template>
    <view class="diag-form">
        <!-- pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/grass/grass.wxml -->
        <scroll-view class="diag-form__scroll" scroll-y>
            <mp-cells ext-class="my-cells">
                <picker @change="bindPickerChange2" :value="herbalForm1" :range="herbalForm" 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' || (herbalForm && herbalForm[herbalForm1] && herbalForm[herbalForm1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (herbalForm && herbalForm[herbalForm1] && herbalForm[herbalForm1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <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' || (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">
                                <text class="diag-form__stepper-btn" :class="{ 'is-disabled': Number(stepper) <= Number(minQty) }" @tap="onStepperMinus">−</text>
                                <input class="diag-form__stepper-input" type="number" :value="stepper" @input="onStepperInput" @blur="onStepperInput" />
                                <text class="diag-form__stepper-btn" :class="{ 'is-disabled': Number(stepper) >= Number(maxQty) }" @tap="onStepperPlus">+</text>
                            </view>
                        </view>
                    </view>
                </mp-cell>
                <picker @change="bindPickerChange3" :value="frequence1" :range="frequence" 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' || (frequence && frequence[frequence1] && frequence[frequence1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (frequence && frequence[frequence1] && frequence[frequence1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange4" :value="usage1" :range="usage" 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' || (usage && usage[usage1] && usage[usage1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (usage && usage[usage1] && usage[usage1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange5" :value="decoctMethod1" :range="decoctMethod" 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' || (decoctMethod && decoctMethod[decoctMethod1] && decoctMethod[decoctMethod1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (decoctMethod && decoctMethod[decoctMethod1] && decoctMethod[decoctMethod1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange6" :value="cookType1" :range="cookType" range-key="descripts">
                    <mp-cell class="diag-form__cell">
                        <view class="diag-form__line">
                            <view class="diag-form__label">
                                煎药方式
                                <view class="redIcon" v-if="!(verification === 'N' || (cookType && cookType[cookType1] && cookType[cookType1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (cookType && cookType[cookType1] && cookType[cookType1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange7" :value="usageExplain1" :range="usageExplain" 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' || (usageExplain && usageExplain[usageExplain1] && usageExplain[usageExplain1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (usageExplain && usageExplain[usageExplain1] && usageExplain[usageExplain1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange8" :value="recLoc1" :range="recLoc" 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' || (recLoc && recLoc[recLoc1] && recLoc[recLoc1].descripts))">
                                    <van-icon name="warning" color="red" />
                                </view>
                            </view>
                            <view class="diag-form__picker">{{ (recLoc && recLoc[recLoc1] && recLoc[recLoc1].descripts) || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <!-- 结算类型保留默认加载、校验及提交传参，仅隐藏该表单行。 -->
                <picker v-show="false" @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-cells>

            <view class="grass-detail">
                <view class="grass-detail__header">
                    <text class="grass-detail__title required">用药明细</text>
                    <view class="grass-detail__btns">
                        <text class="grass-detail__orderset" @tap="goOrderSet">医嘱套</text>
                        <text class="grass-detail__add" @tap="addChange">+ 添加草药</text>
                    </view>
                </view>
                <view class="grass-detail-list">
                    <view class="grass-detail__item" v-for="(item, index) in gList" :key="index">
                        <view class="grass-detail__row">
                            <van-tag type="primary">{{ item.comPrinciple.descripts }}</van-tag>
                            <text class="grass-detail__med">{{ item.searchSelect.medDesc }}</text>
                        </view>
                        <view class="grass-detail__meta">
                            <text class="grass-detail__meta-item">剂量：{{ item.jl }} {{ item.typeList.unitDesc }}</text>
                            <text class="grass-detail__meta-item">用药类型：{{ item.comPrinciple.descripts }}</text>
                            <text class="grass-detail__meta-item" v-if="item.decoctMethod && item.decoctMethod.descripts">备注：{{ item.decoctMethod.descripts }}</text>
                        </view>
                        <view class="grass-detail__actions">
                            <button class="grass-detail__btn grass-detail__btn--remove" @tap="tapRemove" :data-index="index">删除</button>
                            <button class="grass-detail__btn grass-detail__btn--edit" @tap="addChangeEdit" :data-index="index">编辑</button>
                        </view>
                    </view>
                </view>
              
                <view class="grass-detail__empty" v-if="gList.length <= 0">暂无用药明细</view>
            </view>
        </scroll-view>

        <view class="diag-form__actions diag-form__actions--bottom">
            <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>
        <van-toast id="van-toast" />
        <van-dialog id="van-dialog" />
        <van-overlay :show="show">
            <view class="wrapper">
                <van-loading type="spinner" />
            </view>
        </van-overlay>
    </view>
</template>

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

            // 草药list
            selectIndex1: '',

            selectData1: [],

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

            frequence: [],

            //频次
            herbalForm1: '',

            herbalForm: [],

            //剂型
            usage1: '',

            usage: [],

            //用法
            decoctMethod1: '',

            decoctMethod: [],

            //中药煎法
            cookType1: '',

            cookType: [],

            //煎药方式
            usageExplain1: '',

            usageExplain: [],

            //服用要求
            recLoc1: '',

            recLoc: [],

            //科室
            stepper: '1',

            // 用药值
            sum: '',

            // 每次数量
            show: true,

            // 遮罩层
            show1: true,

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

            // 遮罩层条件二
            verification: 'N',

            // 验证
            maxQty: '99999',

            // 最大值
            minQty: '0',

            // 最小值
            isLoading: false,

            descripts: '',
            gListcallDataClone: ''
        };
    },
    /**
     * 可以使用全局样式
     */
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {
        gListData: {
            type: Array,
            //类型
            default: () => [] //默认值
        },

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

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

        diagData: {
            type: Object,
            //诊断对象（含 id / diagCode / diagDesc）
            default: () => ({}) //默认值
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
        this.addInfo(); //组件值外传
    },
    /**
     * 组件的方法列表
     */
    methods: {
        handlePageShow() {
            // 添加草药数据
            let { gListData, gListcallDataClone: gListcallData } = this;
            console.log('erzi', gListcallData);
            this.setData({
                gList: gListData,
                gListcallDataClone: gListcallData
            });
        },

        // 接收 grassPush 页面保存回传的草药明细列表
        // grassPush 是独立 page，navigateBack 后通过祖父页面 addPrescription 转发调用本方法
        setGListPush: function (newGList) {
            this.setData({
                gList: newGList || []
            });
        },

        ready: function (options) {
            // 添加草药数据
            let { gListData, gListcallDataClone: gListcallData } = this;
            console.log('erzi', gListcallData);
            this.setData({
                gList: gListData,
                gListcallDataClone: gListcallData
            });
            // 在组件在视图层布局完成后执行
            this.selectData1Fun(); // 结算类型加载数据
            this.selectData2(); // 其他下拉加载数据
        },

        attached: function () {
            // 在组件实例进入页面节点树时执行
            // 清除Storage
            Cache.remove('searchSelect');
        },

        callpress: function () {
            let { gListcallDataClone: gListcallData } = this;
            if (JSON.stringify(gListcallData) !== '{}') {
                this.setData(
                    {
                        herbalForm1: this.picakIndex('id', gListcallData.cmOrderSetHerbalFormID, this.herbalForm),
                        // 剂型
                        stepper: gListcallData.cmOrderSetDurQty || '1',
                        //用药付数
                        frequence1: this.picakIndex('id', gListcallData.cmOrderSetFreqID, this.frequence),
                        //频次
                        sum: gListcallData.cmOrderSetDoseQty,
                        //数量
                        usage1: this.picakIndex('id', gListcallData.cmOrderSetUsageID, this.usage),
                        //用药方法
                        usageExplain1: this.picakIndex('id', gListcallData.cmOrderSetUsageExplainID, this.usageExplain),
                        //服用要求
                        recLoc1: this.picakIndex('id', gListcallData.cmOrderSetRecLocID, this.recLoc) //默认接收科室
                    },
                    () => {
                        this.setData({
                            gListcallDataClone: {}
                        });
                    }
                );
            }
        },

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

        // 回显数据
        editDataFun: function (editData) {
            if (JSON.stringify(editData) != '{}') {
                if (!editData.gList) {
                    //  不是草药回显
                    return false;
                }
                console.log(editData);
                this.setData(
                    {
                        herbalForm1: this.picakIndex('id', editData.herbalForm.id, this.herbalForm)
                    },
                    () => {
                        this.bindPickerChange2Http(); // 切换 默认值
                    }
                );

                this.setData({
                    gList: editData.gList || [],
                    // 草药list
                    selectIndex1: this.picakIndex('id', editData.selectData1.id, this.selectData1),
                    frequence1: this.picakIndex('id', editData.frequence.id, this.frequence),
                    usage1: this.picakIndex('id', editData.usage.id, this.usage),
                    decoctMethod1: this.picakIndex('id', editData.decoctMethod.id, this.decoctMethod),
                    cookType1: this.picakIndex('id', editData.cookType.id, this.cookType),
                    usageExplain1: this.picakIndex('id', editData.usageExplain.id, this.usageExplain),
                    recLoc1: this.picakIndex('id', editData.recLoc.id, this.recLoc),
                    stepper: editData.stepper || '1',
                    // 用药值
                    sum: editData.sum || '' // 每次数量
                });
            }
        },

        // 结算类型加载数据
        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 || [],
                                // 结算类型
                                show1: false // 遮罩层条件2
                            },
                            () => {
                                // 修复：原代码 `let { selectData1Fun: selectData1 } = this` 取的是方法函数非数据数组
                                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)
                                        });
                                    }
                                });
                                // 兜底：无 defaultFlag === 'Y' 时默认选第一个
                                if (!hasDefault) {
                                    this.setData({
                                        selectIndex1: 0
                                    });
                                }
                                this.showFun(); // 遮罩层
                            }
                        );
                    }
                }
            });
        },

        // 其他下拉加载数据
        selectData2: function (e) {
            let userData = Cache.get('userData');
            let { hospID } = userData;
            $http.post('urlDeault', this, {
                code: '03100066',
                data: {
                    params: [
                        {
                            hospID: hospID || '',
                            //登录医院id
                            admType: 'O',
                            //就诊类型
                            comPrincipleFlag: '1',
                            //配伍原则
                            herbalFormFlag: '1',
                            //剂型
                            frequenceFlag: '1',
                            //频次
                            usageFlag: '1',
                            //用法
                            durationFlag: '1',
                            //疗程单位
                            usageExplainFlag: '1',
                            //服用要求
                            authRangeFlag: '1',
                            //使用级别
                            decoctMethodFlag: '1',
                            //备注
                            cookTypeFlag: '1' //
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                herbalForm: res.result.herbalForm || [],
                                //剂型
                                usage: res.result.usage || [],
                                //用法
                                decoctMethod: res.result.decoctMethod || [],
                                //中药煎法
                                cookType: res.result.cookType || [],
                                //煎药方式
                                usageExplain: res.result.usageExplain || [],
                                //服用要求
                                recLoc: res.result.recLoc || [],
                                //科室
                                frequence: res.result.frequence || [],
                                //频次
                                // 默认值
                                usageExplain1: this.picakIndex('id', res.result.defaultUsageExplainID, res.result.usageExplain),
                                //默认服用要求
                                decoctMethod1: this.picakIndex('id', res.result.defaultDecoctMethodID, res.result.decoctMethod),
                                //默认中药煎法
                                cookType1: this.picakIndex('id', res.result.defaultCookTypeID, res.result.cookType),
                                //默认煎药方式
                                stepper: res.result.defaultDurQty || '1',
                                //默认疗程数
                                sum: res.result.defaultDoseQty,
                                //默认用量
                                frequence1: this.picakIndex('id', res.result.defaultFreqID, res.result.frequence),
                                //默认频次
                                herbalForm1: this.picakIndex('id', res.result.defaultHerbalFormID, res.result.herbalForm),
                                //默认剂型
                                usage1: this.picakIndex('id', res.result.defaultUsageID, res.result.usage),
                                //默认用药方法

                                show2: false // 遮罩层条件2
                            },
                            () => {
                                let { editDataFun: editData, recLoc, cookType1 } = this;
                                let hasRecLocDefault = false;
                                recLoc.map((item, i) => {
                                    if (item.defaultFlag === 'Y') {
                                        hasRecLocDefault = true;
                                        this.setData({
                                            recLoc1: this.picakIndex('id', item.id, recLoc)
                                        });
                                    }
                                });
                                // 兜底：科室无 defaultFlag === 'Y' 时默认选第一个
                                if (!hasRecLocDefault && recLoc.length) {
                                    this.setData({
                                        recLoc1: 0
                                    });
                                }
                                // 非必填项（煎药方式）：后端无默认值时重置为不选中
                                if (!res.result.defaultCookTypeID || res.result.defaultCookTypeID === '') {
                                    cookType1 = '';
                                }
                                this.setData({ cookType1 });
                                this.editDataFun(editData); // 回显数据
                                this.showFun(); // 遮罩层
                                let { gListcallDataClone: gListcallData } = this;
                                if (JSON.stringify(gListcallData) !== '{}') {
                                    this.callpress();
                                } else {
                                    this.bindPickerChange2Http(); // 切换 默认值
                                }
                            }
                        );
                    }
                }
            });
        },

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

        // 使用剂型切换
        bindPickerChange2: function (e) {
            Dialog.confirm({
                title: '提示',
                message: '剂型切换会导致用药明细清空，是否继续切换',
                context: this
            })
                .then(() => {
                    this.setData(
                        {
                            herbalForm1: e.detail.value,
                            gList: [] // 草药list
                        },
                        () => {
                            this.bindPickerChange2Http();
                        }
                    );
                })
                .catch(() => {
                    // on cancel
                });
        },

        // 使用剂型切换 http 重置 科室下拉款数据
        bindPickerChange2Http: function () {
            let { herbalForm1, herbalForm } = this;
            let herbalFormID = herbalForm[herbalForm1].id;
            $http.post('urlDeault', this, {
                code: '03050083',
                data: {
                    params: [
                        {
                            herbalFormID: herbalFormID,
                            admType: 'O',
                            //就诊类型
                            tisaneFlag: 'N' //代煎标识
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData({
                            recLoc: res.data.CMRecLocList || [],
                            // 接收科室下拉框
                            frequence1: this.picakIndex('id', res.data.defaultFreqID, this.frequence),
                            // 默认频次id
                            usage1: this.picakIndex('id', res.data.defaultUsageID, this.usage),
                            // 默认用法id
                            usageExplain1: this.picakIndex('id', res.data.defaultUsageExplainID, this.usageExplain),
                            //默认服用要求
                            stepper: res.data.defaultDurQty || '1',
                            // 默认付数
                            sum: res.data.defaultDoseQty,
                            //默认用量
                            recLoc1: this.picakIndex('id', res.data.defaultCMRecLocID, res.data.CMRecLocList),
                            //默认接收科室id
                            cookType: res.data.cookTypeList || [],
                            // 默认煎药方式List
                            cookType1: this.picakIndex('id', res.data.defaultCookTypeID, this.cookType) // 默认煎药方式List
                        });
                    }
                }
            });
        },

        // 使用频次
        bindPickerChange3: function (e) {
            this.setData({
                frequence1: e.detail.value
            });
        },

        // 用药方法
        bindPickerChange4: function (e) {
            this.setData({
                usage1: e.detail.value
            });
        },

        // 中药煎法
        bindPickerChange5: function (e) {
            this.setData({
                decoctMethod1: e.detail.value
            });
        },

        // 煎药方式
        bindPickerChange6: function (e) {
            this.setData(
                {
                    cookType1: e.detail.value
                },
                () => {
                    let { cookType, cookType1 } = this;
                    //this.bindPickerChange5Http(cookType[cookType1].id);
                }
            );
        },

        // 煎药方式Http
        bindPickerChange5Http: function (id) {
            let userData = Cache.get('userData');
            let { hospID } = userData;
            $http.post('urlDeault', this, {
                code: '02030115',
                data: {
                    params: [
                        {
                            hospID: hospID,
                            cookTypeID: id
                        }
                    ]
                },
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        let newRecLoc = res.result || [];
                        let locaID = '';
                        newRecLoc.map((item, i) => {
                            if (item.defaultFlag === 'Y') {
                                locaID = item.id;
                            }
                        });
                        // 修复：切换煎药方式后如果接口没有返回默认科室（defaultFlag='Y'），
                        // locaID 为空会导致 recLoc1 为 ''，执行科室看起来”没数据”。
                        // 兜底：无默认科室时默认选中第一个有效科室，并保证 recLoc1 有效索引。
                        let recLoc1 = this.picakIndex('id', locaID, newRecLoc);
                        if ((recLoc1 === '' || recLoc1 === false || recLoc1 === undefined || recLoc1 === null) && newRecLoc.length > 0) {
                            recLoc1 = 0;
                        }
                        this.setData(
                            {
                                recLoc: newRecLoc,
                                recLoc1: recLoc1
                            },
                            () => {
                                let { recLoc1, recLoc } = this;
                                let safeRecLoc = (recLoc && recLoc[recLoc1]) || {};
                                this.setData(
                                    {
                                        maxQty: safeRecLoc.maxQty && safeRecLoc.maxQty != '' ? safeRecLoc.maxQty : '99999',
                                        minQty: safeRecLoc.minQty && safeRecLoc.minQty != '' ? safeRecLoc.minQty : '0'
                                    },
                                    () => {
                                        let maxN = Number(this.maxQty) || 99999;
                                        if (Number(this.stepper) > maxN) {
                                            this.setData({
                                                stepper: String(maxN)
                                            });
                                        }
                                    }
                                );
                            }
                        );
                    }
                }
            });
        },

        // 服用要求
        bindPickerChange7: function (e) {
            this.setData({
                usageExplain1: e.detail.value
            });
        },

        // 执行科室
        bindPickerChange8: function (e) {
            this.setData(
                {
                    recLoc1: e.detail.value
                },
                () => {
                    let { recLoc1, recLoc } = this;
                    this.setData({
                        maxQty: recLoc[recLoc1].maxQty && recLoc[recLoc1].maxQty != '' ? recLoc[recLoc1].maxQty : '99999',
                        minQty: recLoc[recLoc1].minQty && recLoc[recLoc1].minQty != '' ? recLoc[recLoc1].minQty : '0'
                    });
                }
            );
        },

        //用药步进器
        onChangeStepper: function (e) {
            this.setData({
                stepper: e.detail
            });
        },

        // 原生 stepper - 用药付数 减
        onStepperMinus: function () {
            let minN = Number(this.minQty) || 1;
            let current = Number(this.stepper) || 0;
            if (current <= minN) return;
            let next = String(Math.max(minN, current - 1));
            this.setData({ stepper: next });
        },

        // 原生 stepper - 用药付数 加
        onStepperPlus: function () {
            let maxN = Number(this.maxQty) || 99999;
            let current = Number(this.stepper) || 0;
            if (current >= maxN) return;
            let next = String(Math.min(maxN, current + 1));
            this.setData({ stepper: next });
        },

        // 原生 stepper - 用药付数 输入
        onStepperInput: function (e) {
            let raw = e && e.detail ? e.detail.value : '';
            let minN = Number(this.minQty) || 1;
            let maxN = Number(this.maxQty) || 99999;
            if (raw === '' || raw === null || raw === undefined) {
                this.setData({ stepper: String(minN) });
                return;
            }
            raw = String(raw).replace(/[^0-9]/g, '');
            let n = parseInt(raw || '0', 10);
            if (isNaN(n)) n = minN;
            n = Math.max(minN, Math.min(maxN, n));
            this.setData({ stepper: String(n) });
        },

        // 每次数量变化
        binddoseChange: function (e) {
            this.setData({
                sum: e.detail.value
            });
        },

        // 跳转医嘱套页面：选择医嘱套批量导入草药
        goOrderSet: function () {
            let { gList, recLoc, recLoc1, herbalForm, herbalForm1 } = this;
            if (!recLoc[recLoc1]) {
                Toast({
                    type: 'fail',
                    message: '请选择科室',
                    context: this
                });
                return false;
            }
            let url =
                '/pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/grass/grassOrderSet/grassOrderSet?gList=' +
                encodeURIComponent(JSON.stringify(gList)) +
                '&recLocID=' +
                encodeURIComponent(recLoc[recLoc1].id) +
                '&herbalFormID=' +
                encodeURIComponent(herbalForm[herbalForm1].id);
            uni.navigateTo({
                url: url
            });
        },

        // 点击编辑
        addChangeEdit: function (e) {
            console.log(1);
            this.addChange(e);
        },

        // 点击添加
        addChange: function (e) {
            console.log(e);
            let { gList, recLoc, recLoc1, herbalForm, herbalForm1 } = this;
            if (!recLoc[recLoc1]) {
                Toast({
                    type: 'fail',
                    message: '请选择科室',
                    context: this
                });
                return false;
            }
            let url =
                '/pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/grass/grassPush/grassPush?gList=' +
                JSON.stringify(gList) +
                '&recLocID=' +
                recLoc[recLoc1].id +
                '&herbalFormID=' +
                herbalForm[herbalForm1].id;
            if (e) {
                url = url + '&e=' + JSON.stringify(e);
            }
            uni.navigateTo({
                //目的页面地址
                url: url
            });
        },

        // 点击删除
        tapRemove: function (event) {
            let { currentTarget } = event;
            let { gList } = this;
            let dataset = currentTarget.dataset;
            gList.splice(dataset.index, 1);
            this.setData({
                gList: gList || [] // 已添加草药
            });
        },

        // 清空
        clearnbtn: function (event) {
            this.setData({
                selectIndex1: '',
                frequence1: '',
                herbalForm1: '',
                usage1: '',
                decoctMethod1: '',
                cookType1: '',
                usageExplain1: '',
                recLoc1: '',
                stepper: '1',
                // 用药值
                sum: '',
                // 每次数量
                verification: 'N' // 验证
            });
        },

        // 保存
        objadd: function (event) {
            let {
                gList,
                selectIndex1,
                selectData1,
                //结算类型加载数据
                frequence1,
                frequence,
                //频次
                herbalForm1,
                herbalForm,
                //剂型
                usage1,
                usage,
                //用法
                decoctMethod1,
                decoctMethod,
                //中药煎法
                cookType1,
                cookType,
                //煎药方式
                usageExplain1,
                usageExplain,
                //服用要求
                recLoc1,
                recLoc,
                //科室
                stepper,
                // 用药值
                sum // 每次数量
            } = this;
            let obj = {
                gList: gList,
                // 草药组
                selectData1: selectData1[selectIndex1] || {},
                //结算类型加载数据
                frequence: frequence[frequence1] || {},
                //频次
                herbalForm: herbalForm[herbalForm1] || {},
                //剂型
                usage: usage[usage1] || {},
                //用法
                decoctMethod: decoctMethod[decoctMethod1] || {},
                //中药煎法
                cookType: cookType[cookType1] || {},
                //煎药方式
                usageExplain: usageExplain[usageExplain1] || {},
                //服用要求
                recLoc: recLoc[recLoc1] || {},
                //科室
                stepper: stepper || '',
                // 用药值
                sum: sum || '', // 每次数量
                // 诊断信息（编辑回显用）
                diagID: (this.diagData && this.diagData.id) || '',
                diagCode: (this.diagData && this.diagData.diagCode) || ''
            };

            return obj;
        },

        // 保存 todo loading
        addbtn: function (event) {
            let { gList } = this;
            let obj = this.objadd();
            let requireData = [
                {
                    message: '没有需要保存的医嘱',
                    value: gList
                },
                {
                    message: '结算类型不能为空',
                    value: obj.selectData1
                },
                {
                    message: '频次不能为空',
                    value: obj.frequence
                },
                {
                    message: '剂型不能为空',
                    value: obj.herbalForm
                },
                {
                    message: '用法不能为空',
                    value: obj.usage
                },
                {
                    message: '中药煎法不能为空',
                    value: obj.decoctMethod
                },
                {
                    message: '服用要求不能为空',
                    value: obj.usageExplain
                },
                {
                    message: '科室不能为空',
                    value: obj.recLoc
                }
            ];
            util.formRequire(requireData, (data) => {
                if (data && data.length > 0) {
                    this.setData({
                        verification: 'Y'
                    });
                    Toast({
                        type: 'fail',
                        message: data[0].message,
                        context: this
                    });
                } else {
                    // 直接保存草药医嘱（03050054）
                    this.setData({ 
                        isLoading: true,
                    }, () => {
                        this.saveHerbalDirect(obj);
                    });
                }
            });
        },

        // 直接保存草药医嘱（03050054）
        saveHerbalDirect: function (obj) {
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { admID } = patientData;
            let { userID, locID, hospID } = userData;
            let orders = [];
            obj.gList.map((item2, i) => {
                orders.push({
                    dose: item2.jl || '',
                    medDesc: (item2.searchSelect && item2.searchSelect.medDesc) || '',
                    medID: (item2.searchSelect && item2.searchSelect.medID) || '',
                    checkBox: item2.checkBox || false,
                    cmOrderSetDetailSeqNo: item2.cmOrderSetDetailSeqNo || 0,
                    key: item2.key !== undefined ? item2.key : i,
                    doseUnitID: (item2.typeList && item2.typeList.unitID) || '',
                    ordDoseUnitDesc: (item2.typeList && item2.typeList.unitDesc) || '',
                    qtyUnitList: item2.qtyUnitList || (item2.typeList ? [item2.typeList] : []),
                    treatyFlag: item2.treatyFlag || '',
                    isboxShadow: item2.isboxShadow || false,
                    diagID: (this.diagData && this.diagData.id) || '',
                    diagCode: (this.diagData && this.diagData.diagCode) || ''
                });
            });
            $http.post('urlDeault', this, {
                code: '03050054',
                data: {
                    params: [
                        {
                            admID: admID || '',
                            hospID: hospID || '',
                            userID: userID || '',
                            locID: locID || '',
                            docID: userID || '',
                            admReasonID: obj.selectData1.id || '', // 结算类型
                            durQty: obj.stepper || '', // 付数
                            freqID: obj.frequence.id || '', // 频次
                            doseQty: obj.sum || '1', // 每次数量
                            usageID: obj.usage.id || '', // 用药方法
                            decoctMethodID: obj.decoctMethod.id || '', // 中药煎法
                            usageExplainID: obj.usageExplain.id || '', //  服用要求
                            recLocID: obj.recLoc.id || '', // 执行科室
                            herbalFormID: obj.herbalForm.id || '', // 使用剂型
                            cookTypeID: obj.cookType.id || '', //煎药方式
                            orders: orders
                        }
                    ]
                },
                success: function (res) {
                    if (res.errorCode == '0') {
                        Cache.set('herbalSaved', true);
                        Toast({
                            type: 'success',
                            message: '保存成功',
                            context: this
                        });
                        setTimeout(() => {
                            this.setData({ isLoading: false });
                            uni.navigateBack({ delta: 1 });
                        }, 800);
                    } else {
                        setTimeout(() => {
                            this.setData({ isLoading: false });
                        }, 300);
                       
                    }
                },
                fail: function () {
                    setTimeout(() => {
                        this.setData({ isLoading: false });
                    }, 300);
                }
            });
        },

        // 获取索引值picker
        picakIndex: function (name, id, arr) {
            // 兜底：arr 为空/未找到匹配项/ id 为空时默认返回 0（第一项），
            // 避免频次/剂型/用法等下拉无默认值时显示空白
            if (!arr || !arr.length) {
                return 0;
            }
            // id 为空时也走默认 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;
        },

        // 去掉遮罩层
        showFun: function () {
            let { show1, show2 } = this;
            if (!show1 && !show2) {
                this.setData({
                    show: false
                });
            }
        }
    },
    created: function () {},
    watch: {
        gListcallData: {
            handler: function (newVal, oldVal) {
                this.gListcallDataClone = newVal;
            },

            immediate: true,
            deep: true
        }
    }
};
</script>
<style>
/* @import '../../../../diagnostic/addDiagnostic/customDiagnostics/customDiagnostics.css'; */
/* @import '../../../../diagnostic/diagnostic.css'; */
/* @import '../../../../Entry.css'; */

.diag-form {
    flex: 1;
    height: calc(100vh - 245rpx);
    display: flex;
    flex-direction: column;
    background: #f4f7fb;
    overflow: hidden;
}

.diag-form__scroll {
    flex: 1;
    min-height: 0;
    box-sizing: border-box;
}

.my-cells {
    display: block;
    margin: 0 0 12rpx;
    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;
}

.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__cell {
    font-size: 28rpx !important;
    color: #1f2937;
}

.diag-form__line {
    width: 100%;
    min-height: 66rpx;
    box-sizing: border-box;
    /* Keep right-aligned controls clear of the cell edge. */
    padding-right: 16rpx;
    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;
    box-sizing: border-box;
    padding-right: 20rpx;
    display: flex;
    align-items: center;
}

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

.diag-form__picker {
    flex: 0 0 60%;
    max-width: 60%;
    color: #3f4a5a;
    min-height: 42rpx;
    line-height: 42rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: right;
}

.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__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__stepper {
    display: inline-flex;
    align-items: center;
    border: 1rpx solid #e5e7eb;
    border-radius: 4rpx;
    overflow: hidden;
    background: #fff;
    height: 52rpx;
}

.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: 52rpx;
    line-height: 52rpx;
    text-align: center;
    font-size: 28rpx;
    border: none;
    outline: none;
    background: #fff;
    color: #1f2937;
    flex-shrink: 0;
    box-sizing: border-box;
    padding: 0;
}

.diag-form__actions {
    width: 100%;
    min-height: 76rpx;
    display: flex;
    align-items: center;
    gap: 14rpx;
    box-sizing: border-box;
    padding: 16rpx 24rpx;
    padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
    background: #fff;
    border-top: 1rpx solid #f0f2f5;
    flex-shrink: 0;
}

.diag-form__actions--bottom {
    margin: 0;
    border-radius: 0;
    box-shadow: none;
}

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

.diag-form__action--plain {
    border: 1px solid #d8dee8;
    background: #fff;
    color: #1f2937;
}

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

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

.grass-detail {
    margin: 0 0 12rpx;
    background: #fff;
    border-radius: 14rpx;
    padding: 18rpx 24rpx;
    box-sizing: border-box;
    box-shadow: 0 6rpx 18rpx rgba(15, 23, 42, 0.04);
}
.grass-detail-list{
    max-height: 550rpx;
    overflow: auto;
}
.grass-detail__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 14rpx;
    border-bottom: 1rpx solid #edf1f6;
}

.grass-detail__title {
    color: #1f2937;
    font-weight: 600;
    font-size: 28rpx;
}

.grass-detail__title.required:before {
    content: "*";
    color: #f5222d;
    margin-right: 4rpx;
}

.grass-detail__add {
    color: #fff;
    background: #1890ff;
    border-radius: 999rpx;
    padding: 6rpx 22rpx;
    font-size: 25rpx;
    line-height: 36rpx;
}

.grass-detail__btns {
    display: flex;
    align-items: center;
    gap: 14rpx;
}

.grass-detail__orderset {
    color: #1687ff;
    background: #fff;
    border: 1rpx solid #1687ff;
    border-radius: 999rpx;
    padding: 5rpx 22rpx;
    font-size: 25rpx;
    line-height: 36rpx;
}

.grass-detail__item {
    padding: 14rpx 0;
    border-bottom: 1rpx solid #edf1f6;
}

.grass-detail__item:last-child {
    border-bottom: 0;
}

.grass-detail__row {
    display: flex;
    align-items: center;
    gap: 12rpx;
}

.grass-detail__med {
    color: #1f2937;
    font-weight: 500;
    font-size: 28rpx;
}

.grass-detail__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 6rpx 18rpx;
    margin-top: 10rpx;
    color: #7b8794;
    font-size: 25rpx;
    line-height: 38rpx;
}

.grass-detail__actions {
    display: flex;
    justify-content: flex-end;
    gap: 14rpx;
    margin-top: 12rpx;
}

.grass-detail__btn {
    height: 56rpx;
    line-height: 56rpx;
    border-radius: 999rpx;
    font-size: 25rpx;
    padding: 0 24rpx;
    margin: 0;
}

.grass-detail__btn:after {
    border: 0;
}

.grass-detail__btn--remove {
    color: #f5222d;
    background: #fff;
    border: 1rpx solid #f5222d;
}

.grass-detail__btn--edit {
    color: #1687ff;
    background: #fff;
    border: 1rpx solid #1687ff;
}

.grass-detail__empty {
    text-align: center;
    color: #8b98a8;
    padding: 40rpx 0;
    font-size: 26rpx;
}

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

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