<template>
    <view class="mos-root">
        <!-- pages/entryWrite/page/Entry/prescription/addPrescription/medicalOrderSet/medicalOrderSet.wxml -->
        <!-- 医嘱套 -->
        <view class="diagnostic-wrapper">
            <view class="all">
                <view class="MedDody">
                    <view class="MedDody__inner">
                        <view class="col-4">
                            <van-collapse :value="activeNames" @change="onChangeActive">
                                <van-collapse-item :title="item.title" :name="index" v-for="(item, index) in medicalRecode" :key="index">
                                    <!-- 西药 -->

                                    <view v-if="active == 0">
                                        <view
                                            @tap.stop.prevent="Edit"
                                            :data-index="cell.ordSetID"
                                            :class="medRecodeIndex == cell.ordSetID ? 'checkMedArr' : 'medArr'"
                                            v-for="(cell, index1) in item.children"
                                            :key="index1"
                                        >
                                            <view>{{ cell.ordSetDesc }}</view>
                                        </view>
                                    </view>

                                    <!-- 草药 -->

                                    <view v-if="active == 1">
                                        <view
                                            @tap.stop.prevent="Edit"
                                            :data-calldata="item.data[index]"
                                            :data-usagedesc="cell.usageDesc"
                                            :data-index="cell.cmOrderSetID"
                                            :class="medRecodeIndex == cell.cmOrderSetID ? 'checkMedArr' : 'medArr'"
                                            v-for="(cell, index1) in item.data"
                                            :key="index1"
                                        >
                                            <view>{{ cell.cmOrderSetDesc }}</view>
                                        </view>
                                    </view>
                                </van-collapse-item>
                            </van-collapse>
                        </view>
                        <view class="col-8">
                            <view class="selectall" v-if="hasMedRecodeDateil">
                                <checkbox :checked="checkedAll" @tap="checkall">全选/取消全选</checkbox>
                            </view>
                            <view class="col-8__body">
                                <view v-if="!hasMedRecodeDateil" class="col-8__empty">
                                    <view class="col-8__empty-icon">∅</view>
                                    <view>暂无医嘱套明细</view>
                                    <view style="margin-top: 8rpx; font-size: 22rpx; color: #cbd5e1;">请选择左侧医嘱套</view>
                                </view>
                                <view v-if="active == 0 && hasMedRecodeDateil">
                                    <view class="detail">
                                        <van-checkbox-group :value="selectedArr" @change="onChange">
                                            <van-cell-group>
                                                <van-cell
                                                    use-label-slot
                                                    value-class="value-class"
                                                    clickable
                                                    :data-index="index"
                                                    @click="toggle($event, { index })"
                                                    v-for="(item, index) in medRecodeDateil.data"
                                                    :key="index"
                                                >
                                                    <view slot="title">
                                                        <view class="van-cell-text">
                                                            {{ item.ordDesc }}
                                                        </view>
                                                    </view>

                                                    <view slot="label">
                                                        <view class="boxTime">
                                                            规格：
                                                            <text class="mr20">{{ item.spec }}</text>
                                                        </view>
                                                        <view class="boxTime">
                                                            <text class="floatR boxTime">{{ item.ordDurQty }} {{ item.ordDurationDesc }}</text>
                                                            <text class="floatR boxTime mr20">{{ item.ordDose }}{{ item.ordDoseUnitDesc }}</text>
                                                            <text class="floatR mr20">X{{ item.ordQty }} {{ item.ordQtyUomDesc }}</text>
                                                        </view>
                                                    </view>

                                                    <van-checkbox @tap.native.stop.prevent="noop" :class="'checkboxes-' + index" :name="item.ordSetDetailID" />
                                                </van-cell>
                                            </van-cell-group>
                                        </van-checkbox-group>
                                    </view>
                                </view>
                                <view v-if="active == 1 && hasMedRecodeDateil">
                                    <view class="detail">
                                        <view class="detailBox">
                                            <text class="fontS30 ml20">用药方法</text>
                                        </view>
                                        <view class="fontS25 ml20 nodata" style="line-height: 60rpx">
                                            {{ usagedesc }}
                                        </view>
                                    </view>
                                    <view class="detail">
                                        <view class="detailBox">
                                            <text class="fontS30 ml20">用药明细</text>
                                        </view>
                                        <view>
                                            <van-checkbox-group :value="selectedArr" @change="onChange">
                                                <van-cell-group>
                                                    <van-cell
                                                        value-class="value-class"
                                                        clickable
                                                        :data-index="index"
                                                        @click="toggle($event, { index })"
                                                        v-for="(item, index) in medRecodeDateil"
                                                        :key="index"
                                                    >
                                                        <view slot="title">
                                                            <view class="van-cell-text">
                                                                <van-tag
                                                                    :color="
                                                                        item.cmOrderSetDetailComPrincipleCode === '01'
                                                                            ? '#FFA33C'
                                                                            : item.cmOrderSetDetailComPrincipleCode === '02'
                                                                            ? '#36D2D2'
                                                                            : item.cmOrderSetDetailComPrincipleCode === '03'
                                                                            ? '#FA5AB4'
                                                                            : '#AB72F9'
                                                                    "
                                                                >
                                                                    {{
                                                                        item.cmOrderSetDetailComPrincipleCode === '01'
                                                                            ? '君药'
                                                                            : item.cmOrderSetDetailComPrincipleCode === '02'
                                                                            ? '臣药'
                                                                            : item.cmOrderSetDetailComPrincipleCode === '03'
                                                                            ? '佐药'
                                                                            : '使药'
                                                                    }}
                                                                </van-tag>
                                                                <text>{{ item.cmOrderSetDetailMedItemDesc }}</text>
                                                                <text class="nodata">【{{ item.cmOrderSetDetailDoseQty }}{{ item.ordDoseUnitDesc }}】</text>
                                                                <text
                                                                    class="nodata"
                                                                    v-if="!(item.cmOrderSetDetailDecoctMethodDesc == '' || !item.cmOrderSetDetailDecoctMethodDesc)"
                                                                >
                                                                    【{{ item.cmOrderSetDetailDecoctMethodDesc }}】
                                                                </text>
                                                            </view>
                                                        </view>

                                                        <van-checkbox @tap.native.stop.prevent="noop" :class="'checkboxes-' + index" :name="item.cmOrderSetDetailID" />
                                                    </van-cell>
                                                </van-cell-group>
                                            </van-checkbox-group>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- <view class="foot"> -->
        <button class="diagnostibutton" @tap.stop.prevent="savePres" :disabled="isLoading">{{ isLoading ? '保存中' : '保存到医嘱列表' }}</button>
        <!-- </view> -->
    </view>
