<template>
    <view>
        <!-- pages/prescritionTemplate/prescriptionTemplate.wxml
  处方模板 -->
        <view class="diagnostic-wrapper">
            <view class="all">
                <view class="head">
                    <view class="topHead">
                        <view class="row">
                            <view class="col">
                                <view class="col-4 borBtom">
                                    <view class="medType" @tap.stop.prevent="showOtherTemlateType">
                                        <text>{{ templateType[checkTemplateIndex].desc }}</text>
                                        <van-icon name="arrow-down" />
                                    </view>
                                </view>
                                <view class="col-8 serachBOX">
                                    <view class="serach">
                                        <icon type="search" class="serachIcon" size="20" />
                                        <input @input="selectTemplate" class="serachInfo" placeholder="搜索套餐/模板名称" />
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="other" v-if="showOtherType" v-for="(item, index) in medictionType" :key="index">
                        <view v-if="index != checkMedTypeIndex">
                            <button class="otherType" @tap.stop.prevent="checkMedType" :data-index="index">
                                <text>{{ item.desc }}</text>
                            </button>
                        </view>
                    </view>
                    <view class="other" v-if="showTemplateType" v-for="(item, index) in templateType" :key="index">
                        <view v-if="index != checkTemplateIndex">
                            <button class="otherType" @tap.stop.prevent="checkTempType" :data-index="index">
                                <text>{{ item.desc }}</text>
                            </button>
                        </view>
                    </view>
                </view>
                <view class="MedDody">
                    <view class="row">
                        <view class="col">
                            <view class="col-4" style="height: 100%">
                                <view v-for="(item, index) in medicalRecode" :key="index">
                                    <view @tap.stop.prevent="checkMedRecorde" :data-index="index" :class="medRecodeIndex == index ? 'checkMedArr' : 'medArr'">
                                        {{ item.ordTempletDesc }}
                                    </view>
                                </view>
                            </view>
                            <view class="col-8" v-if="active == 1">
                                <view class="selectall">
                                    <checkbox :checked="checkedAll" @tap="checkall">全选/取消全选</checkbox>
                                </view>
                                <view v-for="(item, index) in medRecodeDateil" :key="index">
                                    <view class="medDateil row">
                                        <view class="col-9">
                                            <text>{{ item.ordTempletDetailItemDesc }}</text>
                                            <text class="useDateil">【{{ item.ordTempletDetailQty }} {{ item.ordTempletDetailQtyUnitDesc }}】</text>
                                            <text class="useDateil">【{{ item.way }}】</text>
                                        </view>
                                        <view class="col-3" style="float: right;margin-top: -40rpx;margin-right: 10rpx;`">
                                            <checkbox :checked="item.checkStatus" color="dodgerblue" @tap.stop.prevent="checkSaveMed" :data-index="index"></checkbox>
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <view v-if="active == 0" class="col-8">
                                <view class="selectall">
                                    <checkbox :checked="checkedAll" @tap="checkall">全选/取消全选</checkbox>
                                </view>
                                <view v-for="(item, index) in medRecodeDateil" :key="index">
                                    <view class="medDateil row">
                                        <view class="checkMedDateil col-12">
                                            <view class="medName p30">
                                                {{ item.ordTempletDetailItemDesc }}
                                                <checkbox
                                                    color="dodgerblue"
                                                    @tap.stop.prevent="checkSaveMed"
                                                    :data-index="index"
                                                    :checked="item.checkStatus"
                                                    class="checkButton"
                                                ></checkbox>
                                            </view>
                                            <view class="meDose colnone">
                                                <text class="colnone">规格：</text>
                                                {{ item.spec }}
                                            </view>
                                        </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/prescritionTemplate/prescriptionTemplate.js../../config/https.js../../config/https.js
