<template>
    <!-- pages/oneselfCenter/page/schedulingQuery/schedulingQuery.wxml -->
    <view class="scheduling-wrapper">
        <view class="scheduling-content">
            <view class="picker-border">
                <picker :disabled="!withdrawalFlag" @change="bindVisitChange" :value="visitIndex" :range="visitArr">
                    <mp-cell link hover value="是否坐诊" :footer="visitArr[visitIndex]"></mp-cell>
                </picker>
            </view>
            <view class="picker-border">
                <picker @change="bindSchedulingTypeChange" :value="schedulingTypeIndex" :range="schedulingTypeArr" range-key="descripts">
                    <mp-cell link hover value="号别" :footer="schedulingTypeArr[schedulingTypeIndex].descripts"></mp-cell>
                </picker>
            </view>

            <view class="picker-border">
                <mp-cell value="时段间隔(分钟)" :footer="timeIntervalDesc"></mp-cell>
            </view>

            <view class="picker-times">
                <mp-cell value="时段明细"></mp-cell>
            </view>
            <view :class="'picker-border ' + (visitIndex == 1 ? 'disableClass' : '')" v-for="(item, index) in resDetailArr" :key="index">
                <view class="picker-border">
                    <picker @change="bindVisitDetailChange" :value="item.statusCode == 'N' ? 0 : 1" :range="visitDetailArr" :data-index="index" :data-item="item">
                        <mp-cell link hover :value="item.timeDatail" :footer="visitDetailArr[item.statusCode == 'N' ? 0 : 1]"></mp-cell>
                    </picker>
                </view>

                <mp-cell :footer="'已用号源/总号源：' + item.usedNum + '/' + item.totalNumber">
                    <view class="inputLeft">
                        <view>输入号源：</view>
                        <input
                            style="width: 50%; border: 1rpx solid #eeeeee"
                            type="number"
                            @input="formInputChange"
                            :value="item.registNum"
                            :data-index="index"
                            :data-item="item"
                        />
                    </view>
                </mp-cell>
            </view>
        </view>

        <button class="handle-btn" @tap="editSchedulingDetail" :disabled="saveflag">{{ saveflag && saveflag ? '修改中' : '修改排班' }}</button>
    </view>
</template>

