<template>
    <view class="online-scheduling-page">
        <nav-bar :navbarData="navbarData"></nav-bar>
        <view class="online-scheduling" :style="'margin-top: ' + (height * 2 + 10) + 'rpx'">
            <view class="form-card">
                <view class="picker-border">
                    <picker @change="bindRoomChange" :value="roomIndex" :range="roomList" range-key="descripts">
                        <view class="picker-row">
                            <text class="picker-label">选择诊室</text>
                            <text class="picker-value">{{ roomList[roomIndex] ? roomList[roomIndex].descripts : '请选择' }}</text>
                            <view class="arrow-right"></view>
                        </view>
                    </picker>
                </view>
                <view class="picker-border">
                    <picker @change="bindDateChange" :value="dateIndex" :range="dateList" range-key="dateDescripts">
                        <view class="picker-row">
                            <text class="picker-label">选择日期</text>
                            <text class="picker-value">{{ selectedDateDesc || '请选择' }}</text>
                            <view class="arrow-right"></view>
                        </view>
                    </picker>
                </view>
            </view>

            <view class="schedule-card" v-if="scheduleList.length > 0">
                <view class="card-title">排班号源</view>
                <view class="schedule-item" v-for="(item, index) in scheduleList" :key="index">
                     <view class="picker-border interval-row">
                        <picker @change="bindIntervalChange($event, index)" :value="item.intervalIndex || 0" :range="item.intervalList" range-key="descripts">
                            <view class="picker-row">
                                <text class="picker-label">时间间隔</text>
                                <text class="picker-value">{{ getIntervalDesc(item) }}</text>
                                <view class="arrow-right"></view>
                            </view>
                        </picker>
                    </view>
                    <view class="item-header">
                        <text class="time-range">{{ item.timeRange }}</text>
                        <view class="source-inputs">
                            <view class="source-input-item">
                                <text class="input-label">号源数</text>
                                <input class="source-input" type="number" :value="item.registNum" @input="onRegistNumChange($event, index)" />
                            </view>
                            <text class="input-separator">/</text>
                            <view class="source-input-item">
                                <text class="input-label">预约限号</text>
                                <input class="source-input" type="number" :value="item.appointNum" @input="onAppointNumChange($event, index)" />
                            </view>
                        </view>
                    </view>
                    <view class="detail-list" v-if="item.detail && item.detail.length > 0">
                        <view class="detail-item" v-for="(detailItem, detailIndex) in item.detail" :key="detailIndex">
                            <text class="detail-time">{{ detailItem.timeRangDetail }}</text>
                            <text class="detail-count">{{ detailItem.registNum || 0 }}/{{ detailItem.appointNum || 0 }}</text>
                        </view>
                    </view>
                </view>
            </view>

            <view class="empty-tip" v-else-if="roomList.length > 0 && dateList.length > 0 && !loading">
                暂无排班号源数据
            </view>
        </view>

        <view class="bottom-btns">
            <button class="cancel-btn" @tap="goBack">取消</button>
            <button class="confirm-btn" @tap="confirmScheduling" :disabled="saveflag">
                {{ saveflag ? '确认中' : '确认排班' }}
            </button>
        </view>
    </view>
</template>

<script>
import navBar from '@/pages/components/navbar/index';
import Cache from '../../../../utils/cache';
import { $http } from '../../../../config/https.js';
const app = getApp();