import { $http } from '../../../../../../../config/https';
export default {
    components: {},
    data() {
        return {
            medictionType: [
                {
                    id: 1,
                    desc: '西药及其他'
                },
                {
                    id: 2,
                    desc: '草药'
                }
            ],

            checkMedTypeIndex: 0,
            showOtherType: false,

            templateType: [
                {
                    id: 1,
                    desc: '个人模板'
                },
                {
                    id: 2,
                    desc: '科室模板'
                }
            ],

            checkTemplateIndex: 0,
            showTemplateType: false,
            search: '',
            medicalRecode: [],
            medRecodeIndex: 0,
            westMedRecode: [],
            medRecode: [],
            westMedRecodeIndex: 0,
            selectMedFlag: 'west',
            medRecodeDateil: [],
            selectInfo: '',
            saveArr: [],
            detailInfo: [],
            orderData: [],
            errorData: [],
            isLoading: false,
            checkedAll: false,
            recLoc: '',
            desc: ''
        };
    },
    /**
     * 可以使用全局样式
     */
    options: {
        addGlobalClass: true
    },
    props: {
        showRefusal: String,
        myProperty2: String,
        // 简化的定义方式
        addInfo: {
            type: Object,
            //类型
            default: () => ({}) //默认值
        },

        active: {
            type: Number,
            //类型
            default: 0 //默认值
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    moved: function () {},
    destroyed: function () {},
    methods: {
        ready: function () {
            let { recLoc } = this;
            console.log(recLoc);
            this.setData({
                recLoc: recLoc
            });
            this.getDate();
        },

        // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
        attached: function () {},

        selectPatient: function (e) {
            console.log('select---->', e.detail.value);
        },

        // checkMedType: function (e) {
        //   var selectMedFlag = 'west'
        //   var medicalRecode = this.data.westMedRecode
        //   if (e.currentTarget.dataset.index == 1) {
        //     selectMedFlag = "med"
        //     medicalRecode = this.data.medRecode
        //   }
        //   this.setData({
        //     medicalRecode: medicalRecode,
        //     checkMedTypeIndex: e.currentTarget.dataset.index,
        //     showOtherType: false,
        //     selectMedFlag: selectMedFlag
        //   }, () => {
        //     this.getDataDateil()
        //   })
        // },

        showOtherTypeFun: function (e) {
            if (!this.showOtherType) {
                this.setData({
                    showOtherType: true
                });
            } else {
                this.setData({
                    showOtherType: false,
                    saveArr: []
                });
            }
        },

        checkMedRecorde: function (e) {
            this.setData(
                {
                    medRecodeIndex: e.currentTarget.dataset.index,
                    saveArr: []
                },
                () => {
                    this.getDataDateil();
                }
            );
        },

        childFun: function () {
            if (this.active == 0) {
                this.setData(
                    {
                        medicalRecode: this.westMedRecode
                    },
                    () => {
                        this.getDataDateil;
                    }
                );
            } else {
                this.setData(
                    {
                        medicalRecode: this.medRecode
                    },
                    () => {
                        this.getDataDateil;
                    }
                );
            }
        },

        getDate: function (e) {
            let that = this;
            var active = this.active + 1;
            var templateType = this.templateType;
            var checkTemplateIndex = this.checkTemplateIndex;
            let data = {
                params: [
                    {
                        templetTypeID: templateType[checkTemplateIndex].id,
                        status: 'Y',
                        input: this.selectInfo
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03050011',
                data: data,
                success: function (res) {
                    console.log(res);
                    if (res.errorCode == '0') {
                        if (res.result) {
                            var medRecode = [];
                            var westMedRecode = [];
                            for (var i = 0; i < res.result.length; i++) {
                                if (res.result[i].templetCatID == 1) {
                                    westMedRecode = res.result[i].data;
                                }
                                if (res.result[i].templetCatID == 2) {
                                    medRecode = res.result[i].data;
                                }
                            }
                        }
                        this.setData(
                            {
                                medicalRecode: this.active == 0 ? westMedRecode : medRecode,
                                medRecode: medRecode,
                                westMedRecode: westMedRecode
                            },
                            () => {
                                this.getDataDateil();
                            }
                        );
                    }
                }
            });
        },

        checkTempType: function (e) {
            this.setData(
                {
                    checkTemplateIndex: e.currentTarget.dataset.index,
                    showTemplateType: false,
                    saveArr: [],
                    checkedAll: false
                },
                () => {
                    this.getDate();
                }
            );
        },

        selectTemplate: function (e) {
            this.setData(
                {
                    selectInfo: e.detail.value
                },
                () => {
                    this.getDate();
                }
            );
        },

        getDataDateil: function (e) {
            let that = this;
            if (this.medicalRecode != undefined && this.medicalRecode.length > 0) {
                let data = {
                    params: [
                        {
                            ordTempletID: this.medicalRecode[this.medRecodeIndex].ordTempletID
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '03050014',
                    data: data,
                    success: function (res) {
                        console.log(res);
                        if (res.errorCode == '0') {
                            this.setData({
                                medRecodeDateil: res.result
                            });
                        }
                    }
                });
            } else {
                this.setData({
                    medRecodeDateil: []
                });
            }
        },

        showOtherTemlateType: function (e) {
            if (!this.showTemplateType) {
                this.setData({
                    showTemplateType: true
                });
            } else {
                this.setData({
                    showTemplateType: false
                });
            }
        },

        checkSaveMed: function (e) {
            var index = e.currentTarget.dataset.index;
            var checkStatus = this.medRecodeDateil[index].checkStatus;
            var medRecodeDateil = this.medRecodeDateil;
            if (checkStatus) {
                medRecodeDateil[index].checkStatus = false;
            } else {
                medRecodeDateil[index].checkStatus = true;
            }
            this.setData({
                medRecodeDateil: medRecodeDateil
            });
        },

        savePres: function (e) {
            this.setData({
                isLoading: true
            });
            const { medRecodeDateil } = this;
            var patientData = Cache.get('patientData');
            var userData = Cache.get('userData');
            this.setData({
                orderData: []
            });
            let that = this;
            var index = 0;
            medRecodeDateil.map((item) => {
                if (item.checkStatus) {
                    if (this.active == 0) {
                        // this.selectMedDateil(item.medID, index)
                        var arr = [];
                        if (item.medID) {
                            arr.push({
                                medID: item.medID
                            });
                        } else {
                            arr.push({
                                ordSetID: item.ordSetID
                            });
                        }
                        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') {
                                    if (res.errorData.length != 0) {
                                        let contentStr = '';
                                        for (var len = 0; len < res.errorData.length; len++) {
                                            contentStr = contentStr + res.errorData[len].ordDesc + ':' + res.errorData[len].errorMessage + '\n';
                                        }
                                        uni.showModal({
                                            title: '提示',
                                            content: contentStr,
                                            confirmText: '确认',
                                            success(result) {
                                                if (result.confirm) {
                                                    that.setData(
                                                        {
                                                            detailInfo: res.data,
                                                            errorData: res.errorData
                                                        },
                                                        () => {
                                                            index = index + 1;
                                                            let invalid = Object.keys(res.data[0].defaultData).length > 0 ? '' : item.title;
                                                            that.pushMedDateil(item.medID, index, invalid, res.data);
                                                        }
                                                    );
                                                }
                                            }
                                        });
                                    } else {
                                        this.setData(
                                            {
                                                detailInfo: res.data,
                                                errorData: res.errorData
                                            },
                                            () => {
                                                index = index + 1;
                                                let invalid = Object.keys(res.data[0].defaultData).length > 0 ? '' : item.title;
                                                this.pushMedDateil(item.medID, index, invalid, res.data);
                                            }
                                        );
                                    }
                                }
                            },
                            fail: function (error) {
                                this.setData({
                                    isLoading: false
                                });
                            }
                        });
                    } else {
                        //this.selectMedicalDateil(item.medID, index)
                        var addInfo = this.addInfo;
                        let data = {
                            params: [
                                {
                                    admID: patientData.admID,
                                    groupID: userData.groupID,
                                    recLocID: addInfo.recLoc ? addInfo.recLoc.id : '',
                                    userID: userData.userID,
                                    locID: userData.locID,
                                    hospID: userData.hospID,
                                    orders: [
                                        {
                                            ordTempletDetailID: item.ordTempletDetailID
                                        }
                                    ]
                                }
                            ]
                        };
                        $http.post('urlDeault', this, {
                            code: '03050076',
                            data: data,
                            success: function (res) {
                                this.setData({
                                    isLoading: false
                                });
                                if (res.errorCode == '0') {
                                    console.log(res.data);
                                    this.setData(
                                        {
                                            detailInfo: res.data
                                        },
                                        () => {
                                            index = index + 1;
                                            this.pushMedDateil(item.medID, index, '', res.data);
                                        }
                                    );
                                }
                            },
                            fail: function (error) {
                                this.setData({
                                    isLoading: false
                                });
                            }
                        });
                    }
                } else {
                    this.setData({
                        isLoading: false
                    });
                }
            });
        },

        pushMedDateil: function (medID, index, invalid = '', detailInfo) {
            var active = this.active;
            let errorData = this.errorData;
            var orderData = this.orderData;
            var medRecodeDateil = this.medRecodeDateil;
            var valueindex = 0;
            medRecodeDateil.map((item) => {
                if (item.checkStatus) {
                    valueindex = valueindex + 1;
                }
            });
            if (active == 0) {
                if (medID) {
                    detailInfo[0].defaultData.medID = medID;
                    detailInfo[0].defaultData.otherFlag = 1;
                    if (invalid) {
                        detailInfo[0].defaultData.invalid = invalid;
                    }
                    // detailInfo[0].defaultData.ordFreqID = detailInfo[0].defaultData.ordFreqID?detailInfo[0].defaultData.ordFreqID:(addInfo.selectIndex2?addInfo.selectIndex2.id:"")
                    // detailInfo[0].defaultData.ordUsageID = detailInfo[0].defaultData.ordUsageID?detailInfo[0].defaultData.ordUsageID:(addInfo.selectIndex3?addInfo.selectIndex3.id:"")
                    orderData.push(detailInfo[0].defaultData);
                } else {
                    detailInfo.map((item) => {
                        item.defaultData.otherFlag = 1;
                        errorData.map((item1) => {
                            if (item1.indexId == item.indexId) {
                                item.defaultData.invalid = item1.ordDesc;
                            }
                        });
                        orderData.push(item.defaultData);
                    });
                    // console.log(detailInfo)
                }
                // detailInfo[0].defaultData.medID = medID
                // detailInfo[0].defaultData.otherFlag = 1
                // detailInfo[0].defaultData.ordFreqID = detailInfo[0].defaultData.ordFreqID?detailInfo[0].defaultData.ordFreqID:(addInfo.selectIndex2?addInfo.selectIndex2.id:"")
                // detailInfo[0].defaultData.ordUsageID = detailInfo[0].defaultData.ordUsageID?detailInfo[0].defaultData.ordUsageID:(addInfo.selectIndex3?addInfo.selectIndex3.id:"")
                // orderData.push(detailInfo[0].defaultData)
            } else {
                detailInfo.map((item) => {
                    // detailInfo.medID = medID
                    item.otherFlag = 1;
                    item.herbalFormID = item.herbalFormID ? item.herbalFormID : this.addInfo.herbalForm ? this.addInfo.herbalForm.id : '';
                    orderData.push(item);
                });
            }
            if (index == valueindex) {
                var orderObj = {};
                var active = this.active;
                orderObj.data = orderData;
                let pages = getCurrentPages();
                //上一个页面实例对象
                let prevPage = pages[pages.length - 2];
                //关键在这里
                if (active == 0) {
                    prevPage.callData(orderData);
                    uni.navigateBack({
                        delta: 1
                    });
                } else {
                    prevPage.callData2(orderData);
                    orderObj.select = 0;
                    this.$emit('changeSelect', {
                        detail: orderObj
                    });
                }
            }
        },

        selectMedDateil: function (medID, index) {},
        selectMedicalDateil: function (medID, index) {},

        /**全选
         *
         */
        checkall: function () {
            let data = this.medRecodeDateil;
            let { checkedAll } = this;
            for (var len = 0; len < data.length; len++) {
                data[len].checkStatus = !checkedAll;
            }
            this.setData({
                medRecodeDateil: data,
                checkedAll: !checkedAll
            });
        },

        checkMedType() {
            console.log('占位：函数 checkMedType 未声明');
        }
    },
    created: function () {}
};
</script>
<style>
/* @import '../../../Entry.css'; */

