// 定义水电编辑页面类
shr.defineClass("shr.dormitorysystem.WaterElectricityEdit", shr.framework.Edit, {
    // 实例属性：保存当前实例引用（替代全局that）
    that: null,

    /**
     * 初始化DOM元素及事件绑定
     */
    initalizeDOM: function () {
        shr.dormitorysystem.WaterElectricityEdit.superClass.initalizeDOM.call(this);
        this.that = this;
        const operateState = this.getOperateState().toUpperCase();

        // 新增状态下：默认设置开始日期为当天
        if ("ADDNEW" === operateState) {
            this.setDefaultStartDate();
        }

        // 非查看状态下：绑定业务相关事件
        if ("VIEW" !== operateState) {
            this.bindOccupantsChangeEvent(); // 绑定入住人员变更事件
            this.bindDormitoryChangeEvent(); // 绑定房间变更事件
            this.bindStartDateChangeEvent(); // 绑定开始日期变更事件
        }
    },

    /**
     * 【通用方法】设置开始日期默认值为当天
     */
    setDefaultStartDate: function () {
         this.that.getField('startDate').shrDateTimePicker('setValue', new Date());
         this.that.setYearMonthVal();
    },


    /**
     * 【通用方法】设置开始日期默认值为当天
     */
    setYearMonthVal: function () {
        var startDate = $('#startDate').val();
		if(startDate){
			$('#yearMonth').shrTextField("setValue",startDate);
		}
    },

    /**
     * 【通用方法】远程调用获取水电单价
     * @param {String} dormFid 房间ID
     * @param {Date} startDate 开始日期
     */
    fetchWaterElecPrice: function (dormFid, startDate) {
        // 空值校验：房间ID为空时不发起请求
        if (!dormFid) return;

        this.that.remoteCall({
            method: "getWaterElecPrice",
            async: false,
            param: {
                dormFid: dormFid,
                startDate: startDate
            },
            success: (data) => {
                if (data) {
                    // 赋值水电单价到表单字段
                    this.that.getField('waterprice').shrTextField('setValue', data.CFWaterprice);
                    this.that.getField('electricityprice').shrTextField('setValue', data.CFElectricityprice);
                }
            },
            // 新增错误处理（增强鲁棒性）
            error: (err) => {
                console.error('获取水电单价失败：', err);
            }
        });
    },

    /**
     * 【事件绑定】入住人员选择变更事件
     */
    bindOccupantsChangeEvent: function () {
        $("#occupants").shrPromptBox("option", {
            onchange: (e, value) => {
                const occupants = value.current;
                if (!occupants) return;

                // 赋值组织/岗位/人员等信息
                this.assignOccupantsInfo(occupants);
            }
        });
    },

    /**
     * 【通用方法】赋值入住人员相关信息到表单
     * @param {Object} occupants 入住人员数据对象
     */
    assignOccupantsInfo: function (occupants) {
        // 所属组织
        $("#adminOrg").shrPromptBox("setValue", {
            id: occupants["personPosition.personDep.id"],
            name: occupants["personPosition.personDep.name"]
        });
        // 岗位
        $("#position").shrPromptBox("setValue", {
            id: occupants["personPosition.primaryPosition.id"],
            name: occupants["personPosition.primaryPosition.name"]
        });
        // 人员
        $("#person").shrPromptBox("setValue", {
            id: occupants["person.id"],
            name: occupants["person.name"],
            number: occupants["person.number"]
        });
        $('#empName').shrTextField("setValue",occupants["personPosition.person.name"]);
        $('#empNumber').shrTextField("setValue", occupants["personPosition.person.number"]);
        // 入住日期
        $("#bizDate").shrDateTimePicker("setValue", occupants.CheckInDate);
        // 退宿日期
        $("#leaveDate").shrDateTimePicker("setValue", occupants.CheckOutDate);
        // 现住房间
        $("#dormitory").shrPromptBox("setValue", {
            id: occupants["Dormitory.id"],
            name: occupants["Dormitory.name"],
            displayName: occupants["Dormitory.displayName"]
        });
        $('#hrOrgUnit').shrPromptBox("setValue",
                            {
                                id: '00000000-0000-0000-0000-000000000000CCE7AED4',
                                name: 'HR组织'
                            }
                        );
    },

    /**
     * 【事件绑定】房间选择变更事件
     */
    bindDormitoryChangeEvent: function () {
        $("#dormitory").shrPromptBox("option", {
            onchange: (e, value) => {
                const dormitory = value.current;
                if (!dormitory) return;

                // 获取开始日期
                const startDate = this.that.getField('startDate').shrDateTimePicker('getValue');
                // 调用通用方法获取水电单价
                this.fetchWaterElecPrice(dormitory.id, startDate);
            }
        });
    },

    /**
     * 【事件绑定】开始日期变更事件
     */
    bindStartDateChangeEvent: function () {
        $("#startDate").shrDateTimePicker("onChange", () => {
            // 获取房间ID
            const dormitory = this.that.getField('dormitory').shrPromptBox('getValue');
            // 获取变更后的开始日期
            const startDate = this.that.getField('startDate').shrDateTimePicker('getValue');
            // 调用通用方法获取水电单价
            this.fetchWaterElecPrice(dormitory.id, startDate);
            setYearMonthVal();
        });
    },


    saveAction: function(event) {
        var _self = this;
        var operateState = _self.getOperateState().toUpperCase();
        if("ADDNEW"==operateState) {
            var startDate = $('#startDate').val();
            var person = $('#person').shrPromptBox("getValue");
            let timestamp = new Date().getTime();
            var number="TWE"+person.number+"-"+timestamp;
            $('#number').shrTextField("setValue",number);
        }
        if (_self.validate() && _self.verify()) {
            _self.doSave(event, 'save');
        }else{
            if(_self != top){// in iframe
                shr.setIframeHeight(window.name);
            }

        }
    },

    
});