<template>
    <view>
        <!-- pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/grass/grassPush/grassPush.wxml -->
        <nav-bar :navbarData="navbarData"></nav-bar>
        <view class="diagnosticEntry" :style="'margin-top: ' + (height * 2 + 10) + 'rpx; height: calc(100vh - ' + (height * 2 + 10) + 'rpx)'">
            <view class="boxTitle fontS30 topTitle">
                <text class="floatR addToList" @tap="addChange">{{ addText }}</text>
            </view>
            <mp-cells ext-class="my-cells">
                <mp-cell class="fontS30 tapSelect" link hover @tap.native="tapSelect">
                    <view class="required">
                        草药名称
                        <view class="redIcon" v-if="!(verification === 'N' || (searchSelect.medDesc && searchSelect.medDesc !== ''))">
                            <van-icon name="warning" color="red" />
                        </view>
                    </view>
                    <view slot="footer">
                        {{ searchSelect.medDesc || '请选择' }}
                    </view>
                </mp-cell>
                <mp-cell class="fontS30" hover>
                    <view class="required">
                        单次剂量
                        <view class="redIcon" v-if="!(verification === 'N' || (jl && jl !== ''))">
                            <van-icon name="warning" color="red" />
                        </view>
                    </view>
                    <view slot="footer">
                        <view class="weui-input">
                            <input :focus="doseFocus" class="weui-input" placeholder="请输入单次剂量" :value="jl" @input="bindnoteChange" type="digit" />
                        </view>
                    </view>
                </mp-cell>
                <picker @change="bindPickerChange2" :value="typeList1" :range="typeList" range-key="unitDesc">
                    <mp-cell class="fontS30" link hover>
                        <view class="required">
                            剂量单位
                            <view
                                class="redIcon"
                                v-if="!(verification === 'N' || (typeList[typeList1].unitDesc && typeList[typeList1].unitDesc !== '' && typeList[typeList1].unitDesc !== '请选择'))"
                            >
                                <van-icon name="warning" color="red" />
                            </view>
                        </view>
                        <view slot="footer">
                            <view class="picker">{{ typeList[typeList1].unitDesc || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange1" :value="comPrinciple1" :range="comPrinciple" range-key="descripts">
                    <mp-cell class="fontS30" link hover>
                        <view>用药类型</view>
                        <view slot="footer">
                            <view class="picker">{{ comPrinciple[comPrinciple1].descripts || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
                <picker @change="bindPickerChange3" :value="decoctMethod1" :range="decoctMethod" range-key="descripts">
                    <mp-cell class="fontS30" link hover>
                        <view>备注</view>
                        <view slot="footer">
                            <view class="picker">{{ decoctMethod[decoctMethod1].descripts || '请选择' }}</view>
                        </view>
                    </mp-cell>
                </picker>
            </mp-cells>
            <view class="box medList" v-if="selectIndex === ''">
                <view class="boxTitle fontS30 borderB2">
                    <text>已添加草药</text>
                </view>
                <view class="medData" v-for="(item, index) in gList" :key="index">
                    <view class="medDesc">
                        <view>
                            <text>{{ item.searchSelect.medDesc }}</text>
                        </view>
                    </view>

                    <view>
                        <text class="detailInfo">剂量：{{ item.jl }} {{ item.typeList.unitDesc }}</text>
                        <text class="detailInfo">用药类型：{{ item.comPrinciple.descripts }}</text>
                        <text class="detailInfo">备注：{{ item.decoctMethod.descripts }}</text>
                    </view>

                    <view class="boxBtm">
                        <button class="remove" @tap="tapRemove" :data-index="index">删除</button>
                        <button class="edit" @tap="tapEdit" :data-index="index">编辑</button>
                    </view>
                </view>
                <view class="textCenter empty" v-if="gList.length <= 0">暂无添加草药</view>
            </view>
            <view class="col textCenter bottombtn" v-if="selectIndex === ''">
                <button class="saveTo" @tap="addbtn" :disabled="isLoading">{{ isLoading ? '保存中' : '保存' }}</button>
            </view>
        </view>
        <van-dialog id="van-dialog" />
        <van-toast id="van-toast" />
    </view>
</template>

<script>
import Cache from '../../../../../../../../../utils/cache';
import navBar from '@/pages/components/navbar/index';
// pages/entryWrite/page/Entry/prescription/addPrescription/customDiagnostics/grass/grassPush/grassPush.js
import { $http } from '../../../../../../../../../config/https';
import Toast from '../../../../../../../../../utils/toast';
import Dialog from '../../../../../../../../../utils/dialog';
import util from '../../../../../../../../../utils/util';
const app = getApp();
export default {
    components: {
        navBar
    },
    data() {
        return {
            medID: '',

            //   医嘱项id
            recLocID: '',

            //   执行科室id
            herbalFormID: '',

            //   剂型
            searchSelect: {
                medDesc: ''
            },

            //   选中的医嘱名称
            decoctMethod1: '',

            //备注
            decoctMethod: [],

            //备注
            comPrinciple1: '',

            //用药类型
            comPrinciple: [],

            //用药类型
            typeList1: '',

            //剂量单位
            typeList: [],

            //剂量单位
            jl: '',

            // 单次剂量
            gList: [],

            // 已添加草药
            selectIndex: '',

            // 当前编辑
            doseFocus: false,

            verification: 'N',

            // 验证
            editVis: 'N',

            // 编辑标识
            navbarData: {
                isGoBack: true,
                background: '',
                title: '添加草药',
                //导航栏 中间的标题
                bottom: false
            },

            height: app.globalData.height,
            addText: '添加到列表',
            isLoading: false,
            unitDesc: '',
            descripts: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 接收gList
        this.optionsUrl(options);
        this.searchSelectFun(); //获取选中的select数据
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // 清除Storage
        // wx.removeStorageSync('searchSelect');
        this.selectData2(); // 其他下拉加载数据
        this.selectData3(); // 其他下拉加载数据
        console.log('onReady');
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 获取选中的select数据
        searchSelectFun: function (selectData) {
            console.log(selectData);
            let searchSelect = selectData;
            if (searchSelect) {
                this.setData(
                    {
                        searchSelect,
                        medID: searchSelect.medID,
                        doseFocus: true
                    },
                    () => {
                        this.selectData2(); // 其他下拉加载数据
                        this.selectData3(); // 其他下拉加载数据
                    }
                );
            }
        },

        // 医嘱名称跳转select
        tapSelect: function (e) {
            let { herbalFormID } = this;
            uni.navigateTo({
                //目的页面地址
                url: '/pages/components/searchSelect/searchSelect?code=03050019&type=Y&herbalFormID=' + herbalFormID,
                success: function (res) {}
            });
        },

        // 其他下拉加载数据
        selectData2: function (e) {
            let userData = Cache.get('userData');
            let { hospID } = userData;
            $http.post('urlDeault', this, {
                code: '03100066',
                data: {
                    params: [
                        {
                            hospID: hospID || '',
                            //登录医院id
                            admType: 'O',
                            //就诊类型
                            comPrincipleFlag: '1',
                            //配伍原则
                            herbalFormFlag: '1',
                            //剂型
                            frequenceFlag: '1',
                            //频次
                            usageFlag: '1',
                            //用法
                            durationFlag: '1',
                            //疗程单位
                            usageExplainFlag: '1',
                            //服用要求
                            authRangeFlag: '1',
                            //使用级别
                            decoctMethodFlag: '1',
                            //备注
                            cookTypeFlag: '1' //
                        }
                    ]
                },

                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        this.setData(
                            {
                                decoctMethod: res.result.decoctMethod || [],
                                //备注
                                comPrinciple: res.result.comPrinciple || [] //配伍规则
                                // 默认值
                                // jl: res.result.defaultDoseQty || '', // 单次剂量
                            },
                            () => {
                                let { decoctMethod, comPrinciple } = this;
                                decoctMethod.unshift({
                                    descripts: '请选择'
                                });
                                comPrinciple.unshift({
                                    descripts: '请选择'
                                });
                                this.setData({
                                    decoctMethod,
                                    comPrinciple
                                });
                            }
                        );
                    }
                }
            });
        },

        // 获取医嘱项信息(草药)
        selectData3: function (e) {
            let userData = Cache.get('userData');
            let patientData = Cache.get('patientData');
            let { hospID, locID, userID, groupID } = userData;
            let { admID } = patientData;
            let { medID, recLocID } = this;
            $http.post('urlDeault', this, {
                code: '03050076',
                data: {
                    params: [
                        {
                            recLocID: recLocID || '',
                            groupID: groupID || '',
                            userID: userID || '',
                            locID: locID || '',
                            admID: admID || '',
                            hospID: hospID || '',
                            orders: [
                                {
                                    medID: medID || '',
                                    ordSetID: ''
                                }
                            ]
                        }
                    ]
                },
                success: function (res) {
                    let errorCode = res.errorCode;
                    let errorList = res.errorList[0];
                    let { typeList1, selectIndex, gList, comPrinciple1, comPrinciple, decoctMethod, decoctMethod1, searchSelectFun: searchSelect, jl } = this;
                    if (errorCode === '0') {
                        if (errorList) {
                            if (errorList.errorMessage.indexOf('诊断') > -1) {
                                Dialog.confirm({
                                    title: '提示',
                                    confirmButtonText: '录入诊断',
                                    message: errorList.errorMessage
                                })
                                    .then(() => {
                                        // 历史诊疗
                                        uni.navigateTo({
                                            //目的页面地址
                                            url: '/pages/entryWrite/page/Entry/Entry?select=1&addText=添加诊断' // 历史诊疗,
                                        });
                                    })
                                    .catch(() => {
                                        // on cancel
                                    });
                            } else {
                                Dialog.alert({
                                    title: '提示',
                                    message: errorList.errorMessage,
                                    context: this
                                });
                            }
                            this.setData({
                                searchSelect: {} //   选中的医嘱名称
                            });

                            return false;
                        }
                        if (res.data[0]) {
                            typeList1 =
                                selectIndex !== ''
                                    ? this.picakIndex('unitID', gList[selectIndex].typeList.unitID, res.data[0].qtyUnitList)
                                    : this.picakIndex('unitID', res.data[0].ordDoseUnitID, res.data[0].qtyUnitList);
                            // comPrinciple1 = selectIndex !== '' ? this.picakIndex('id', gList[selectIndex].comPrinciple.id, comPrinciple) : this.picakIndex('id', res.data[0].comPrincipleID, comPrinciple)
                            decoctMethod1 = selectIndex !== '' ? this.picakIndex('id', gList[selectIndex].decoctMethod.id, decoctMethod) : '';
                            searchSelect = selectIndex !== '' ? gList[selectIndex].searchSelect : searchSelect;
                            jl = selectIndex !== '' ? gList[selectIndex].jl : jl;
                            this.setData({
                                typeList: (res.data[0] && res.data[0].qtyUnitList) || [],
                                //剂量单位
                                typeList1,
                                // comPrinciple1,
                                decoctMethod1,
                                searchSelect,
                                jl
                            });
                        }
                    }
                }
            });
        },

        // 剂量单位
        bindPickerChange1: function (e) {
            this.setData({
                comPrinciple1: e.detail.value
            });
        },

        // 用药类型
        bindPickerChange2: function (e) {
            this.setData({
                typeList1: e.detail.value
            });
        },

        // 备注
        bindPickerChange3: function (e) {
            this.setData({
                decoctMethod1: e.detail.value
            });
        },

        // 单次剂量
        bindnoteChange: function (e) {
            this.setData({
                jl: e.detail.value
            });
        },

        // 添加列表
        addChange: function (e) {
            let { gList, searchSelectFun: searchSelect, decoctMethod1, decoctMethod, comPrinciple1, comPrinciple, typeList, typeList1, jl, selectIndex } = this;
            let requireData = [
                {
                    message: '请先选择草药',
                    value: searchSelect
                },
                {
                    message: '剂量不能为空',
                    value: jl
                },
                {
                    message: '剂量单位不能为空',
                    value: typeList[typeList1] && typeList[typeList1].unitDesc === '请选择' ? {} : typeList[typeList1]
                }
            ];
            util.formRequire(requireData, (data) => {
                if (data && data.length > 0) {
                    this.setData({
                        verification: 'Y'
                    });
                    Toast({
                        type: 'fail',
                        message: data[0].message,
                        context: this
                    });
                } else {
                    if (selectIndex === '') {
                        var fitArr = gList.filter((item, i) => {
                            return item.searchSelect.medID === searchSelect.medID;
                        });
                        if (fitArr.length > 0) {
                            Toast({
                                type: 'fail',
                                message: '已添加该草药',
                                context: this
                            });
                            return;
                        }
                        console.log(decoctMethod[decoctMethod1]);
                        gList.unshift({
                            searchSelect: searchSelect,
                            decoctMethod: decoctMethod[decoctMethod1] && decoctMethod[decoctMethod1].descripts !== '请选择' ? decoctMethod[decoctMethod1] : {},
                            //备注
                            comPrinciple: comPrinciple[comPrinciple1] && comPrinciple[comPrinciple1].descripts !== '请选择' ? comPrinciple[comPrinciple1] : {},
                            //用药类型
                            typeList: typeList[typeList1] && typeList[typeList1].unitDesc !== '请选择' ? typeList[typeList1] : {},
                            //剂量单位
                            jl: jl || '' // 单次剂量
                        });
                    } else {
                        gList[selectIndex].searchSelect = searchSelect;
                        gList[selectIndex].decoctMethod = decoctMethod[decoctMethod1] && decoctMethod[decoctMethod1].descripts !== '请选择' ? decoctMethod[decoctMethod1] : {}; //备注
                        gList[selectIndex].comPrinciple = comPrinciple[comPrinciple1] && comPrinciple[comPrinciple1].descripts !== '请选择' ? comPrinciple[comPrinciple1] : {};
                        gList[selectIndex].typeList = typeList[typeList1] && typeList[typeList1].unitDesc !== '请选择' ? typeList[typeList1] : {};
                        gList[selectIndex].jl = jl;
                    }
                    let { navbarData } = this;
                    navbarData.title = '保存草药';
                    this.setData(
                        {
                            navbarData,
                            addText: '添加到列表',
                            gList,
                            selectIndex: '',
                            medID: '',
                            //   医嘱项id
                            searchSelect: {},
                            //   选中的医嘱名称
                            decoctMethod1: '',
                            //备注
                            comPrinciple1: '',
                            //用药类型
                            typeList1: '',
                            //剂量单位
                            typeList: [],
                            //剂量单位
                            jl: '' // 单次剂量
                        },
                        () => {
                            let { editVis } = this;
                            if (editVis === 'Y') {
                                this.addbtn(); // 保存
                            }
                        }
                    );
                }
            });
        },

        // 点击删除
        tapRemove: function (event) {
            let { currentTarget } = event;
            let { gList } = this;
            let dataset = currentTarget.dataset;
            gList.splice(dataset.index, 1);
            this.setData({
                gList: gList || [] // 已添加草药
            });
        },

        // 保存
        addbtn: function (event) {
            this.setData({
                isLoading: true
            });
            let { gList } = this;
            if (gList.length == 0) {
                this.setData({
                    isLoading: false
                });
                Toast({
                    type: 'fail',
                    message: '未添加草药',
                    context: this
                });
                return false;
            }
            this.setData({
                medID: '',
                //   医嘱项id
                recLocID: '',
                //   执行科室id
                searchSelect: {},
                //   选中的医嘱名称
                decoctMethod1: '',
                //备注
                comPrinciple1: '',
                //用药类型
                typeList1: '',
                //剂量单位
                typeList: [],
                //剂量单位
                jl: '' // 单次剂量
            });

            let pages = getCurrentPages();
            //上一个页面实例对象
            let prevPage = pages[pages.length - 2];
            //关键在这里
            prevPage.callData(gList);
            this.setData({
                isLoading: false
            });
            uni.navigateBack({
                delta: 1
            });
        },

        // 接收 url传参
        optionsUrl: function (options) {
            let gList = JSON.parse(options.gList); //解析得到对象
            let recLocID = JSON.parse(options.recLocID); //科室ID
            let herbalFormID = JSON.parse(options.herbalFormID); //剂型
            let e = JSON.parse(options.e); //编辑
            let { index } = e.currentTarget.dataset;
            console.log(index);
            if (index || index === 0) {
                // 编辑进来

                let { navbarData, addText } = this;
                navbarData.title = '编辑草药';
                this.setData({
                    navbarData,
                    editVis: 'Y',
                    addText: '保存'
                });
            }
            this.setData(
                {
                    gList,
                    recLocID,
                    herbalFormID
                },
                () => {
                    this.tapEdit(e);
                }
            );
        },

        // 获取索引值picker
        picakIndex: function (name, id, arr) {
            let index = '';
            if (!arr) {
                return false;
            }
            arr.map((item, i) => {
                if (item[name] == id) {
                    index = i;
                }
            });
            return index;
        },

        // 编辑
        tapEdit: function (e) {
            let { gList } = this;
            let selectIndex = e.currentTarget.dataset.index;
            console.log(e);
            if (!gList[selectIndex]) {
                return false;
            }
            this.setData(
                {
                    medID: gList[selectIndex].searchSelect.medID,
                    selectIndex
                },
                () => {
                    let { navbarData } = this;
                    navbarData.title = '编辑草药';
                    this.setData({
                        navbarData,
                        addText: '保存'
                    });
                    this.selectData3();
                }
            );
            // console.log(gList[selectIndex])
        }
    }
};
</script>
<style>
/* @import '../../../../../diagnostic/addDiagnostic/customDiagnostics/customDiagnostics.css'; */
/* @import '../../../../../diagnostic/diagnostic.css'; */

page {
    height: 100%;
}

.topTitle {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0;
}

.addtext {
    color: #fff;
    padding: 5rpx 10rpx;
    background: #1890ff;
    border-radius: 8rpx;
}

.addToList {
    color: #fff;
    padding: 0 10rpx;
    background: #1890ff;
    height: 100%;
    line-height: 80rpx;
    min-width: 200rpx;
    text-align: center;
}

.detailInfo {
    padding: 10rpx 16rpx;
    color: #ccc;
}

.medDesc {
    padding: 0;
    margin-right: 20rpx;
    height: 80rpx;
    line-height: 80rpx;
}

.medList {
    height: calc(100% - 80rpx - 456rpx - 100rpx);
    margin: 10rpx 0;
    overflow: auto;
    box-sizing: border-box;
}

.empty {
    height: 300rpx;
    line-height: 300rpx;
}

.medData {
    border-bottom: 1rpx solid #eee;
}

.bottombtn {
    height: 100rpx;
    font-size: 30rpx;
    color: #fff;
    padding: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
}

.saveTo {
    flex: 1;
    align-items: center;
    justify-content: center;
    display: flex;
    background-color: #1890ff;
    color: #fff;
    border-radius: 0 !important;
}

.redIcon {
    display: inline-block;
    vertical-align: middle;
}
</style>