.medType {
    text-align: center;
    padding-top: 20rpx;
    float: left;
    width: 220rpx !important;
    font-size: 32rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: rgba(102, 102, 102, 1);
}

page {
    background-color: white;
    height: 100%;
}

.all {
    width: 100%;
    height: 100%;
}

.medType1 {
    font-size: 28rpx;
    color: dodgerblue;
}

.row {
    width: 100%;
}

.col {
    height: 100%;
}

.col-4 {
    width: 33.3333333%;
    background-color: white;
    float: left;
    border-right: 2rpx solid #eee;
    margin-left: -2rpx;
    overflow: hidden;
}

.col-8 {
    width: 66.66666666%;
    height: 100%;
    overflow: hidden;
}

.head {
    float: none;
    background-color: white;
}

.arrow {
    margin-left: 16rpx;
    font-size: 20rpx;
    padding-bottom: 16rpx;
}

.other {
    z-index: 99;
    position: fixed;
    background: white;
}

.otherType {
    border-radius: 5px;
    float: left;
    font-size: 24rpx;
    font-weight: 400;
    width: 180rpx !important;
    margin-bottom: 5rpx;
    text-align: center;
}

.medDateil {
    background: white;
    padding-top: 12rpx;
    padding-bottom: 12rpx;
    font-size: 28rpx;
    padding-left: 10rpx;
    margin-bottom: 10rpx;
    float: left;
    border-bottom: 2rpx solid #eee;
}

