<template>
    <!-- pages/entryWrite/page/Entry/prescription/addExamine/completeExamine/completeExamine.wxml -->
    <view class="complete-content">
        <view class="complete-wrap">
            <view v-if="listArr.length <= 0" class="nodata-show">
                <view style="text-align: center">
                    <text>当前未选择项目</text>
                    <view class="btn-reset" @tap="resetSelect">重新选择</view>
                    <view class="btn-back" @tap="resetBack">返回医嘱列表</view>
                </view>
            </view>
            <view class="item-content" v-for="(item, aIndex) in listArr" :key="aIndex">
                <view class="item-title">
                    <text class="title-left">{{ item.ordDesc }}</text>
                    <text v-if="handle === 'add'" class="title-right" @tap="onDeleteItem" :data-index="aIndex">删除</text>
                </view>

                <view>
                    <picker @change="bindTemplateChange" :data-index="aIndex" :data-templatelist="item.template" :range="item.template" range-key="descripts">
                        <mp-cell link hover value="检查目的" footer="引用模板"></mp-cell>
                    </picker>
                    <view class="picker-border weui-cell">
                        <view class="weui-cell__bd">
                            <input class="weui-input" placeholder="请输入" :data-index="aIndex" :value="item.templateValue" @input="inputTemplateValue" />
                        </view>
                    </view>

                    <view class="picker-border">
                        <mp-cell link hover @tap.native="tapCheckPart($event, { index: aIndex })" :data-index="aIndex" value="检查部位" footer="请选择"></mp-cell>
                    </view>
                    <van-popup
                        closeable
                        :show="item.basicShow"
                        position="right"
                        custom-style="width: 90%; height: 100%"
                        :data-index="aIndex"
                        @close="hideBasic($event, { index: aIndex })"
                    >
                        <view class="part-flex">
                            <view class="part-a">
                                <view v-for="(partItem, bIndex) in item.partList" :key="bIndex">
                                    <view class="part-aTitle">{{ partItem.descripts }}</view>

                                    <view class="part-child">
                                        <view class="part-aChild" v-for="(partItemChild, cIndex) in partItem.child" :key="cIndex">
                                            <view
                                                :class="'part-margin ' + (partItemChild.checked ? 'child-active' : '')"
                                                :data-aindex="aIndex"
                                                :data-bindex="bIndex"
                                                :data-cindex="cIndex"
                                                :data-checked="partItemChild.checked"
                                                :data-id="partItemChild.id"
                                                @tap="tapPartChild"
                                            >
                                                {{ partItemChild.descripts }}
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </view>
                            <view class="part-b">
                                <view class="part-bbtn" @tap="onReset" :data-index="aIndex">重置</view>
                                <view class="part-bbtn btn-sure" @tap="onPartSure" :data-index="aIndex">
                                    确认
                                    <label v-if="item.partCheckedList.length > 0" style="margin-left: 8rpx">({{ item.partCheckedList.length }}个部位)</label>
                                </view>
                            </view>
                        </view>
                    </van-popup>

                    <view class="picker-border no-part" v-if="item.partCheckedList.length <= 0">暂无部位</view>
                    <view v-else>
                        <view class="picker-border" v-for="(partCheckedItem, bodyIndex) in item.partCheckedList" :key="bodyIndex">
                            <mp-cell :title="partCheckedItem.descripts + ' ' + partCheckedItem.descriptsSelectStr">
                                <view class="btn-flex">
                                    <view class="selectT selectL" @tap="tapCheckBody" :data-index="bodyIndex" :data-aindex="aIndex">选择体位</view>
                                    <view class="selectT" @tap="tapDeleteBody" :data-index="bodyIndex" :data-aindex="aIndex" :data-checkitem="partCheckedItem">删除</view>
                                </view>
                            </mp-cell>

                            <van-popup
                                closeable
                                :show="partCheckedItem.bodyShow"
                                position="bottom"
                                custom-style="height: 40%"
                                :data-index="bodyIndex"
                                :data-aindex="aIndex"
                                @close="hideBody($event, { index: bodyIndex, aindex: aIndex })"
                            >
                                <view class="part-flex">
                                    <view class="part-a">
                                        <view class="part-bTitle">请选择体位（可多选）</view>
                                        <view class="part-child">
                                            <view class="part-bChild" v-for="(positionItem, positionIndex) in partCheckedItem.positionList" :key="positionIndex">
                                                <view
                                                    :class="'part-margin ' + (positionItem.checked ? 'child-active' : '')"
                                                    :data-aindex="aIndex"
                                                    :data-bindex="bodyIndex"
                                                    :data-cindex="positionIndex"
                                                    :data-checked="positionItem.checked"
                                                    :data-id="positionItem.id"
                                                    @tap="tapPositionChild"
                                                >
                                                    {{ positionItem.descripts }}
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                    <view class="part-b">
                                        <view class="part-bbtn btn-sure" @tap="hideBody" :data-index="bodyIndex" :data-aindex="aIndex">确认</view>
                                    </view>
                                </view>
                            </van-popup>
                        </view>
                    </view>

                    <view v-if="!(item.isFold && handle !== 'edit')">
                        <view class="picker-border">
                            <picker @change="bindAdmReasonChange" :data-aindex="aIndex" :range="item.admReasonList" :value="item.admReasonIndex" range-key="descripts">
                                <mp-cell link hover value="*结算类型" :footer="item.admReasonList[item.admReasonIndex].descripts"></mp-cell>
                            </picker>
                        </view>
                        <view class="picker-border">
                            <picker @change="bindrecLocChange" :data-aindex="aIndex" :range="item.recLocList" :value="item.recLocIndex" range-key="recLocDesc">
                                <mp-cell link hover value="*执行科室" :footer="item.recLocList[item.recLocIndex].recLocDesc"></mp-cell>
                            </picker>
                        </view>
                    </view>

                    <view v-if="handle !== 'edit'" class="picker-border fold" :data-fold="item.isFold" :data-aindex="aIndex" @tap="onFold">
                        {{ item.isFold ? '更多 ∨' : '收起 ∧' }}
                    </view>
                </view>
            </view>
        </view>
        <view v-if="listArr.length > 0" class="save-btn" @tap="saveList">保存</view>
    </view>
