<template>
    <!-- pages/components/presriptionDetail/presriptionDetail.wxml -->
    <view class="page">
        <view class="page-head">
            <view class="view-head-prescStatusDesc">{{ getStatusInfo(statusObj.Desc).text }}</view>
            <view class="view-head-image">
                <image class="head-image" :mode="imageMode" :src="getStatusInfo(statusObj.Desc).image"></image>
            </view>
        </view>
        <view class="page-head-tip">
            <block v-if="aduitMark">
                <view class="cell cell--aduit" @tap="handleTip($event, { url: order.tipUrl })" :data-url="order.tipUrl">
                    <text class="cell-title cell-title--aduit">{{ order.prescStatusDesc }}</text>
                    <text class="cell-arrow">›</text>
                </view>
                <view class="head-tip-reason">
                    <view>
                        <text class="head-tip-text">操作信息:</text>
                        <text>{{ order.tip }}</text>
                    </view>
                    <view>
                        <text class="head-tip-text">
                            原
                            <text class="head-tip-text0">因:</text>
                        </text>
                        <text class="head-tip-text1">{{ order.labelText }}</text>
                    </view>
                </view>
            </block>
            <block v-if="patientData.patName !== undefined && patientData.patName !== ''">
                <view class="view-item-baseInfo">
                    <view>
                        <image class="scroll-view-item-image" :src="patientData.patImg"></image>
                    </view>
                    <view class="view-item-baseInfo-text">
                        <view>
                            <text>{{ patientData.patName }} {{ patientData.patNo }}</text>
                        </view>
                        <view class="view-item-baseInfo-sex">
                            <image
                                class="view-item-baseInfo-sex-image"
                                :src="patientData.patSexDesc == '男' ? imgDomain + '/images/icon/doctor/male.png' : imgDomain + '/images/icon/doctor/female.png'"
                            ></image>
                        </view>
                        <view class="view-item-baseInfo-age">
                            <text class="view-item-baseInfo-ageText">{{ patientData.patAge }}</text>
                        </view>
                    </view>
                </view>
            </block>
        </view>

        <view class="scrollView">
            <view class="cell cell--section">
                <text class="cell-title cell-title--section">{{ panelMsg[type] }}</text>
                <text class="cell-value cell-value--link" @tap="navigateToProcess">医嘱处理时间轴</text>
            </view>
            <block v-if="type === 2">
                <block v-for="(item, index) in jList" :key="index">
                    <view class="cell">
                        <text class="cell-title">{{ item.title }}</text>
                        <text :class="'cell-value ' + (item.code === 'prescPrice' ? 'orderPresc-fontColor' : '')">{{ item.value }}</text>
                    </view>
                </block>
            </block>
            <block v-else-if="type === 3">
                <block v-for="(item, index) in yList" :key="index">
                    <view class="cell">
                        <text class="cell-title">{{ item.title }}</text>
                        <text :class="'cell-value ' + (item.code === 'prescPrice' ? 'orderPresc-fontColor' : '')">{{ item.value }}</text>
                    </view>
                </block>
            </block>
            <block v-else>
                <block v-for="(item, index) in orderPresc" :key="index">
                    <view class="cell">
                        <text class="cell-title">{{ item.title }}</text>
                        <text :class="'cell-value ' + (item.code === 'prescPrice' ? 'orderPresc-fontColor' : '')">{{ item.value }}</text>
                    </view>

                    <block v-if="item.code === 'medItem' && herbsData.length > 0">
                        <block v-for="(herbsItem, index1) in herbsData" :key="index1">
                            <view class="herbs">
                                <view
                                    class="herbs-item-comPrinciple"
                                    :style="
                                        'background-color:' +
                                        (herbsItem.comPrinciple == '君'
                                            ? '#FFA23E'
                                            : herbsItem.comPrinciple == '臣'
                                            ? '#39D1D1'
                                            : herbsItem.comPrinciple == '佐'
                                            ? '#FA5AB2'
                                            : herbsItem.comPrinciple == '使'
                                            ? '#AA71F9'
                                            : '')
                                    "
                                >
                                    {{ herbsItem.comPrinciple !== undefined && herbsItem.comPrinciple !== '' ? herbsItem.comPrinciple + '药' : '' }}
                                </view>
                                <view class="herbs-item-medItem">{{ herbsItem.medItem !== undefined && herbsItem.medItem !== '' ? herbsItem.medItem : '' }}</view>
                                <view class="herbs-item-decoctMethod">
                                    {{ herbsItem.dose !== undefined && herbsItem.dose !== '' ? '【' + herbsItem.dose + '】' : ''
                                    }}{{ herbsItem.decoctMethod !== undefined && herbsItem.decoctMethod !== '' ? ' 【' + herbsItem.decoctMethod + '】' : '' }}
                                </view>
                            </view>
                        </block>
                    </block>
                </block>
            </block>

            <block v-if="refundFee.refundDateTime && (refundFee.refundDateTime !== undefined) && (refundFee.refundDateTime !== '')">
                <view class="cell cell--section">
                    <text class="cell-title cell-title--section">退费信息</text>
                    <text class="cell-value"></text>
                </view>
                <block v-for="(item, index) in refundFee" :key="index">
                    <view class="cell">
                        <text class="cell-title">{{ item.title }}</text>
                        <text class="cell-value">{{ item.value }}</text>
                    </view>
                </block>
            </block>
            <view class="cell cell--section">
                <text class="cell-title cell-title--section">支付信息</text>
                <text class="cell-value"></text>
            </view>
            <block v-for="(item, index) in orderFee" :key="index">
                <view class="cell">
                    <text class="cell-title">{{ item.title }}</text>
                    <text class="cell-value">{{ item.value }}</text>
                </view>
            </block>
        </view>
    </view>