</template>

<script>
import Cache from '../../../../../../../utils/cache';
// pages/entryWrite/page/Entry/prescription/addPrescription/medicalOrderSet/medicalOrderSet.js
import { $http } from '../../../../../../../config/https';
import Toast from '../../../../../../../utils/toast';
export default {
    data() {
        return {
            activeNames: [0],

            // 左侧展开
            active: 0,

            // 切换
            medicalRecode: [],

            // 左侧list医嘱套列表
            medRecodeDateil: [],

            // 右侧侧list医嘱套列表 明细
            medRecodeIndex: 0,

            //初始选中
            selectedArr: [],

            // 右侧选中
            usagedesc: '',

            // 用法
            callData: {},

            // 回显数据
            isLoading: false,

            checkedAll: false,

            cell: {
                ordSetID: '',
                ordSetDesc: '',
                usageDesc: '',
                cmOrderSetID: '',
                cmOrderSetDesc: ''
            }
        };
    },
    /**
     * 组件的属性列表
     */
    options: {
        addGlobalClass: true
    },
    computed: {
        // 是否有右侧明细数据：西药是 {data:[...]} 形态，草药是 [...] 形态
        hasMedRecodeDateil: function () {
            const d = this.medRecodeDateil;
            if (!d) return false;
            if (Array.isArray(d)) return d.length > 0;
            if (d.data && Array.isArray(d.data)) return d.data.length > 0;
            return false;
        }
    },
    /**
     * 组件的属性列表
     */
    props: {
        active: {
            type: Number,
            //类型
            default: 0 //默认值
        },

        addInfo: {
            type: Object,
            //类型
            default: () => ({}) //默认值
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    destroyed: function () {},
    /**
     * 组件的方法列表
     */
    methods: {
        ready: function (options) {
            this.childFun(); // 接口查询
            console.log(this.addInfo);
        },

        attached: function () {},

        // 清空
        clearn: function () {
            this.setData({
                activeNames: [],
                // 左侧展开
                medicalRecode: [],
                // 左侧list医嘱套列表
                medRecodeDateil: [],
                // 右侧侧list医嘱套列表 明细
                medRecodeIndex: 0,
                //初始选中
                selectedArr: [] // 右侧选中
            });
        },

        // 父组件调取
        childFun: function () {
            this.clearn(); // 清空
            let { active } = this;
            if (active == 0) {
                // 左侧list医嘱套列表 西药
                this.medWList();
            } else {
                // 左侧list医嘱套列表 草药
                this.medGList();
            }
        },

        // 左侧list医嘱套列表 西药
        medWList: function (e) {
            let userData = Cache.get('userData');
            let { userID, locID, hospID, groupID } = userData;
            $http.post('urlDeault', this, {
                code: '03050060',
                data: {
                    params: [
                        {
                            userID: userID || '',
                            //用户id
                            locID: locID || '',
                            //登录科室id
                            hospID: hospID || '',
                            //登录医院id
                            groupID: groupID || '',
                            //登录角色id
                            activeFlag: '',
                            //生效标识
                            selfFlag: '',
                            //本人添加标识
                            searchCode: '' // 搜索内容
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                medicalRecode: res.data.list || [] // 左侧list医嘱套列表 西药
                            },
                            () => {
                                console.log(this.medicalRecode[0]);
                                let e = {
                                    currentTarget: {
                                        dataset: {
                                            index: this.medicalRecode[0] && this.medicalRecode[0].children[0] && this.medicalRecode[0].children[0].ordSetID,
                                            usagedesc: this.medicalRecode[0] && this.medicalRecode[0].children[0] && this.medicalRecode[0].children[0].usageDesc
                                        }
                                    }
                                };
                                this.Edit(e);
                                this.setData({
                                    activeNames: [0],
                                    medRecodeIndex: this.medicalRecode[0] && this.medicalRecode[0].children[0] && this.medicalRecode[0].children[0].ordSetID
                                });
                            }
                        );
                    }
                }
            });
        },

        // 左侧list医嘱套列表 草药
        medGList: function (e) {
            $http.post('urlDeault', this, {
                code: '03050024',
                data: {
                    params: [
                        {
                            userSelf: 'Y',
                            // 个人标志
                            status: 'Y',
                            //生效标志
                            input: '' //搜索框内容
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                medicalRecode: res.result || [] // 左侧list医嘱套列表 草药
                            },
                            () => {
                                console.log(this.medicalRecode[0]);
                                let e = {
                                    currentTarget: {
                                        dataset: {
                                            index: this.medicalRecode[0] && this.medicalRecode[0].data[0] && this.medicalRecode[0].data[0].cmOrderSetID,
                                            usagedesc: this.medicalRecode[0] && this.medicalRecode[0].data[0] && this.medicalRecode[0].data[0].usageDesc,
                                            calldata: this.medicalRecode[0] && this.medicalRecode[0].data[0]
                                        }
                                    }
                                };
                                this.Edit(e);
                                this.setData({
                                    activeNames: [0],
                                    medRecodeIndex: this.medicalRecode[0] && this.medicalRecode[0].data[0] && this.medicalRecode[0].data[0].cmOrderSetID
                                });
                            }
                        );
                    }
                }
            });
        },

        // 右侧list医嘱套列表明细 西药
        medWListEdit: function (ordSetID) {
            let userData = Cache.get('userData');
            let { userID, locID, hospID, groupID } = userData;
            $http.post('urlDeault', this, {
                code: '03050063',
                data: {
                    params: [
                        {
                            userID: userID || '',
                            // 用户id
                            locID: locID || '',
                            //登录科室id
                            hospID: hospID || '',
                            //登录医院id
                            ordSetID: ordSetID || '',
                            // 医嘱套id
                            groupID: groupID || '' // 登录角色id
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData({
                            medRecodeDateil: res.data || [] // 右侧侧list医嘱套列表 西药
                        });
                    }
                }
            });
        },

        // 右侧list医嘱套列表明细 草药
        medGListEdit: function (cmOrderSetID, usagedesc, callData) {
            var { addInfo } = this;
            console.log(usagedesc);
            $http.post('urlDeault', this, {
                code: '03050027',
                data: {
                    params: [
                        {
                            cmOrderSetID: cmOrderSetID || '',
                            //草药医嘱套ID
                            recLocID: addInfo.recLoc ? addInfo.recLoc.id : '' //科室
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData({
                            medRecodeDateil: res.result || [],
                            // 右侧侧list医嘱套列表 草药
                            usagedesc,
                            callData
                        });
                    }
                }
            });
        },

        // 右侧list医嘱套列表明细 总点击
        Edit: function (e) {
            console.log(e.currentTarget.dataset);
            let { active } = this;
            let { index, usagedesc, calldata } = e.currentTarget.dataset;
            this.setData({
                medRecodeIndex: index
            });
            if (active == 0) {
                // 左侧list医嘱套列表 西药
                this.medWListEdit(index);
            } else {
                // 左侧list医嘱套列表 草药
                console.log(calldata);
                this.medGListEdit(index, usagedesc, calldata);
            }
        },

        // 左侧展开list
        onChangeActive: function (event) {
            this.setData(
                {
                    activeNames: event.detail
                },
                () => {
                    console.log(this.activeNames);
                }
            );
        },

        // 右侧变化
        onChange(event) {
            // console.log(event)
            this.setData({
                selectedArr: event.detail
            });
        },

        toggle(event, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(event, _dataset);
            /* ---处理dataset end--- */
            // console.log(event)
            const { index } = event.currentTarget.dataset;
            const checkbox = this.zpSelectComponent(`.checkboxes-${index}`);
            checkbox.toggle();
        },

        noop() {},

        // 保存
        savePres: function (e) {
            this.setData({
                isLoading: true
            });
            const { medRecodeDateil, active, addInfo } = this;
            var patientData = Cache.get('patientData');
            let orderData = [];
            let orderObj = {};
            if (active === 0) {
                var arr = []; // 参数数组
                console.log(addInfo);
                medRecodeDateil.data.map((item) => {
                    if (this.selectedArr.includes(item.ordSetDetailID)) {
                        item.otherFlag = 1;
                        item.ordAdmReasonID = addInfo.selectIndex1.id;
                        orderData.push(item);
                        arr.push({
                            medID: item.medID
                        });
                    }
                });
                let data = {
                    params: [
                        {
                            orders: arr,
                            admID: patientData.admID
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '03050020',
                    data: data,
                                success: function (res) {
                                    this.setData({
                                        isLoading: false
                                    });
                                    if (res.errorCode == '0') {
                                        let errorData = res.errorData;
                                        let successData = res.data;
                                        if (errorData.length != 0) {
                                            let contentStr = '';
                                            for (var len = 0; len < errorData.length; len++) {
                                                contentStr = contentStr + errorData[len].ordDesc + ':' + errorData[len].errorMessage + '\n';
                                            }
                                            uni.showModal({
                                                title: '提示',
                                                content: contentStr,
                                                confirmText: '确认',
                                                success(res) {
                                                    if (res.confirm) {
                                                        let errorArr = [];
                                                        errorData.map((item, i) => {
                                                            errorArr.push(item.medID);
                                                        });
                                                        orderData.map((item, i) => {
                                                            if (errorArr.includes(item.medID)) {
                                                                item.invalid = item.ordDesc;
                                                            }
                                                            successData.map((cell, i) => {
                                                                if (cell.defaultData.medID === item.medID) {
                                                                    item.ordQty = cell.defaultData.ordQty;
                                                                    item.spec = cell.defaultData.spec;
                                                                }
                                                            });
                                                        });
                                                        // 关键修复：addPrescription.vue 没有 callData 方法，
                                                        // 正确方法是 callDataFun（西药），与 getAddInfo 保持一致
                                                        try {
                                                            let pages = getCurrentPages();
                                                            let prevPage = pages[pages.length - 2];
                                                            if (prevPage && typeof prevPage.callDataFun === 'function') {
                                                                prevPage.callDataFun(orderData);
                                                            } else if (prevPage && typeof prevPage.wListPush === 'function') {
                                                                orderData.forEach((it) => prevPage.wListPush(it, 'N'));
                                                            }
                                                        } catch (err) {
                                                            console.warn('[medicalOrderSet.savePres] 通知父页面失败:', err);
                                                        }
                                                        uni.navigateBack({
                                                            delta: 1
                                                        });
                                                    }
                                                }
                                            });
                                        } else {
                                            let errorArr = [];
                                            errorData.map((item, i) => {
                                                errorArr.push(item.medID);
                                            });
                                            orderData.map((item, i) => {
                                                if (errorArr.includes(item.medID)) {
                                                    item.invalid = item.ordDesc;
                                                }
                                                successData.map((cell, i) => {
                                                    if (cell.defaultData.medID === item.medID) {
                                                        item.ordQty = cell.defaultData.ordQty;
                                                        item.spec = cell.defaultData.spec;
                                                    }
                                                });
                                            });
                                            console.log(orderData);
                                            // 关键修复：addPrescription.vue 没有 callData 方法，
                                            // 正确方法是 callDataFun（西药），与 getAddInfo 保持一致
                                            try {
                                                let pages = getCurrentPages();
                                                let prevPage = pages[pages.length - 2];
                                                if (prevPage && typeof prevPage.callDataFun === 'function') {
                                                    prevPage.callDataFun(orderData);
                                                } else if (prevPage && typeof prevPage.wListPush === 'function') {
                                                    orderData.forEach((it) => prevPage.wListPush(it, 'N'));
                                                }
                                            } catch (err) {
                                                console.warn('[medicalOrderSet.savePres] 通知父页面失败:', err);
                                            }
                                            uni.navigateBack({
                                                delta: 1
                                            });
                                        }
                                    }
                                },
                    fail: function (error) {
                        this.setData({
                            isLoading: false
                        });
                    }
                });
            } else {
                this.setData({
                    isLoading: false
                });
                medRecodeDateil.map((item) => {
                    if (this.selectedArr.includes(item.cmOrderSetDetailID)) {
                        item.otherFlag = 1;
                        item.ordDesc = item.cmOrderSetDetailMedItemDesc;
                        item.medID = item.cmOrderSetDetailMedItemID;
                        item.ordDoseUnitDesc = item.ordDoseUnitDesc;
                        item.ordDoseUnitID = item.ordDoseUnitID;
                        item.ordDose = item.cmOrderSetDetailDoseQty;
                        item.comPrincipleID = item.cmOrderSetDetailComPrincipleID;
                        item.comPrincipleDesc = item.cmOrderSetDetailComPrincipleDesc;
                        item.decoctMethodID = item.cmOrderSetDetailDecoctMethodID;
                        item.decoctMethodDesc = item.cmOrderSetDetailDecoctMethodDesc;
                        orderData.push(item);
                    }
                });

                //this.selectMedicalDateil(item.medID, index)

                let pages = getCurrentPages();
                //上一个页面实例对象
                let prevPage = pages[pages.length - 2];
                let datapress = {};
                let { callData } = this;
                //关键在这里
                orderObj.select = 0;
                orderObj.data = orderData;
                datapress.data = callData;
                this.$emit('changeSelect', {
                    detail: orderObj
                });
                this.$emit('callDataPress', {
                    detail: datapress
                });
            }
        },

        //全选
        checkall: function (event) {
            let data = this.medRecodeDateil.data;
            let { checkedAll } = this;
            let checkData = [];
            if (!checkedAll) {
                if (this.active == 0) {
                    for (var len = 0; len < data.length; len++) {
                        checkData.push(data[len].ordSetDetailID);
                    }
                } else {
                    data = this.medRecodeDateil;
                    for (var len = 0; len < data.length; len++) {
                        checkData.push(data[len].cmOrderSetDetailID);
                    }
                }
            }
            this.setData({
                selectedArr: checkData,
                checkedAll: !checkedAll
            });
        }
    },
    created: function () {}
};
</script>
<style>
/* @import '../templateDiagnostic/templateDiagnostic.css'; */

/* 根容器：撑满父容器 */
.mos-root {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.value-class {
    flex: none !important;
}

.nodata {
    color: #666;
}

.detail {
    border-bottom: 1rpx solid #f2f2f2;
}

.detailBox {
    line-height: 70rpx;
    font-weight: 600;
    color: #1f2937;
    border-bottom: 1rpx solid #f2f2f2;
    background: #fafbfc;
}

.selectall {
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 26rpx;
    color: #1687ff;
    background: #fff;
    border-bottom: 1rpx solid #f2f2f2;
    padding: 16rpx 20rpx;
    flex-shrink: 0;
    font-weight: 500;
}

.col-8__empty {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #9ca3af;
    font-size: 26rpx;
    padding: 80rpx 40rpx;
}

.col-8__empty-icon {
    width: 120rpx;
    height: 120rpx;
    background: #f4f7fb;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
    font-size: 56rpx;
    color: #cbd5e1;
}

.MedDody {
    flex: 1;
    min-height: 0;
    background: #fff;
    border-radius: 8rpx;
    overflow: hidden;
}

.MedDody__inner {
    display: flex;
    width: 100%;
    height: 100%;
}

.all {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f4f7fb;
}

.col-4 {
    width: 38%;
    flex-shrink: 0;
    background: #fafbfc;
    border-right: 2rpx solid #eee;
    overflow-y: auto;
    height: 100%;
}

.col-8 {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    background: #fff;
}

.col-8__body {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    position: relative;
}

.medArr {
    display: block;
    font-size: 28rpx;
    border-bottom: 1rpx solid #f2f2f2;
    font-weight: 400;
    padding: 24rpx 20rpx;
    color: #4b5563;
    line-height: 1.4;
    word-break: break-all;
}

.checkMedArr {
    display: block;
    font-size: 28rpx;
    border-bottom: 1rpx solid #f2f2f2;
    font-weight: 600;
    color: #1687ff;
    padding: 24rpx 16rpx;
    border-left: 6rpx solid #1687ff;
    background: #e8f3ff;
    line-height: 1.4;
    word-break: break-all;
}

/* 保存按钮：与 prescription.vue .diagnostibutton 风格一致的药丸悬浮按钮 */
.mos-root .diagnostibutton {
    position: fixed;
    left: 20rpx;
    right: 20rpx;
    bottom: 24rpx;
    height: 84rpx;
    line-height: 84rpx;
    background: #1890ff;
    color: #fff;
    font-size: 30rpx;
    font-weight: 500;
    text-align: center;
    border-radius: 999rpx;
    padding: 0;
    margin: 0;
    z-index: 10;
    box-shadow: 0 6rpx 16rpx rgba(24, 144, 255, 0.28);
}

.mos-root .diagnostibutton::after {
    border: initial;
}

.mos-root .diagnostibutton[disabled] {
    background: #91cfff;
    color: #fff;
    box-shadow: none;
}
</style>