.useDateil {
    margin-left: 15rpx;
    color: #999;
}

.westUseDateil {
    margin-left: 15rpx;
    color: #999;
    width: 60%;
}

.MedDody {
    height: calc(100% - 120rpx);
    background: white;
}

.serach {
    background-color: #eee;
    color: #999;
    font-size: 28rpx;
    width: 60%;
    height: 60rpx;
    padding-top: 20rpx;
    float: left;
    border-radius: 5px;
    margin-top: 10rpx;
    padding-left: 5px;
    width: 100%;
}

.topHead {
    height: 100rpx;
    overflow: hidden;
}

.serachIcon {
    float: left;
    width: 40rpx;
}

.serachInfo {
    font-size: 32rpx;
}

.row {
    height: 100%;
}

.medArr {
    display: block;
    font-size: 28rpx;
    width: 98%;
    margin-left: 10rpx;
    margin-bottom: 12rpx;
    /* height: 100rpx; */
    font-weight: 400;
    padding: 20rpx 10rpx;
}

.checkMedArr {
    display: block;
    font-size: 28rpx;
    width: 98%;
    margin-left: 10rpx;
    margin-bottom: 12rpx;
    /* height: 100rpx; */
    font-weight: 400;
    color: dodgerblue;
    padding-left: 10px;
    border-left: 2px solid dodgerblue;
    padding: 20rpx 10rpx;
}

.col-8 {
    height: 100%;
    overflow-y: auto;
}

.saveButton {
    align-items: center;
    border-radius: 40rpx;
    background-color: dodgerblue;
    color: white;
    font-size: 28rpx;
    margin-top: 20rpx;
    font-weight: 400;
}

.checkButton {
    float: right;
    margin-right: 10rpx;
}

.borBtom {
    border-bottom: 2rpx solid #eee;
    padding-bottom: 30rpx;
}

.serachBOX {
    padding: 0 20rpx;
    box-sizing: border-box;
}

.medName {
    padding: 10rpx;
    border-bottom: 2rpx solid #f1f1f1;
    font-size: 30rpx;
}

.meDose {
    padding: 10rpx;
    font-size: 30rpx;
    color: #1890ff;
}

.colnone {
    font-size: 25rpx;
    color: #969799;
}

.p30 {
    padding: 30rpx 10rpx;
}

.selectall {
    font-size: 34rpx;
    background: #ffffff;
    border-bottom: 1rpx solid #f5f4f4;
    color: #1890ff;
}
</style>