export default {
    components: {
        navBar
    },
    data() {
        return {
            navbarData: {
                background: '',
                title: '上线排班',
                height: '100',
                bottom: true,
                isGoBack: true
            },
            height: app.globalData.height,

            // 用户信息
            userData: {},

            // 出诊类型ID，由上一页传入
            resourceTypeID: '',

            // 科室医生ID，默认取 userData.userID，如需调整请通过 opener 传入
            depDoctorID: '',

            // 诊室
            roomList: [],
            roomIndex: 0,

            // 日期
            dateList: [],
            dateIndex: 0,

            // 排班号源
            scheduleList: [],

            // 加载与提交状态
            loading: false,
            saveflag: false
        };
    },

    computed: {
        selectedDateDesc() {
            const item = this.dateList[this.dateIndex];
            if (!item) return '';
            return item.dateDescripts ? item.dateDescripts.replace(/\^/g, ' ') : '';
        },

        selectedRoomID() {
            const item = this.roomList[this.roomIndex];
            return item ? item.id : '';
        },

        selectedDate() {
            const item = this.dateList[this.dateIndex];
            return item ? this.formatDate(item.date) : '';
        }
    },

    onLoad: function (options) {
        this.userData = Cache.get('userData') || {};
        // 默认使用 userID 作为 depDoctorID， opener 可覆盖
        this.setData({
            resourceTypeID: options.resourceTypeID || '',
            depDoctorID: options.depDoctorID || this.userData.userID || ''
        });

        const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
        const hasOpenerChannel = eventChannel && typeof eventChannel.on === 'function';

        if (hasOpenerChannel) {
            eventChannel.on('onlineSchedulingInit', (data) => {
                data = data || {};
                this.setData({
                    resourceTypeID: data.resourceTypeID || this.resourceTypeID,
                    depDoctorID: data.depDoctorID || this.depDoctorID
                });
                this.initData();
            });
        }

        // 若 URL 参数已携带 resourceTypeID，直接初始化；否则等待 opener 通过 eventChannel 传递
        if (this.resourceTypeID || !hasOpenerChannel) {
            this.initData();
        }
    },

    methods: {
        initData: function () {
            if (!this.resourceTypeID) {
                uni.showToast({ title: '缺少出诊类型', icon: 'none' });
                return;
            }
            this.getDateList().then(() => {
                this.getRoomList().then(() => {
                    this.getScheduleList();
                });
            });
        },

        formatDate: function (dateValue) {
            if (!dateValue) return '';
            // 接口返回的 date 可能是 67759 这样的内部日期码，也可能是标准日期字符串
            const str = String(dateValue);
            if (str.indexOf('-') > -1) return str;
            // 若为非标准日期码，尝试从 dateDescripts 中解析
            const item = this.dateList[this.dateIndex];
            if (item && item.dateDescripts) {
                const match = item.dateDescripts.match(/\d{4}-\d{2}-\d{2}/);
                if (match) return match[0];
            }
            return str;
        },

        // 获取本周日期范围 2026-07-06||2026-07-12
        getWeekRange: function () {
            const now = new Date();
            const day = now.getDay() || 7;
            const monday = new Date(now.getTime() - (day - 1) * 24 * 60 * 60 * 1000);
            const sunday = new Date(monday.getTime() + 6 * 24 * 60 * 60 * 1000);
            const fmt = (d) => `${d.getFullYear()}-${this.pad2(d.getMonth() + 1)}-${this.pad2(d.getDate())}`;
            return `${fmt(monday)}||${fmt(sunday)}`;
        },

        pad2: function (value) {
            return String(value).padStart(2, '0');
        },

        // 获取日期下拉
        getDateList: function () {
            return new Promise((resolve) => {
                this.setData({ loading: true });
                const data = {
                    params: [
                        {
                            dateStr: this.getWeekRange(),
                            resourceTypeID: this.resourceTypeID
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '03020045',
                    data: data,
                    success: (res) => {
                        this.setData({ loading: false });
                        if (res.errorCode == '0') {
                            const list = Array.isArray(res.data) ? res.data : [];
                            // 过滤不可用的日期
                            const enabledList = list.filter((item) => item.disabled !== 'Y');
                            this.setData({
                                dateList: enabledList.length > 0 ? enabledList : list,
                                dateIndex: 0
                            });
                        } else {
                            uni.showToast({ title: res.errorMessage || '获取日期失败', icon: 'none' });
                        }
                        resolve();
                    },
                    fail: () => {
                        this.setData({ loading: false });
                        uni.showToast({ title: '获取日期失败', icon: 'none' });
                        resolve();
                    }
                });
            });
        },

        // 获取诊室下拉
        getRoomList: function () {
            return new Promise((resolve) => {
                const userData = this.userData;
                const data = {
                    params: [
                        {
                            hospID: userData.hospID,
                            locID: userData.locID,
                            resourceTypeID: this.resourceTypeID
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '01040023',
                    data: data,
                    success: (res) => {
                        if (res.errorCode == '0') {
                            const list = Array.isArray(res.room) ? res.room : [];
                            this.setData({
                                roomList: list,
                                roomIndex: 0
                            });
                        } else {
                            uni.showToast({ title: res.errorMessage || '获取诊室失败', icon: 'none' });
                        }
                        resolve();
                    },
                    fail: () => {
                        uni.showToast({ title: '获取诊室失败', icon: 'none' });
                        resolve();
                    }
                });
            });
        },

        // 获取排班号源
        getScheduleList: function () {
            if (!this.selectedRoomID || !this.selectedDate) return;
            this.setData({ loading: true });
            const userData = this.userData;
            const data = {
                params: [
                    {
                        userID: userData.userID,
                        locID: userData.locID,
                        hospID: userData.hospID,
                        timeRangeID: '',
                        resourceTypeID: this.resourceTypeID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03020032',
                data: data,
                success: (res) => {
                    this.setData({ loading: false });
                    if (res.errorCode == '0' || res.errorCode === 0) {
                        // 接口返回 roomID 时同步诊室选择
                        if (res.roomID && this.roomList.length > 0) {
                            const roomIdx = this.roomList.findIndex((item) => item.id == res.roomID);
                            if (roomIdx >= 0) {
                                this.setData({ roomIndex: roomIdx });
                            }
                        }
                        const list = Array.isArray(res.resModel) ? res.resModel : [];
                        const scheduleList = list.map((item) => {
                            const intervalList = Array.isArray(item.intervalList) ? item.intervalList : [];
                            // 为 intervalList 生成显示文本
                            intervalList.forEach((interval) => {
                                interval.descripts = interval.timeLength ? `${interval.timeLength}分钟` : '全时段';
                            });
                            // 默认选中 defaultFlag=1 的项
                            const defaultIndex = intervalList.findIndex((interval) => interval.defaultFlag == 1 || interval.defaultFlag == 'Y');
                            const intervalIndex = defaultIndex >= 0 ? defaultIndex : 0;
                            return {
                                ...item,
                                intervalList,
                                intervalIndex
                            };
                        });
                        this.setData({ scheduleList });
                    } else {
                        uni.showToast({ title: res.errorMessage || '获取号源失败', icon: 'none' });
                    }
                },
                fail: () => {
                    this.setData({ loading: false });
                    uni.showToast({ title: '获取号源失败', icon: 'none' });
                }
            });
        },

        bindRoomChange: function (e) {
            this.setData(
                {
                    roomIndex: e.detail.value
                },
                () => {
                    this.getScheduleList();
                }
            );
        },

        bindDateChange: function (e) {
            this.setData(
                {
                    dateIndex: e.detail.value
                },
                () => {
                    this.getScheduleList();
                }
            );
        },

        bindIntervalChange: function (e, index) {
            const intervalIndex = e.detail.value;
            this.scheduleList[index].intervalIndex = intervalIndex;
            this.setData({
                scheduleList: this.scheduleList
            });
        },

        onRegistNumChange: function (e, index) {
            this.scheduleList[index].registNum = e.detail.value;
            this.setData({
                scheduleList: this.scheduleList
            });
        },

        onAppointNumChange: function (e, index) {
            this.scheduleList[index].appointNum = e.detail.value;
            this.setData({
                scheduleList: this.scheduleList
            });
        },

        getIntervalDesc: function (item) {
            const interval = item.intervalList[item.intervalIndex || 0];
            if (!interval) return '全时段';
            return interval.descripts;
        },

        getSelectedInterval: function (item) {
            return item.intervalList[item.intervalIndex || 0] || {};
        },

        goBack: function () {
            uni.navigateBack({});
        },

        confirmScheduling: function () {
            if (this.saveflag) return;
            if (!this.selectedRoomID) {
                uni.showToast({ title: '请选择诊室', icon: 'none' });
                return;
            }
            if (!this.selectedDate) {
                uni.showToast({ title: '请选择日期', icon: 'none' });
                return;
            }
            if (this.scheduleList.length === 0) {
                uni.showToast({ title: '暂无排班数据', icon: 'none' });
                return;
            }

            this.setData({ saveflag: true });
            const userData = this.userData;
            const date = this.selectedDate;
            const params = this.scheduleList.map((item) => {
                const interval = this.getSelectedInterval(item);
                const detail = Array.isArray(item.detail) ? item.detail : [];
                return {
                    depDoctorID: item.depDoctorID,
                    roomID: this.selectedRoomID,
                    regTitleID: item.regTitleID || '14',
                    regTitle: item.regTitle || '图文咨询',
                    timeRangeID: item.timeRangeID || '',
                    timeRange: item.timeRange || '',
                    intervalList: item.intervalList.map((intervalItem) => ({
                        id: intervalItem.id,
                        timeLength: intervalItem.timeLength,
                        defaultFlag: intervalItem.defaultFlag
                    })),
                    registNum: item.registNum || 0,
                    appointNum: item.appointNum || 0,
                    detail: detail.map((detailItem) => ({
                        indexId: detailItem.indexId || '',
                        id: detailItem.id || '',
                        timeRangDetail: detailItem.timeRangDetail || '',
                        registNum: detailItem.registNum || 0,
                        appointNum: detailItem.appointNum || 0
                    })),
                    timeInterval: interval.timeLength || '',
                    timeIntervalID: interval.id || '',
                    addNum: '',
                    expertiseID: '',
                    togetherSource: '',
                    userID: userData.userID,
                    resourceTypeID: this.resourceTypeID,
                    date: date,
                    locID: userData.locID
                };
            });

            $http.post('urlDeault', this, {
                code: '03020044',
                data: { params },
                success: (res) => {
                    this.setData({ saveflag: false });
                    if (res.errorCode == '0') {
                        uni.showToast({ title: '排班成功', icon: 'success' });
                        const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
                        if (eventChannel && typeof eventChannel.emit === 'function') {
                            eventChannel.emit('onlineSchedulingConfirm', {
                                roomID: this.selectedRoomID,
                                date: date
                            });
                        }
                        setTimeout(() => {
                            uni.navigateBack({});
                        }, 500);
                    } else {
                        uni.showToast({ title: res.errorMessage || '排班失败', icon: 'none' });
                    }
                },
                fail: () => {
                    this.setData({ saveflag: false });
                    uni.showToast({ title: '排班失败', icon: 'none' });
                }
            });
        }
    }
};
</script>

<style>
page {
    height: 100%;
    background: #f5f7fb;
}

.online-scheduling-page {
    min-height: 100%;
    padding-bottom: 140rpx;
    box-sizing: border-box;
}

.online-scheduling {
    padding: 20rpx;
}

.form-card,
.schedule-card {
    background: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 16rpx rgba(25, 82, 150, 0.06);
}

.picker-border {
    border-bottom: 1rpx solid #f0f0f0;
}

.picker-border:last-child {
    border-bottom: none;
}

.picker-row {
    display: flex;
    align-items: center;
    padding: 28rpx 24rpx;
    font-size: 30rpx;
}

.picker-label {
    color: #333333;
    font-weight: 500;
    flex-shrink: 0;
    margin-right: 24rpx;
}

.picker-value {
    flex: 1;
    text-align: right;
    color: #666666;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.arrow-right {
    width: 16rpx;
    height: 16rpx;
    border-top: 2rpx solid #c0c4cc;
    border-right: 2rpx solid #c0c4cc;
    transform: rotate(45deg);
    margin-left: 12rpx;
    flex-shrink: 0;
}

.card-title {
    padding: 24rpx;
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    border-bottom: 1rpx solid #f0f0f0;
}

.schedule-item {
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.schedule-item:last-child {
    border-bottom: none;
}

.item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
}

.time-range {
    font-size: 30rpx;
    font-weight: bold;
    color: #333333;
}

.source-count {
    font-size: 28rpx;
    color: #1890ff;
    font-weight: 500;
}

.source-inputs {
    display: flex;
    align-items: center;
}

.source-input-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.input-label {
    font-size: 20rpx;
    color: #999999;
    margin-bottom: 4rpx;
}

.source-input {
    width: 80rpx;
    height: 52rpx;
    line-height: 52rpx;
    text-align: center;
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333333;
    padding: 0 8rpx;
}

.input-separator {
    margin: 0 12rpx;
    font-size: 28rpx;
    color: #999999;
    padding-top: 18rpx;
}

.interval-row .picker-row {
    padding: 20rpx 0;
}

.interval-row .picker-label {
    font-size: 28rpx;
    color: #666666;
}

.detail-list {
    margin-top: 12rpx;
    padding: 16rpx;
    background: #f8fafc;
    border-radius: 8rpx;
}

.detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12rpx 0;
    font-size: 28rpx;
    color: #4b5563;
}

.detail-time {
    color: #333333;
}

.detail-count {
    color: #1890ff;
}

.empty-tip {
    text-align: center;
    padding: 80rpx 40rpx;
    color: #999999;
    font-size: 28rpx;
}

.bottom-btns {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    padding: 20rpx;
    background: #ffffff;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
    box-sizing: border-box;
}

.bottom-btns button {
    flex: 1;
    height: 88rpx;
    line-height: 88rpx;
    font-size: 30rpx;
    border-radius: 44rpx;
    margin: 0 10rpx;
}

.cancel-btn {
    background: #f5f7fb;
    color: #666666;
}

.confirm-btn {
    background: #0079fe;
    color: #ffffff;
}

.confirm-btn[disabled] {
    background: #a0cfff;
    color: #ffffff;
}
</style>