</template>
<script>
// pages/components/presriptionDetail/presriptionDetail.js
import Cache from '../../../../utils/cache.js';
import { $http } from '../../../../config/https.js';
import { httpconfig } from '../../../../config/httpconfig';
const userData = Cache.get('userData');
const patientData = Cache.get('patientData');
// 状态描述 → 显示文字 / 状态图标 映射表
// 兼容后端返回 Desc 为数字字符串（'505'）或中文描述（'已计费'）
const STATUS_MAP = {
    '505': { text: '已审核通过', image: '../../resources/aduitPass.png' },
    '506': { text: '审核未通过', image: '../../resources/auditOff.png' },
    '507': { text: '申诉中',     image: '../../resources/appealed.png' },
    '501': { text: '已发药',     image: '../../resources/deliveredMed.png' },
    '503': { text: '已退药',     image: '../../resources/returnDrug.png' },
    '已审核通过': { text: '已审核通过', image: '../../resources/aduitPass.png' },
    '审核未通过': { text: '审核未通过', image: '../../resources/auditOff.png' },
    '申诉中':     { text: '申诉中',     image: '../../resources/appealed.png' },
    '已发药':     { text: '已发药',     image: '../../resources/deliveredMed.png' },
    '已退药':     { text: '已退药',     image: '../../resources/returnDrug.png' },
    '已计费':     { text: '已计费',     image: '../../resources/unconfirmed.png' }
};
const STATUS_DEFAULT = { image: '../../resources/unconfirmed.png' };
export default {
    data() {
        return {
            imgDomain: httpconfig.imgDomain,
            panelMsg: ['处方信息', '处方信息', '医嘱信息', '处方信息'],
            imageMode: 'scaleToFill',
            tipIsLink: true,

            patientData: {
                patName: '',
                patImg: '',
                patNo: '',
                patSexDesc: '',
                patAge: ''
            },

            statusObj: {
                Code: '',
                Desc: ''
            },

            reasonLabel: `原因:`,
            perscProcessUrl: '',

            order: {
                prescStatusDesc: '',
                tip: '',
                labelText: '',
                tipUrl: ''
            },

            aduitMark: false,

            //审核拒绝或是申诉详情
            herbsData: [],

            //西药/草药
            orderPresc: [
                { title: '处方号',   value: '', code: 'prescno' },
                { title: '确认时间', value: '', code: 'confirmDate' },
                { title: '签名时间', value: '', code: 'signatureDate' },
                { title: '医嘱名称', value: '', code: 'medItem' },
                { title: '规格',     value: '', code: 'spec' },
                { title: '用法',     value: '', code: 'usage' },
                { title: '数量',     value: '', code: 'qty' },
                { title: '单价',     value: '', code: 'unitPrice' },
                { title: '总金额',   value: '', code: 'prescPrice' }
            ],

            // 检查
            jList: [
                { title: '检查号',   value: '', code: 'prescNo' },
                { title: '确认时间', value: '', code: 'confirmDate' },
                { title: '签名时间', value: '', code: 'signatureDate' },
                { title: '医嘱名称', value: '', code: 'medItem' },
                { title: '检查目的', value: '', code: 'appPurpose' },
                { title: '检查部位', value: '', code: 'position' },
                { title: '数量',     value: '', code: 'qty' },
                { title: '单价',     value: '', code: 'unitPrice' },
                { title: '总金额',   value: '', code: 'prescPrice' },
                { title: '结算类型', value: '', code: 'admReason' },
                { title: '执行科室', value: '', code: 'execLoc' }
            ],

            // 检验
            yList: [
                { title: '检查号',   value: '', code: 'prescNo' },
                { title: '确认时间', value: '', code: 'confirmDate' },
                { title: '签名时间', value: '', code: 'signatureDate' },
                { title: '医嘱名称', value: '', code: 'medItem' },
                { title: '标本',     value: '', code: 'specimen' },
                { title: '数量',     value: '', code: 'qty' },
                { title: '单价',     value: '', code: 'unitPrice' },
                { title: '总金额',   value: '', code: 'prescPrice' },
                { title: '结算类型', value: '', code: 'admReason' },
                { title: '执行科室', value: '', code: 'execLoc' }
            ],

            orderFee: [
                { title: '支付状态', value: '', code: 'payStatus' },
                { title: '支付时间', value: '', code: 'payDateTime' },
                { title: '支付金额', value: '', code: 'patAmt' },
                { title: '支付方式', value: '', code: 'payType' }
            ],

            refundFee: [
                { title: '退费时间', value: '', code: 'refundDateTime' },
                { title: '已退数量', value: '', code: 'refundNum' },
                { title: '退费金额', value: '', code: 'refundPatAmt' }
            ],

            winWidth: '',
            winHeight: '',
            prescAudit: '',

            herbsItem: {
                comPrinciple: '',
                medItem: '',
                dose: '',
                decoctMethod: ''
            }
        };
    },
    /**
     * 组件的属性列表
    */
    props: {
        ordID: String,
        prescNo: String,
        type: Number
    },
    /**
     * 组件的方法列表
    */
    methods: {
        /**
         * 根据后端返回的 statusObj.Desc 返回 { text, image }
         * text: 优先用映射表里的中文，缺失时回退原始 desc
         * image: 映射表里查图标，缺失时用 unconfirmed.png
         */
        getStatusInfo: function (desc) {
            if (desc === undefined || desc === null || desc === '') {
                return { text: '', image: STATUS_DEFAULT.image };
            }
            const entry = STATUS_MAP[desc];
            if (entry) {
                return { text: entry.text, image: entry.image };
            }
            return { text: desc, image: STATUS_DEFAULT.image };
        },

        navigateToProcess: function () {
            uni.navigateTo({ url: this.perscProcessUrl });
        },

        handlePageShow: function () {
            this.findOrdData();
        },

        handlePageHide: function () {},
        handlePageResize: function (size) {},
        ready: function (options) {},

        // 生命周期函数
        attached: function (options) {
            var that = this;
            uni.getSystemInfo({
                success: function (res) {
                    that.setData({
                        winWidth: res.windowWidth,
                        winHeight: res.windowHeight
                    });
                }
            });
            uni.setNavigationBarTitle({
                title: '医嘱详情'
            });
            this.setData({
                patientData: patientData
            });
            // 初始化时拉取数据（H5 端没有 Page.onShow，自动调用一次）
            this.findOrdData();
        },

        handleTip: function (e, _dataset) {
            this.handleDataset(e, _dataset);
            let { prescNo, prescAudit } = this;
            let { dataset } = e.currentTarget;
            uni.navigateTo({
                url: '/pages/entryWrite/page/Entry/prescription/prescAuditDetail/prescAuditDetail?prescNo=' + prescNo
            });
        },

        findOrdData: function () {
            let { ordID, prescNo, orderPresc, orderFee, refundFee, order, herbsData, type } = this;
            console.log('type', type);
            let { hospID } = Cache.get('userData');
            let data = {
                params: [
                    {
                        ordID,
                        prescNo,
                        hospID,
                        flag: type === 2 || type === 3 ? 'Y' : 'N'
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100072',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        let result = res.result;
                        let newherbsData = [...herbsData];
                        let herbsFlag = false;
                        if (result.hasOwnProperty('herbsData') && result.herbsData.length > 0) {
                            newherbsData = [...result.herbsData];
                            herbsFlag = true;
                        }
                        let newOrderPresc = [...orderPresc];
                        if (result.hasOwnProperty('medObj')) {
                            newOrderPresc.map((element) => {
                                if (result.medObj.hasOwnProperty(element.code)) {
                                    element.value = result.medObj[element.code];
                                }
                                if (element.code === 'prescno') {
                                    element.value = this.prescNo;
                                }
                                if (
                                    (element.code === 'unitPrice' || element.code === 'prescPrice') &&
                                    result.medObj[element.code] !== undefined &&
                                    result.medObj[element.code] !== ''
                                ) {
                                    element.value = `￥${result.medObj[element.code]}`;
                                }
                            });
                        }
                        if (herbsFlag) {
                            //草药过滤规格及用法
                            newOrderPresc = newOrderPresc.filter((element) => (element.code !== 'spec') && (element.code !== 'usage'));
                            newOrderPresc.forEach((element) => {
                                if (element.code === 'medItem') {
                                    element.title = '医嘱内容';
                                }
                                if (element.code === 'qty') {
                                    element.value = `${newherbsData[0].durQty}`;
                                }
                            });
                        }
                        let newPatientData = {
                            ...patientData
                        };
                        if (result.hasOwnProperty('patObj')) {
                            newPatientData = {
                                ...result.patObj
                            };
                        }
                        let newOrderFee = [...orderFee];
                        if (result.hasOwnProperty('payObj')) {
                            newOrderFee.map((element) => {
                                if (result.payObj.hasOwnProperty(element.code)) {
                                    element.value = result.payObj[element.code];
                                }
                                if (element.code == 'payDateTime' && result.payObj.hasOwnProperty('payDate') && result.payObj.hasOwnProperty('payTime')) {
                                    element.value = `${result.payObj.payDate} ${result.payObj.payTime}`;
                                }
                            });
                        }
                        let newRefundFee = [...refundFee];
                        if (result.hasOwnProperty('refundObj')) {
                            newRefundFee.map((element) => {
                                if (result.refundObj.hasOwnProperty(element.code)) {
                                    element.value = result.refundObj[element.code];
                                }
                            });
                        }
                        let newOrder = {
                            ...order
                        };
                        if (result.hasOwnProperty('audObj')) {
                            newOrder.prescStatusDesc = result.audObj.auditstatus;
                            newOrder.tip = result.audObj.auditDateTime;
                            newOrder.labelText = result.audObj.reason;
                            if (result.audObj['docAudit'] !== undefined && result.audObj.docAudit['auditstatus'] !== undefined) {
                                newOrder.prescStatusDesc = result.audObj.docAudit['auditstatus'];
                                newOrder.tip = `${result.audObj.docAudit['docName']} ${result.audObj.docAudit['auditDateTime']}`;
                                newOrder.labelText = result.audObj.docAudit['reason'];
                            }
                        }
                        let newJList = [];
                        if (type === 2) {
                            newJList = this.jList.map((item) => {
                                let { value, ...other } = item;
                                return {
                                    value: result.medObj[item.code],
                                    ...other
                                };
                            });
                        }
                        let newYList = [];
                        if (type === 3) {
                            newYList = this.yList.map((item) => {
                                let { value, ...other } = item;
                                return {
                                    value: result.medObj[item.code],
                                    ...other
                                };
                            });
                        }
                        this.setData({
                            statusObj: result.statusObj,
                            prescAudit: result.audObj,
                            orderPresc: newOrderPresc,
                            orderFee: newOrderFee,
                            refundFee: newRefundFee,
                            aduitMark: result['audObj'] !== undefined && result.audObj['mark'] !== undefined && result.audObj.mark == 'Y' ? true : false,
                            order: newOrder,
                            patientData: newPatientData,
                            herbsData: newherbsData,
                            perscProcessUrl: '/pages/entryWrite/page/Entry/prescription/prescProcess/prescProcess?ordID=' + ordID,
                            jList: newJList,
                            yList: newYList
                        });
                    } else {
                        uni.showToast({
                            title: res.result.errorMessage
                        });
                        return;
                    }
                }
            });
        }
    },
    mounted() {
        this.attached();
        this.$nextTick(() => this.ready());
    },
    moved: function () {},
    destroyed: function () {},
    created: function () {}
};
</script>
<style>
.page {
    margin: 10rpx 24rpx 0rpx 24rpx;
    display: flex;
    flex-direction: column;
    height: 100vh;
}
.page-head {
    display: flex;
    position: relative;
    background-image: linear-gradient(to right, #f1451e, #fc7d40);
    width: 705rpx;
    height: 170rpx;
}
.view-head-prescStatusDesc {
    font-size: 40rpx;
    font-weight: 500;
    margin-left: 102rpx;
    margin-top: 50rpx;
    color: #ffffff;
}
.view-head-image {
    position: absolute;
    right: 49rpx;
    top: 30rpx;
}
.head-image {
    width: 152rpx;
    height: 128rpx;
}
.page-head-tip {
    background-color: rgba(240, 245, 248, 1);
}
.head-tip-reason {
    background-color: #ffffff;
    padding-left: 36rpx;
    padding-bottom: 24rpx;
}
.head-tip-text {
    color: #999999;
}
.head-tip-text0 {
    margin-left: 64rpx;
}
.head-tip-text1 {
    margin-left: 14rpx;
}
.van-cell__left-icon-wrap {
    color: #0079fe !important;
    font-size: 50rpx !important;
    margin-top: 20rpx !important;
}
.page-head-tip-patInfo {
    font-size: 36rpx;
}
.view-item-baseInfo {
    font-size: 32rpx;
    display: flex;
    flex-direction: row;
    margin-top: 10rpx;
    background-color: #ffffff;
}
.scroll-view-item-image {
    margin-left: 36rpx;
    margin-top: 10rpx;
    width: 100rpx;
    height: 100rpx;
}
.view-item-baseInfo-text {
    margin-top: 36rpx;
    margin-left: 24rpx;
    display: flex;
    flex-direction: row;
}
.view-item-baseInfo-sex {
    margin-left: 12rpx;
    margin-top: 4rpx;
}
.view-item-baseInfo-sex-image {
    height: 36rpx;
    width: 36rpx;
}
.view-item-baseInfo-age {
    margin-top: -4rpx;
}
.view-item-baseInfo-ageText {
    background-color: #13c2c2;
    color: #ffffff;
    font-size: 28rpx;
    margin-left: 12rpx;
    height: 36rpx;
    width: 72rpx;
}
.head-tip-label {
    color: #ff9933 !important;
}
.orderPresc-fontColor {
    color: #ff9933 !important;
}
.scrollView {
    margin-top: 4rpx;
    flex: 1;
    overflow: auto;
}

/* === 原生 cell 样式（替代 van-cell） === */
.cell {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 24rpx;
    background: #ffffff;
    border-bottom: 1rpx solid #f0f0f0;
}
.cell--aduit {
    background: #ffffff;
    padding: 24rpx 24rpx;
}
.cell--section {
    background: #f5f7fa;
    padding: 24rpx;
}
.cell-title {
    font-size: 28rpx;
    color: #333333;
    flex: none;
}
.cell-title--aduit {
    font-size: 32rpx;
    font-weight: 900;
}
.cell-title--section {
    font-size: 32rpx;
    font-weight: 900;
    color: #333333;
}
.cell-value {
    font-size: 28rpx;
    color: #666666;
    text-align: right;
}
.cell-value--link {
    color: #1890ff;
    font-weight: 600;
}
.cell-arrow {
    color: #1890ff;
    font-size: 36rpx;
    line-height: 1;
    margin-left: 8rpx;
}

.herbs {
    display: flex;
    background-color: #fff;
    padding-left: 30rpx;
    padding-top: 16rpx;
}
.herbs-item-comPrinciple {
    font-size: 24rpx;
    height: 40rpx;
    width: 72rpx;
    padding-top: 6rpx;
    text-align: center;
    color: #ffffff;
}
.herbs-item-medItem {
    font-size: 28rpx;
    margin-left: 20rpx;
}
.herbs-item-decoctMethod {
    margin-left: 25rpx;
}
</style>