<script>
import Cache from '../../../../utils/cache';
// pages/oneselfCenter/page/schedulingQuery/schedulingQuery.js
import { $http } from '../../../../config/https.js';
import messageUtil from '../../../../utils/message.js';
export default {
    components: {},
    data() {
        return {
            resDetailID: '',

            //当前排班ID
            regTitleID: '',

            //当前职称ID
            timeIntervalDesc: '',

            //时段间隔
            // 下拉选项
            schedulingTypeArr: [],

            schedulingTypeIndex: 0,

            // accounts: [],
            // accountIndex: 0,
            timeIndex: 0,

            // 是否坐诊
            visitArr: ['坐诊', '停诊'],

            visitIndex: 0,

            // 时段明细列表
            resDetailArr: [],

            visitDetailArr: ['坐诊', '停诊'],
            visitDetailIndex: {},

            // 记录当前坐诊的时段
            makeVisitTimeArr: [],

            withdrawalFlag: 'N',

            // 能否停诊标志
            saveflag: false,

            resourceTypeID: '',
            descripts: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let item = JSON.parse(options.transData);
        this.setData({
            resDetailID: item.resDetailID,
            timeIntervalDesc: item.timeIntervalDesc,
            regTitleID: item.regTitleID,
            resourceTypeID: options.resourceTypeID
        });
        uni.setNavigationBarTitle({
            title: `修改排班 ${options.date} ${item.timeRange}`
        });
        this.getSchedulingType();
        this.getSchedulingDetail(item.resDetailID);

        // 时段状态  是否坐诊
        if (item.statusID == '1') {
            this.setData({
                visitIndex: 0
            });
        } else {
            this.setData({
                visitIndex: 1
            });
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.canWithdrawal();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        // 根据配置是否能停诊
        canWithdrawal: function () {
            let userData = Cache.get('userData');
            let { userID, hospID, locID } = userData;
            let data = {
                params: [
                    {
                        userID,
                        hospID,
                        locID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100117',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setData({
                            withdrawalFlag: res.result
                        });
                    }
                }
            });
        },

        // 大时段坐诊状态
        bindVisitChange: function (e) {
            // if (this.data.visitIndex !== e.detail.value) {
            //   this.setData({
            //     visitIndex: e.detail.value
            //   });
            // }
            this.setData(
                {
                    visitIndex: e.detail.value
                },
                () => {
                    let newDArray = this.resDetailArr.map((data) => {
                        this.updateVisit(data);
                        if (e.detail.value == '0') {
                            data.status = '坐诊';
                            data.statusCode = 'N';
                        } else {
                            data.status = '停诊';
                            data.statusCode = 'S';
                        }
                        return data;
                    });
                    this.setData({
                        resDetailArr: newDArray
                    });
                }
            );
        },

        // 停诊/恢复坐诊
        bindVisitChangeHttp: function (e) {
            let userData = Cache.get('userData');
            let { userID } = userData;
            let { visitIndex } = this;
            let data = {
                params: [
                    {
                        resDetailID: this.resDetailID,
                        userID: userID,
                        statusCode: visitIndex == '0' ? 'N' : 'S'
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100051',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.getUnTreatPatList();
                        this.getSchedulingDetail(this.resDetailID);
                    }
                }
            });
        },

        /**
         * 获取未诊疗的患者列表
         */
        getUnTreatPatList: function () {
            let timeData = this.makeVisitTimeArr
                .filter((data) => {
                    return data.statusCode == 'S';
                })
                .map((data) => {
                    return data.resTimeID;
                });
            if (timeData.length > 0) {
                let data = {
                    params: [
                        {
                            locResID: this.resDetailID,
                            timeData: timeData //时段id
                        }
                    ]
                };

                $http.post('urlDeault', this, {
                    code: '03100101',
                    data: data,
                    success: function (res) {
                        if (res.errorCode == '0') {
                            if (res.result.length > 0) {
                                for (let i = 0; i < res.result.length; i++) {
                                    messageUtil.handleSendMessage2('B', '医生停诊', 'patient' + res.result[i].patID, res.result[i]);
                                }
                                // res.result.forEach(data => {
                                //   messageUtil.handleSendMessage2("B", "医生停诊","patient"+data.patID,data);
                                // });
                            }
                        }
                    }
                });
            }
        },

        // 时段明细坐诊状态
        bindVisitDetailChange: function (e) {
            let { index, item } = e.currentTarget.dataset;
            let newItem = item;
            if (e.detail.value == 0) {
                newItem.statusCode = 'N';
            } else {
                newItem.statusCode = 'S';
            }
            this.resDetailArr[index] = newItem;
            this.updateVisit(newItem);
            this.setData(
                {
                    resDetailArr: this.resDetailArr
                },
                () => {
                    // let userData = wx.getStorageSync('userData');
                    // let {
                    //   userID,
                    // } = userData;
                    // let data = {
                    //   "params": [{
                    //     resTime: [item.resTimeID],
                    //     userID: userID,
                    //     statusCode: e.detail.value == "0" ? "N" : "S"
                    //   }]
                    // };
                    // $http.post('urlDeault', this, {
                    //   code: "03100052",
                    //   data: data,
                    //   success: function (res) {
                    //     if (res.errorCode == "0") {
                    //       // 更新坐诊状态
                    //       let mark = false;
                    //       this.data.resDetailArr.forEach(item => {
                    //         if (item.statusCode == "N") {
                    //           mark = true;
                    //         }
                    //       })
                    //       // 时段状态  是否坐诊
                    //       if (mark) {
                    //         this.setData({
                    //           visitIndex: 0
                    //         });
                    //       } else {
                    //         this.setData({
                    //           visitIndex: 1
                    //         });
                    //       }
                    //     }
                    //   }
                    // });
                }
            );
        },

        // 修改时段明细坐诊状态的值
        updateVisit: function (item) {
            let aa = this.makeVisitTimeArr.map((data) => {
                if (item.resTimeID == data.resTimeID) {
                    data.statusCode = item.statusCode;
                }
                return data;
            });
            this.setData({
                makeVisitTimeArr: aa
            });
        },

        bindSchedulingTypeChange: function (e) {
            this.setData({
                schedulingTypeIndex: e.detail.value
            });
        },

        // 排班类型
        getSchedulingType: function () {
            let userData = Cache.get('userData');
            let { userID, groupID, locID, hospID } = userData;
            let data = {
                params: [
                    {
                        userID: userID,
                        groupID: groupID,
                        locID: locID,
                        hospID: hospID,
                        resTypeID: this.resourceTypeID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100130',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setData(
                            {
                                schedulingTypeArr: res.result.Data
                            },
                            () => {
                                this.getRegTitleIndex(this.regTitleID);
                            }
                        );
                    }
                }
            });
        },

        // 当前排班明细
        getSchedulingDetail: function (resDetailID) {
            let data = {
                params: [
                    {
                        resDetailID: resDetailID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100049',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        let newData = res.result.map((data) => {
                            data.totalNumber = data.registNum;
                            return data;
                        });
                        let newVisit = res.result.filter((data) => {
                            return data.statusCode == 'N';
                        });
                        this.setData({
                            resDetailArr: newData,
                            makeVisitTimeArr: newVisit
                        });
                    }
                }
            });
        },

        // 修改当前排班
        editSchedulingDetail: function () {
            // this.bindVisitChangeHttp();
            let that = this;
            if (that.saveflag == true) {
                throw SyntaxError();
            }
            that.setData({
                saveflag: true
            }); //请求前禁用标记改为true,防止重复请求
            this.getUnTreatPatList();
            let userData = Cache.get('userData');
            let { userID } = userData;
            let resTimes = this.resDetailArr
                .filter((data) => {
                    if (data.registNum !== '') {
                        return data;
                    }
                })
                .map((data) => {
                    return {
                        resTimeID: data.resTimeID,
                        registNum: data.registNum,
                        statusCode: data.statusCode
                    };
                });
            let data = {
                params: [
                    {
                        statusCode: this.visitIndex == '0' ? 'N' : 'S',
                        //大时段的坐诊状态
                        resDetailID: this.resDetailID,
                        userID: userID,
                        regTitleID: this.getRegTitleId(),
                        registNum: '',
                        addNum: '',
                        resTime: resTimes
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100062',
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        uni.navigateBack({});
                    }
                    setTimeout(() => {
                        that.setData({
                            saveflag: false
                        }); //请求成功禁用标记改回false
                    }, 1000);
                },
                fail: function () {
                    setTimeout(() => {
                        that.setData({
                            saveflag: false
                        }); //请求虽然失败,禁用标记也改回false
                    }, 1000);
                }
            });
        },

        // 获取职称ID
        getRegTitleId: function () {
            let array = this.schedulingTypeArr;
            if (array.length > 0) {
                return array[this.schedulingTypeIndex].id;
            }
        },

        // 根据ID获取下标
        getRegTitleIndex: function (id) {
            let array = this.schedulingTypeArr;
            if (array.length > 0) {
                let index = array.findIndex((data) => {
                    return id == data.id;
                });
                this.setData({
                    schedulingTypeIndex: index
                });
            }
        },

        bindTimeChange: function (e) {
            this.setData({
                timeIndex: e.detail.value
            });
        },

        // 获取排班类型下标
        formInputChange: function (e) {
            let { index } = e.target.dataset;
            this.resDetailArr[index].registNum = e.detail.value;
            this.setData({
                resDetailArr: this.resDetailArr
            });
        }
    }
};
</script>
<style>
/* @import '../schedulingHandle/schedulingHandle.css'; */
.disableClass {
    pointer-events: none;
    background: #eee;
}

.inputLeft {
    display: flex;
}
.rightStyle {
    display: flex;
    justify-content: center;
    align-items: center;
}
.rightLable {
    flex: 1;
    text-align: right;
    margin-right: 5px;
}
.rightInput {
    border: 1px solid #eee;
    width: 60px;
    border-radius: 5px;
    text-align: center;
}
</style>