</template>

<script>
import Cache from '../../../../../../../utils/cache';
// pages/entryWrite/page/Entry/prescription/addExamine/completeExamine/completeExamine.js
import { $http } from '../../../../../../../config/https';
import store from '../store';
import create from '../../../../../../../utils/create';
create(store, {
    /**
     * 页面的初始数据
     */
    data: {
        sequenceList: [],
        listArr: [],
        //组合的所有数据
        handle: 'add',
        //默认状态为添加 用来控制返回
        allListArr: [],
        //用来编辑保存
        allListArrIndex: 0,
        //当前编辑的index
        tempArr: [],
        //用来存储未保存的数据
        motto: null,
        defaultShow: true
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.handle === 'add') {
            let tempArr = JSON.parse(options.jList);
            this.setData({
                tempArr
            });

            // 新增
            let orders = JSON.parse(options.medIds);
            let medIDs = orders.map((data) => {
                return data.medID + '';
            });
            this.getDoctorQuery(orders).then(async () => {
                let template = await this.getCheckTemplate();
                let part = await this.getCheckMainPart(medIDs);
                console.log(this.sequenceList);
                console.log(template);
                console.log(part);
                let newArr = this.sequenceList.map((data, index) => {
                    let partL = [];
                    if (Object.keys(part[data.defaultData.medID]).length > 0) {
                        partL = part[data.defaultData.medID].partList.map((item) => {
                            let { child, ...other } = item;
                            let c = child.map((sub) => {
                                return {
                                    ...sub,
                                    checked: false
                                };
                            });
                            return {
                                ...other,
                                child: c
                            };
                        });
                    }
                    return {
                        ordSeqNo: index,
                        medID: data.defaultData.medID,
                        ordDesc: data.defaultData.ordDesc,
                        partList: partL,
                        //部位
                        positionList: part[data.defaultData.medID].positionList,
                        //体位
                        partCheckedList: [],
                        template: template,
                        //模板
                        templateValue: '',
                        basicShow: false,
                        //显示部位弹框
                        bodyShow: false,
                        //显示体位弹框
                        admReasonList: data.dataList.admReasonList,
                        //结算类型
                        admReasonIndex: 0,
                        //0是自费1是普通医保
                        recLocList: data.dataList.recLocList,
                        //执行科室
                        recLocIndex: 0,
                        //执行科室的下拉index
                        ordersObJ: data.defaultData,
                        //保存医嘱需要
                        isFold: true //是否折叠
                    };
                });

                this.setData({
                    listArr: newArr,
                    handle: 'add'
                });
                console.log('newArr==', newArr);
            });
        } else {
            let listArr = JSON.parse(options.listArr);
            this.setData(
                {
                    allListArr: listArr,
                    allListArrIndex: options.index
                },
                () => {
                    this.setData({
                        listArr: [listArr[options.index]],
                        handle: 'edit'
                    });
                }
            );
        }
    },
    // 1.获取医嘱项信息
    getDoctorQuery: function (orders) {
        return new Promise((resolve, reject) => {
            let patientData = Cache.get('patientData');
            let { admID, admNo } = patientData;
            let data = {
                params: [
                    {
                        admID: admID,
                        orders: orders
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03050020',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setData(
                            {
                                sequenceList: res.data
                            },
                            () => {
                                resolve();
                            }
                        );
                    } else {
                        reject();
                    }
                },
                fail: function (err) {
                    reject();
                }
            });
        });
    },
    // 获取检查目的模板
    getCheckTemplate: function () {
        return new Promise((resolve, reject) => {
            let userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        userID: userData.userID,
                        hospID: userData.hospID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100159',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        resolve(res.result);
                    }
                },
                fail: function (err) {}
            });
        });
    },
    //获取医嘱项主部位信息
    getCheckMainPart: function (medIDs) {
        return new Promise((resolve, reject) => {
            let userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        medID: medIDs,
                        hospID: userData.hospID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100160',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        resolve(res.result);
                    }
                },
                fail: function (err) {}
            });
        });
    },
    // 获取医嘱项部位信息
    getCheckPart: function (medIDs) {
        return new Promise((resolve, reject) => {
            let userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        medID: medIDs,
                        hospID: userData.hospID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100161',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        resolve(res.result);
                    }
                },
                fail: function (err) {}
            });
        });
    },
    // 关闭部位
    hideBasic: function (e) {
        let { index } = e.currentTarget.dataset;
        this.listArr[index].basicShow = false;
        this.setData({
            listArr: this.listArr
        });
    },
    hideBody: function (e) {
        let { index, aindex } = e.currentTarget.dataset;
        this.listArr[aindex].partCheckedList[index].bodyShow = false;
        this.setData({
            listArr: this.listArr
        });
    },
    // 检查部位
    tapCheckPart: function (e) {
        let { index } = e.currentTarget.dataset;
        this.listArr[index].basicShow = true;
        this.setData({
            listArr: this.listArr
        });
    },
    // 选择体位
    tapCheckBody: function (e) {
        let { index, aindex } = e.currentTarget.dataset;
        this.listArr[aindex].partCheckedList[index].bodyShow = true;
        this.setData({
            listArr: this.listArr
        });
    },
    tapDeleteBody: function (e) {
        let { index, aindex, checkitem } = e.currentTarget.dataset;
        let editIndex = this.listArr[aindex].partList.findIndex((item) => checkitem.areaID === item.id);
        let partIndex = this.listArr[aindex].partList[editIndex].child.findIndex((item) => checkitem.id === item.id);
        this.listArr[aindex].partList[editIndex].child[partIndex].checked = false;
        this.listArr[aindex].partCheckedList.splice(index, 1); //删除体位
        this.setData({
            listArr: this.listArr
        });
    },
    bindTemplateChange: function (e) {
        let { templatelist, index } = e.currentTarget.dataset;
        this.listArr[index].templateValue = templatelist[e.detail.value].descripts;
        this.setData({
            listArr: this.listArr
        });
    },
    inputTemplateValue: function (e) {
        let { index } = e.currentTarget.dataset;
        this.listArr[index].templateValue = e.detail.value;
        this.setData({
            listArr: this.listArr
        });
    },
    // 点击各个部位
    tapPartChild: function (e) {
        console.log(this.listArr, '点击child', e);
        let { aindex, bindex, cindex, checked, id } = e.currentTarget.dataset;
        this.listArr[aindex].partList[bindex].child[cindex].checked = !checked;
        if (!checked) {
            //  添加体位

            this.listArr[aindex].partCheckedList.push(
                Object.assign(
                    {
                        bodyShow: false,
                        positionList: this.listArr[aindex].positionList.map((item) => {
                            return {
                                checked: false,
                                ...item
                            };
                        })
                    },
                    this.listArr[aindex].partList[bindex].child[cindex]
                )
            );
        } else {
            let arr = this.listArr[aindex].partCheckedList;
            arr.splice(
                arr.findIndex((item) => item.id === id),
                1
            );
        }
        this.setData({
            listArr: this.listArr
        });
    },
    // 点击各个体位
    tapPositionChild: function (e) {
        let { aindex, bindex, cindex, checked, id } = e.currentTarget.dataset;
        this.listArr[aindex].partCheckedList[bindex].positionList[cindex].checked = !checked;
        if (!checked) {
            let newStr = this.listArr[aindex].partCheckedList[bindex].positionList
                .filter((item) => {
                    return item.checked === true;
                })
                .map((item) => {
                    return item.descripts;
                })
                .join(', ');
            this.listArr[aindex].partCheckedList[bindex].descriptsSelectStr = '(' + newStr + ')';
        } else {
            let newArr = this.listArr[aindex].partCheckedList[bindex].positionList
                .filter((item) => {
                    return item.checked === true;
                })
                .map((item) => {
                    return item.descripts;
                });
            let newStr = newArr.join(',');
            if (newArr.length > 0) {
                this.listArr[aindex].partCheckedList[bindex].descriptsSelectStr = '(' + newStr + ')';
            } else {
                this.listArr[aindex].partCheckedList[bindex].descriptsSelectStr = '';
            }
        }
        this.setData({
            listArr: this.listArr
        });
    },
    onReset: function (e) {
        let { index } = e.currentTarget.dataset;
        let arr = this.listArr[index].partList;
        arr.forEach((aitem, i) => {
            aitem.child.forEach((bitem, y) => {
                this.listArr[index].partList[i].child[y].checked = false;
            });
        });
        this.listArr[index].partCheckedList = [];
        this.setData({
            listArr: this.listArr
        });
    },
    onPartSure: function (e) {
        console.log('this.data.listArr==', this.listArr);
        let { index } = e.currentTarget.dataset;
        this.listArr[index].basicShow = false;
        this.setData({
            listArr: this.listArr
        });
    },
    saveList: function () {
        let patientData = Cache.get('patientData');
        let userData = Cache.get('userData');
        let { userID, locID, hospID, userName } = userData;
        let { admID, admNo } = patientData;
        let paramsArr = [];
        if (this.handle === 'add') {
            paramsArr = this.tempArr.concat(this.listArr);
        } else {
            //编辑对应的检查
            console.log(this.allListArr, this.allListArrIndex, this.listArr);
            this.allListArr[this.allListArrIndex] = this.listArr[0];
            paramsArr = this.allListArr;
        }
        let data = {
            params: [
                {
                    medType: 'JC',
                    admID: admID || '',
                    hospID: hospID,
                    userID: userID,
                    locID: locID || '',
                    //开单科室
                    docID: userID,
                    paramsArr: paramsArr
                }
            ]
        };
        console.log('data=', data);
        $http.post('urlDeault', this, {
            code: '03050176',
            data: data,
            success: function (res) {
                if (res.errorCode == '0') {
                    uni.navigateBack({
                        delta: this.handle === 'add' ? 2 : 1
                    });
                }
            },
            fail: function (err) {}
        });
    },
    bindAdmReasonChange: function (e) {
        console.log('e==', e);
        let { aindex } = e.currentTarget.dataset;
        this.listArr[aindex].admReasonIndex = e.detail.value;
        this.setData({
            listArr: this.listArr
        });
    },
    bindrecLocChange: function (e) {
        console.log('e==', e);
        let { aindex } = e.currentTarget.dataset;
        this.listArr[aindex].recLocIndex = e.detail.value;
        this.setData({
            listArr: this.listArr
        });
    },
    onFold: function (e) {
        let { aindex, fold } = e.currentTarget.dataset;
        this.listArr[aindex].isFold = !fold;
        this.setData({
            listArr: this.listArr
        });
    },
    // 删除列表项
    onDeleteItem: function (e) {
        let { index } = e.currentTarget.dataset;
        let { listArr } = this;
        listArr.splice(index, 1);
        this.setData({
            listArr,
            defaultShow: false
        });
    },
    resetSelect: function (e) {
        uni.navigateBack({
            delta: 1
        });
    },
    resetBack: function (e) {
        uni.navigateBack({
            delta: 2
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {}
});
</script>
<style>
/* pages/entryWrite/page/Entry/prescription/addExamine/completeExamine/completeExamine.wxss */
page {
    height: 100%;
    width: 100%;
}
.complete-content {
    /* height: 100%;
  width: 100%;
  background-color: #FFFFFF;
  overflow: auto; */
    display: flex;
    flex-direction: column;
    height: 100%;
}
.complete-wrap {
    height: 100%;
    width: 100%;
    background-color: #ffffff;
    overflow: auto;
}

.item-title {
    display: flex;
    flex-direction: row;
    padding-left: 10rpx;
    padding: 20rpx 20rpx;
    font-size: 32rpx;
    font-weight: bold;
    background-color: #f5f4f4;
    border-bottom: 1rpx solid #f5f4f4;
}

.picker-border {
    border-bottom: 1rpx solid var(--weui-FG-3);
}
.btn-flex {
    width: 250rpx;
    display: flex;
    flex-direction: row;
    justify-content: right;
    margin-left: auto;
}
.selectT {
    background-color: #ffffff;
    width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    border: 1rpx solid #f5f4f4;
    text-align: center;
    border-radius: 20rpx;
}
.selectL {
    padding: 0px 5rpx;
    margin-right: 10rpx;
}
.part-flex {
    display: flex;
    flex-direction: column;
    height: 100%;
}
.part-a {
    flex: 1;
    padding: 20rpx;
    padding-top: 50rpx;
    height: 100%;
    overflow: auto;
}
.part-bTitle {
    text-align: center;
}
.part-b {
    height: 100rpx;
    display: flex;
    flex-direction: row;
}
.part-bbtn {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30rpx;
}
.btn-sure {
    color: #ffffff;
    background-color: #1890ff;
}
.part-aTitle {
    font-size: 36rpx;
    font-weight: bold;
    color: black;
}
.part-child {
    display: flex;
}
.part-aChild {
    flex: 0 0 33.333%;
}
.part-bChild {
    flex: 0 0 25%;
}

.part-margin {
    font-size: 26rpx;
    border: 1rpx solid #f5f4f4;
    text-align: center;
    margin: 10rpx;
    padding: 10rpx;
}

.child-active {
    color: #1890ff;
    border: 1rpx solid #1890ff;
}

.save-btn {
    height: 100rpx;
    line-height: 100rpx;
    color: #ffffff;
    background-color: #1890ff;
    text-align: center;
    font-size: 32rpx;
}
.no-part {
    padding: 16px;
    text-align: center;
    color: var(--weui-FG-2);
}
.fold {
    padding: 16px;
    text-align: center;
}

.title-left {
    flex: 1;
}

.title-right {
    color: #fa541c;
}
.nodata-show {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.btn-reset {
    color: #ffffff;
    background-color: #1890ff;
    padding: 20rpx;
    width: 200rpx;
    border-radius: 60rpx;
    margin-top: 80rpx;
}
.btn-back {
    background-color: #ffffff;
    padding: 20rpx;
    width: 200rpx;
    border: 1rpx solid #f5f4f4;
    border-radius: 60rpx;
    margin-top: 30rpx;
}
</style>
