<template>
    <view class="hd-root">
        <view class="diagnostic-wrapper">
            <view class="container">
                <view class="col">
                    <view class="col-4">
                        <radio-group class="group" @change="radioChange">
                            <view class="label" :style="item.checked ? 'color: #0079FE;border-left: 5rpx solid #0079FE' : ''" v-for="(item, index) in admList" :key="index">
                                <radio :id="item.admID" hidden :value="item.admID" :checked="item.checked"></radio>

                                <label style="mr20" :for="item.admID">
                                    <view class="locitem">
                                        <view class="locitem__date">{{ item.admDate }}</view>
                                        <view class="locitem__loc">{{ item.admLocDesc }}</view>
                                    </view>
                                </label>
                            </view>
                        </radio-group>
                    </view>
                    <view class="col-8" v-if="active === 0 && historyAdmID != ''">
                        <view class="selectall">
                            <checkbox :checked="checkedAll" @tap="checkall">全选/取消全选</checkbox>
                        </view>
                        <van-checkbox-group :value="selectedXArr" @change="onChange1">
                            <van-cell-group>
                                <van-cell
                                    :title="item.ordMedItemDesc || item.ordDesc || ''"
                                    :label="item.ordUsageDesc ? '用法：' + item.ordUsageDesc : ''"
                                    value-class="value-class"
                                    clickable
                                    :data-index="index"
                                    @click="toggle($event, { index })"
                                    v-for="(item, index) in historyPresList"
                                    :key="index"
                                >
                                    <van-checkbox @tap.native.stop.prevent="noop" :class="'checkboxes-' + index" :name="item.ordID" />
                                </van-cell>
                            </van-cell-group>
                        </van-checkbox-group>
                        <!-- <checkbox-group class="group" bindchange="checkboxChange">
										<view class="div" wx:for="{{historyPresList}}" wx:key="ordID">
												<view class="col-12">
														<label class="col-10">
																<checkbox hidden value="{{item.ordID}}" checked="{{item.checked}}"></checkbox>
																<text class="text">{{item.ordMedItemDesc}}</text>
														</label>
														<view class="icon">
																<mp-icon type="field" icon="done" color="#0079FE" style="opacity:{{item.checked ? 1: 0}}"></mp-icon>
														</view>
												</view>
												<view wx:if="{{item.specDesc}}">
														<text class="font">规格：{{item.specDesc}}</text>
												</view>
												<view wx:if="{{item.ordUsageDesc}}">
														<text class="font">用法：{{item.ordUsageDesc}}</text>
												</view>
										</view>
								</checkbox-group> -->
                    </view>
                    <view class="col-8" v-if="active === 1 && historyAdmID != ''">
                        <view class="selectall">
                            <checkbox :checked="checkedAll" @tap="checkall">全选/取消全选</checkbox>
                        </view>
                        <view class="overview">
                            <picker class="fontS30" @change="bindPickerChangeCM" :value="selectCMIndex" :range="presCMList" range-key="title">
                                <view class="col-12">
                                    <view class="col-9">
                                        <view class="moreHide">处方概述：{{ presCMList[selectCMIndex].title }}</view>
                                    </view>
                                    <view class="col-2">
                                        <mp-badge :content="presCMCount" style="margin-left: 5px" />
                                    </view>
                                    <view class="col-1">
                                        <mp-icon icon="arrow" color="#999999" :size="17"></mp-icon>
                                    </view>
                                </view>
                            </picker>
                        </view>
                        <view class="usage">
                            <view>
                                <text class="fontS30">用药方法</text>
                            </view>
                            <view>
                                <text class="font">{{ presCMList[selectCMIndex].note }}</text>
                            </view>
                        </view>
                        <view class="detail">
                            <view>
                                <text class="fontS30">用药明细</text>
                            </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 presCMDetailList"
                                        :key="index"
                                    >
                                        <view slot="title">
                                            <view class="van-cell-text">
                                                <van-tag
                                                    :color="
                                                        item.comPrincipleCode === '01'
                                                            ? '#FFA33C'
                                                            : item.comPrincipleCode === '02'
                                                            ? '#36D2D2'
                                                            : item.comPrincipleCode === '03'
                                                            ? '#FA5AB4'
                                                            : '#AB72F9'
                                                    "
                                                >
                                                    {{
                                                        item.comPrincipleCode === '01'
                                                            ? '君药'
                                                            : item.comPrincipleCode === '02'
                                                            ? '臣药'
                                                            : item.comPrincipleCode === '03'
                                                            ? '佐药'
                                                            : '使药'
                                                    }}
                                                </van-tag>
                                                {{ item.ordDesc + (item.decoctMethodID ? ' 【' + item.decoctMethodDesc + '】' : '') }}
                                            </view>
                                        </view>

                                        <van-checkbox @tap.native.stop.prevent="noop" :class="'checkboxes-' + index" :name="item.ordID" />
                                    </van-cell>
                                </van-cell-group>
                            </van-checkbox-group>
                            <!-- <checkbox-group class="group" bindchange="checkboxChangeCM">
												<view class="div-detail" wx:for="{{presCMDetailList}}" wx:key="ordID">
														<label class="col-10">
																<checkbox hidden value="{{item.ordID}}" checked="{{item.checked}}"></checkbox>
																<text class="text">{{item.ordDesc}}</text>
														</label>
														<view class="icon">
																<mp-icon type="field" icon="done" color="#0079FE" style="opacity:{{item.checked ? 1: 0}}"></mp-icon>
														</view>
														<view wx:if="{{item.doseTxt}}">
																<text class="font">{{item.doseTxt}}</text>
														</view>
														<view wx:if="{{item.ordUsageDesc}}">
																<text class="font">用法：{{item.ordUsageDesc}}</text>
														</view>
												</view>
										</checkbox-group> -->
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- <view class="bottomView"> -->
        <button class="diagnostibutton" @tap="savePres" :disabled="isLoading">{{ isLoading ? '保存中' : '保存到医嘱列表' }}</button>
        <!-- </view> -->
    </view>
