<template>
    <view>
        <!-- pages/Entry/prescription/addPrescription/addPrescription.wxml -->
        <nav-bar :navbarData="navbarData"></nav-bar>
        <van-dialog id="van-dialog" />
        <view class="container">
            <view class="diagnosticEntry" :style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx)'">
                <view class="header-wrapper">
                    <view class="diagnosticheader">
                        <view class="header-flex" :data-index="index" @tap="tapChange" v-for="(item, index) in array" :key="index">
                            <view :class="'diagnosticheaderBox ' + (select === index ? 'select' : '') + ' ' + (index !== 3 ? 'borderRight' : '')">{{ item.title }}</view>
                        </view>
                    </view>
                </view>
                <view>
                    <view class="fontS30 slectBox" v-if="!(select === 2 || select === 3)">
                        <picker @change="bindPickerChange" :value="active" :range="objectArray" range-key="name">
                            <view class="picker weui-select">
                                当前选择：{{ objectArray[active].name }}
                                <mp-icon class="ml20" icon="arrow" color="black" :size="10"></mp-icon>
                            </view>
                        </picker>
                    </view>
                </view>
                <view :class="'diagnosticcontent  ' + (select === 2 || select === 3 ? '' : 't200') + ' '">
                    <!-- <view class="row">
				<view class="col clearn ">
					<view class="col-12"> -->

                    <view v-if="select === 0">
                        <!-- 自定义处方 -->
                        <customDiagnostics
                            id="customDiagnostics"
                            ref="customDiagnostics"
                            :overlay="overlay"
                            :wListData="wList"
                            :gListcallData="callData"
                            :gListData="gList"
                            :active="active"
                            :editData="editData"
                            @addInfo="getAddInfo($event, { tagId: 'customDiagnostics' })"
                        ></customDiagnostics>
                    </view>
                    <view v-if="select === 1">
                        <!-- 历史处方 -->
                        <historicalDiagnosis
                            id="historicalDiagnosis"
                            :addInfo="addInfo"
                            :active="active"
                            @changeSelect="changeSelect($event, { tagId: 'historicalDiagnosis' })"
                        ></historicalDiagnosis>
                    </view>
                    <view v-if="select === 2">
                        <!-- 处方模板 -->
                        <templateDiagnostic
                            id="templateDiagnostic"
                            :addInfo="addInfo"
                            :active="active"
                            @changeSelect="changeSelect($event, { tagId: 'templateDiagnostic' })"
                        ></templateDiagnostic>
                    </view>
                    <view v-if="select === 3">
                        <!-- 医嘱套 -->
                        <medicalOrderSet
                            id="medicalOrderSet"
                            :addInfo="addInfo"
                            :active="active"
                            @changeSelect="changeSelect($event, { tagId: 'medicalOrderSet' })"
                            @callDataPress="callDataPress($event, { tagId: 'medicalOrderSet' })"
                        ></medicalOrderSet>
                    </view>
                    <!-- </view>
				</view>
			</view> -->
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../../../../utils/cache';
import navBar from '@/pages/components/navbar/index';
import customDiagnostics from '@/pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/customDiagnostics';
import historicalDiagnosis from '@/pages/entryWrite/page/Entry/prescription/addPrescription/historicalDiagnosis/historicalDiagnosis';
import templateDiagnostic from '@/pages/entryWrite/page/Entry/prescription/addPrescription/templateDiagnostic/templateDiagnostic';
import medicalOrderSet from '@/pages/entryWrite/page/Entry/prescription/addPrescription/medicalOrderSet/medicalOrderSet';
// pages/Entry/prescription/addPrescription/addPrescription.js
// pages/entryWrite/page/Entry/prescription/addPrescription/1.js
const app = getApp();
import Dialog from '../../../../../../utils/dialog';
import { $http } from '../../../../../../config/https';
export default {
    components: {
        navBar,
        customDiagnostics,
        historicalDiagnosis,
        templateDiagnostic,
        medicalOrderSet
    },
    data() {
        return {
            select: 0,

            // 选中的值tabbox
            array: [
                {
                    title: '自定义医嘱'
                },
                {
                    title: '历史医嘱'
                },
                {
                    title: '医嘱模板'
                },
                {
                    title: '医嘱套'
                }
            ],

            // tab选项
            objectArray: [
                {
                    id: 0,
                    name: '西医及其他'
                },
                {
                    id: 1,
                    name: '草药'
                }
            ],

            wList: [],

            // 西药数据
            gList: [],

            // 草药数据
            callData: {},

            // 草药数据
            active: 0,

            // 切换
            editData: {},

            // 回显数据
            addInfo: {},

            navbarData: {
                isGoBack: true,
                background: '',
                title: '添加医嘱',
                //导航栏 中间的标题
                bottom: false
            },

            height: app.globalData.height,

            // 西药草药是否有权限
            overlay: 'N',

            addText: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 接收wList
        this.optionsUrl(options);
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        let { active } = this;
        // 验证是否有西药草药权限
        this.bindPickerChangeHttp(active);
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 获取选中的select数据
        searchSelect: function (selectData) {
            // H5 + Vue3 下 zpSelectComponent 通过 vnode.data.attrs.id 查找子组件不稳定,
            // 优先使用 Vue $refs 进行子组件调用。
            let child = (this.$refs && this.$refs.customDiagnostics) || null;
            if (!child && typeof this.zpSelectComponent === 'function') {
                try {
                    child = this.zpSelectComponent('#customDiagnostics');
                } catch (e) {
                    child = null;
                }
            }
            if (child && typeof child.searchSelect === 'function') {
                child.searchSelect(selectData);
            } else {
                // 兜底:写入缓存,等子组件自取
                try {
                    Cache.set('searchSelect', selectData);
                } catch (e) {}
            }
        },

        // 点击切换
        tapChange: function (event) {
            let { currentTarget } = event;
            let { array } = this;
            let dataset = currentTarget.dataset;
            this.navigationBarTitleText(dataset.index); //自定义导航栏切换
            this.setData(
                {
                    select: dataset.index,
                    // 选中的tab
                    addText: array[dataset.index].addText // 添加按钮名称
                },
                () => {
                    this.templateDiagnostic = this.zpSelectComponent('#templateDiagnostic');
                    this.historicalDiagnosis = this.zpSelectComponent('#historicalDiagnosis');
                    this.customDiagnostics = this.zpSelectComponent('#customDiagnostics');
                    this.medicalOrderSet = this.zpSelectComponent('#medicalOrderSet');
                }
            );
        },

        // 自定义导航栏切换
        navigationBarTitleText: function (i) {
            let { navbarData, array } = this;
            navbarData.title = array[i].title;
            this.setData({
                navbarData
            });
        },

        // 接收 url传参
        optionsUrl: function (options) {
            let wList = JSON.parse(options.wList); //解析得到对象
            let active = JSON.parse(options.active); //解析得到对象
            let editData = options.editData ? JSON.parse(options.editData) : {}; //解析得到对象
            this.setData({
                wList,
                active,
                editData
            });
        },

        // 回调执行
        callDataFun: function (data) {
            this.setData({
                gList: data
            });
        },

        // 获取子组件参数
        getAddInfo(e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            var obj = e.detail;
            // var obj = Object.assign(addInfo, e.detail);
            //  合并
            this.setData({
                addInfo: obj
            });
        },

        // 切换
        bindPickerChange: function (e) {
            this.setData(
                {
                    active: e.detail.value
                },
                () => {
                    this.bindPickerChangeHttp(e.detail.value); // 验证是否有西药草药权限
                    let { select } = this;
                    if (select === 1) {
                        this.historicalDiagnosis.childFun(); // 历史处方
                    }

                    if (select === 2) {
                        this.templateDiagnostic.childFun(); // 处方模板
                    }

                    if (select === 3) {
                        this.medicalOrderSet.childFun(); // 医嘱套
                    }
                }
            );
        },

        // 验证是否有西药草药权限
        bindPickerChangeHttp: function (type) {
            let patientData = Cache.get('patientData');
            let userData = Cache.get('userData');
            let { userID, locID, hospID } = userData;
            let { admID } = patientData;
            $http.post('urlDeault', this, {
                code: '03050229',
                data: {
                    params: [
                        {
                            admID: admID,
                            //就诊记录ID
                            userID: userID,
                            //用户id
                            locID: locID,
                            //科室id
                            hospID: hospID,
                            //医院id
                            cmFlag: type == 1 ? 'Y' : '' //草药录入标志
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode == '0') {
                        let { select } = this;
                        if (select == 0) {
                            this.setData({
                                overlay: 'N'
                            });
                        }
                    }
                },
                fail: function (res) {
                    let { select } = this;
                    if (select == 0) {
                        Dialog.alert({
                            title: '提示',
                            message: res.errorMessage,
                            context: this
                        }).then(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                        });
                    }
                }
            });
        },

        changeSelect: function (obj, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(obj, _dataset);
            /* ---处理dataset end--- */
            var data = obj.detail.data;
            console.log('chuandi', data);
            let errStr = '';
            var newArr = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i].hasOwnProperty('invalid')) {
                    if (errStr) {
                        errStr = errStr + ',' + data[i].invalid;
                    } else {
                        errStr = data[i].invalid;
                    }
                } else {
                    var newObj = {
                        searchSelect: {
                            medDesc: data[i].ordDesc,
                            medID: data[i].medID,
                            medPrice: data[i].price ? data[i].price : data[i].qtyUnitList[0].price
                        },
                        typeList: {
                            unitDesc: data[i].ordDoseUnitDesc,
                            unitID: data[i].ordDoseUnitID
                        },
                        jl: data[i].ordDose,
                        comPrinciple: {
                            id: data[i].comPrincipleID,
                            descripts: data[i].comPrincipleDesc
                        },
                        decoctMethod: {
                            id: data[i].decoctMethodID,
                            descripts: data[i].decoctMethodDesc
                        }
                    };
                    newArr.push(newObj);
                }
            }
            if (errStr) {
                Dialog.alert({
                    title: '提示',
                    message: errStr + '为无效药',
                    context: this
                });
            }
            this.setData({
                select: obj.detail.select,
                gList: newArr
            });
        },

        callDataPress: function (obj, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(obj, _dataset);
            /* ---处理dataset end--- */
            var data = obj.detail.data;
            this.setData(
                {
                    callData: data
                },
                () => {
                    setTimeout(() => {
                        this.setData({
                            callData: {}
                        });
                    }, 1000);
                }
            );
        }
    }
};
</script>
<style>
/* @import '../../Entry.css'; */
/* @import '../../diagnostic/addDiagnostic/customDiagnostics/customDiagnostics.css'; */

.slectBox {
    background: #fff;
    margin: 8rpx 16rpx 0;
    border-radius: 12rpx;
    overflow: hidden;
}

.weui-select {
    display: flex;
    align-items: center;
    height: 64rpx;
    line-height: 64rpx;
    padding: 0 24rpx;
    color: #1f2937;
    font-size: 26rpx;
    border-bottom: 0;
}

.diagnosticcontent {
    top: calc(74rpx + 64rpx + 24rpx) !important;
}

.diagnosticcontent.t200 {
    top: calc(74rpx + 64rpx + 24rpx) !important;
}
</style>