</template>

<script>
import Cache from '../../../../../../../utils/cache';
// pages/Entry/prescription/addPrescription/historicalDiagnosis/historicalDiagnosis.js
import { $http } from '../../../../../../../config/https';
export default {
    components: {},
    data() {
        return {
            selectIndex: '0',

            presTypeList: [
                {
                    id: '0',
                    name: '西医及其他'
                },
                {
                    id: '1',
                    name: '草药'
                }
            ],

            admList: [],
            historyAdmID: '',
            historyPresList: [],
            selectCMIndex: '0',
            presCMList: [],
            presCMCount: 0,
            presCMDetailList: [],
            selectedArr: [],
            selectedXArr: [],
            isLoading: false,
            checkedAll: false,
            title: '',
            note: ''
        };
    },
    /**
     * 组件的属性列表
     */
    options: {
        addGlobalClass: true
    },
    props: {
        active: {
            type: Number,
            //类型
            default: 0 //默认值
        },

        addInfo: {
            type: Object,
            //类型
            default: () => ({}) //默认值
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
    },
    /**
     * 组件的方法列表
     */
    methods: {
        ready: function () {
            // 在组件在视图层布局完成后执行

            this.getHistoryAdmList();
        },

        attached: function () {},

        childFun: function () {
            this.setData(
                {
                    checkedAll: false
                },
                () => {
                    if (this.active === 0) {
                        this.getHistoryOrderList(this.historyAdmID);
                    } else {
                        this.getHistoryCMOrderList(this.historyAdmID);
                    }
                }
            );
        },

        bindPickerChangeCM: function (e) {
            this.setData(
                {
                    selectCMIndex: e.detail.value,
                    selectedArr: []
                },
                () => this.getHistoryCMOrderDetail(this.presCMList[e.detail.value].ordPrescNo)
            );
        },

        getHistoryAdmList: function () {
            const userData = Cache.get('userData');
            const patientData = Cache.get('patientData');
            $http.post('urlDeault', this, {
                code: '03050052',
                data: {
                    params: [
                        {
                            patID: patientData.patID,
                            hospID: userData.hospID
                        }
                    ]
                },
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        const list = (res.result && res.result.data) || [];
                        // 默认选中第一条就诊记录，并加载对应的历史医嘱
                        if (list.length > 0) {
                            list[0].checked = true;
                        }
                        this.setData({
                            admList: list,
                            historyAdmID: list.length > 0 ? list[0].admID : '',
                            checkedAll: false
                        }, () => {
                            if (list.length > 0) {
                                if (this.active === 0) {
                                    this.getHistoryOrderList(list[0].admID);
                                } else {
                                    this.getHistoryCMOrderList(list[0].admID);
                                }
                            }
                        });
                    }
                }
            });
        },

        // 历史处方（西药及其他）
        getHistoryOrderList: function (admID) {
            $http.post('urlDeault', this, {
                code: '03050022',
                data: {
                    params: [
                        {
                            admID
                        }
                    ]
                },
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData({
                            historyPresList: (res.result && res.result.data) || [],
                            selectedXArr: []
                        });
                    }
                }
            });
        },

        // 历史处方（草药）
        getHistoryCMOrderList: function (admID) {
            const userData = Cache.get('userData');
            $http.post('urlDeault', this, {
                code: '03050058',
                data: {
                    params: [
                        {
                            admID,
                            hospID: userData.hospID
                        }
                    ]
                },
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                presCMList: res.result.data,
                                presCMCount: res.result.totalCount,
                                selectedArr: []
                            },
                            () => {
                                if (res.result.totalCount > 0) {
                                    this.getHistoryCMOrderDetail(res.result.data[0].ordPrescNo);
                                } else {
                                    this.setData({
                                        presCMDetailList: res.result.data
                                    });
                                }
                            }
                        );
                    }
                }
            });
        },

        // 获取草药处方明细
        getHistoryCMOrderDetail: function (ordPrescNo) {
            const userData = Cache.get('userData');
            var { addInfo } = this;
            $http.post('urlDeault', this, {
                code: '03050059',
                data: {
                    params: [
                        {
                            ordPrescNo,
                            hospID: userData.hospID,
                            recLocID: addInfo.recLoc ? addInfo.recLoc.id : '' //科室
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData({
                            presCMDetailList: res.data
                        });
                    }
                }
            });
        },

        radioChange: function (e) {
            let checked = e.detail.value;
            this.setData(
                {
                    checkedAll: false
                },
                () => {
                    let changed = {};
                    for (let i = 0; i < this.admList.length; i++) {
                        if (checked == this.admList[i].admID) {
                            changed['admList[' + i + '].checked'] = true;
                            if (this.active === 0) {
                                this.getHistoryOrderList(e.detail.value);
                            } else {
                                this.getHistoryCMOrderList(e.detail.value);
                            }
                        } else {
                            changed['admList[' + i + '].checked'] = false;
                        }
                    }
                    changed.historyAdmID = e.detail.value;
                    this.setData(changed);
                }
            );
        },

        checkboxChange: function (e) {
            let checked = e.detail.value;
            let changed = {};
            for (let i = 0; i < this.historyPresList.length; i++) {
                if (checked == this.historyPresList[i].ordID) {
                    changed['historyPresList[' + i + '].checked'] = true;
                } else {
                    changed['historyPresList[' + i + '].checked'] = false;
                }
            }
            this.setData(changed);
        },

        // 选择草药
        checkboxChangeCM: function (e) {
            let checked = e.detail.value;
            let changed = {};
            for (let i = 0; i < this.presCMDetailList.length; i++) {
                if (checked == this.presCMDetailList[i].ordID) {
                    changed['presCMDetailList[' + i + '].checked'] = true;
                } else {
                    changed['presCMDetailList[' + i + '].checked'] = false;
                }
            }
            this.setData(changed);
        },

        selectPres: function (e) {
            let checked = e.currentTarget.id;
            let changed = {};
            for (let i = 0; i < this.historyPresList.detail.length; i++) {
                if (checked == this.historyPresList.detail[i].id) {
                    changed['historyPresList']['detail[' + i + '].checked'] = true;
                } else {
                    changed['historyPresList']['detail[' + i + '].checked'] = false;
                }
            }
            this.setData(changed);
        },

        savePres: function (e) {
            this.setData({
                isLoading: true
            });
            const { historyPresList, presCMDetailList } = this;
            const userData = Cache.get('userData');
            const patientData = Cache.get('patientData');
            let orderData = [];
            let orderObj = {};
            if (this.active === 0) {
                historyPresList.map((item) => {
                    if (this.selectedXArr.includes(item.ordID)) {
                        item.ordID = '';
                        item.medID = item.ordMedItemID;
                        item.ordSeqNo = '';
                        item.otherFlag = 1;
                        orderData.push(item);
                    }
                });
                // 关键修复：addPrescription.vue 没有 callData 方法，
                // 正确的方法是 callDataFun（与 getAddInfo 一致），
                // 兜底 wListPush / gListPush 以兼容老链路
                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('[historicalDiagnosis.savePres] 西药通知父页面失败:', err);
                }
                uni.navigateBack({
                    delta: 1
                });
            } else {
                presCMDetailList.map((item) => {
                    if (this.selectedArr.includes(item.ordID)) {
                        item.ordID = '';
                        item.ordSeqNo = '';
                        item.otherFlag = 1;
                        item.ordDose = item.dose;
                        item.ordDoseUnitID = item.doseUnitID;
                        orderData.push(item);
                    }
                });
                // 关键在这里
                orderObj.select = 0;
                orderObj.data = orderData;
                this.$emit('changeSelect', {
                    detail: orderObj
                });
            }
            this.setData({
                isLoading: false
            });
        },

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

        onChange1(event) {
            // console.log(event)
            this.setData({
                selectedXArr: 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() {},

        checkall: function () {
            let data = this.historyPresList;
            let { checkedAll } = this;
            let checkData = [];
            if (!checkedAll) {
                if (this.active == 1) {
                    data = this.presCMDetailList;
                }
                for (var len = 0; len < data.length; len++) {
                    checkData.push(data[len].ordID);
                }
            }
            if (this.active == 1) {
                this.setData({
                    selectedArr: checkData,
                    checkedAll: !checkedAll
                });
            } else {
                this.setData({
                    selectedXArr: checkData,
                    checkedAll: !checkedAll
                });
            }
        }
    },
    created: function () {}
};
</script>
<style>
/* pages/Entry/prescription/addPrescription/historicalDiagnosis/historicalDiagnosis.wxss */
/* 根 view 撑满父容器 */
.hd-root {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.div {
    margin: 15rpx 0;
    background-color: #ffffff;
    border-bottom: 2rpx solid #f2f2f2;
}

.div > picker {
    height: 60rpx;
}

.container {
    display: flex;
    flex: 1;
    min-height: 0;
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 8rpx;
    overflow: hidden;
}

.container .history {
    color: #0079fe;
    border-left: 5rpx solid #0079fe;
    font-size: 0.8rem;
    margin-bottom: 20rpx;
}

.container .col {
    width: 100%;
    display: flex;
    flex: 1;
    min-height: 0;
}

.group {
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 1);
    padding: 0;
    font-size: 28rpx;
}

.button {
    border-radius: 50rpx;
    background: #0079fe;
    color: white;
    font-size: 30rpx;
}

.col-8 {
    flex: 1;
    min-width: 0;
    background-color: #ffffff;
    height: 100%;
    overflow-y: auto;
    border-left: 2rpx solid #f2f2f2;
    display: flex;
    flex-direction: column;
}

.col-12 {
    background-color: #ffffff;
    margin-bottom: 10rpx;
}

.detailTitle {
    border-top: 1rpx solid #f2f2f2;
    margin-top: 10rpx;
}

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

.label {
    margin: 0;
    border-bottom: 2rpx solid #f5f4f4;
    padding: 20rpx 16rpx;
    background: #fff;
}

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

.icon {
    display: inline-block;
}

.font {
    font-size: 28rpx;
    width: 100%;
    color: #999999;
}

.overview {
    padding: 14rpx 16rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #f2f2f2;
}

.overview .moreHide {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.usage {
    background-color: #ffffff;
    margin: 2rpx 0;
    padding: 12rpx 16rpx;
    width: 100%;
    border-bottom: 1rpx solid #f2f2f2;
}

.detail {
    background-color: #ffffff;
    padding: 0;
    flex: 1;
    min-height: 0;
    overflow-y: auto;
}

.div-detail {
    margin-top: 15rpx;
    background-color: #ffffff;
    border-top: 2rpx solid #f2f2f2;
}

.detail .group {
    height: 700rpx;
}

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

.locitem {
    font-size: 26rpx;
    font-weight: 400;
    line-height: 1.4;
}

.locitem__date {
    color: #1f2937;
    font-size: 28rpx;
    margin-bottom: 4rpx;
}

.locitem__loc {
    color: #6b7280;
    font-size: 24rpx;
}

.selectall {
    font-size: 28rpx;
    background: #ffffff;
    border-bottom: 1rpx solid #f5f4f4;
    color: #1890ff;
    padding: 18rpx 20rpx;
    flex-shrink: 0;
}

/* 重置默认 style="mr20" 无效样式 */
.label[style*="mr20"] {
    margin-right: 0;
}

/* 保存按钮：与 prescription.vue .diagnostibutton 风格一致的药丸悬浮按钮 */
.hd-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);
}

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

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