<template>
    <view class="container">
        <!-- 计划名称输入框 -->
        <view class="input-container">
            <text class="input-label">计划名称:</text>
            <input
                class="input-field"
                type="text"
                v-model="planInfo.name"
                placeholder="请输入计划名称"
            />
        </view>
        <!-- <view class="input-container">
            <text class="input-label">触发阈值:</text>
            <input
                class="input-field"
                type="number"
                v-model="thresholdTime"
                placeholder="请输入触发阈值"
            />
        </view>

        <view class="input-container">
            <text class="input-label">归并时间:</text>
            <input
                class="input-field"
                type="number"
                v-model="mergeTime"
                placeholder="请输入归并时间"
            />
        </view> -->

        <!-- 事件类型选择 -->
        <view class="select-container">
            <text class="input-label">事件类型:</text>
            <input
                class="input-field"
                type="text"
                v-model="eventType.eventDesc"
                placeholder="请选择计划类型"
                disabled="true"
            />
        </view>

        <!-- 计划时间 -->
        <view class="time-container" style="margin-bottom: 20rpx">
            <text class="input-label">计划时间:</text>
            <view class="time-picker-container">
                <picker
                    mode="date"
                    v-model="startDate"
                    start="2000-01-01"
                    end="2099-12-31"
                    @change="bindStartChange"
                >
                    <view class="picker-content">{{ startDate }}</view>
                </picker>
                ~
                <picker
                    mode="date"
                    v-model="stopDate"
                    start="2000-01-01"
                    end="2099-12-31"
                    @change="bindEndChange"
                >
                    <view class="picker-content">{{ stopDate }}</view>
                </picker>
            </view>
        </view>

        <!-- 生效时段 -->
        <view class="time-container" v-if="judgeFlage != 'noneFlag'">
            <text class="input-label">生效时段:</text>
            <view class="time-picker-container">
                <picker
                    mode="time"
                    v-model="effectiveStart"
                    @change="bindEffectiveStartChange"
                >
                    <view class="picker-content" style="width: 170rpx">{{
                        effectiveStart
                    }}</view>
                </picker>
                ~
                <picker
                    mode="time"
                    v-model="effectiveEnd"
                    @change="bindEffectiveEndChange"
                >
                    <view class="picker-content" style="width: 170rpx">{{
                        effectiveEnd
                    }}</view>
                </picker>
            </view>
        </view>
        <view class="time-range-wrapper" v-if="timeRange.length > 0">
            <view
                class="time-item"
                v-for="(item, index) in timeRange"
                :key="index"
            >
                <text class="time-text"
                    >{{ item.start_time }} - {{ item.end_time }}</text
                >
                <text class="delete-btn" @click="removeTime(index)">×</text>
            </view>
        </view>

        <!-- 告警提醒 -->
        <view class="switch-container" style="margin-top: 20rpx">
            <text class="input-label">告警联动(服务号推送):</text>
            <switch
                :checked="linkagePushWechatService == 1"
                @change="onChangeLian"
                :active-value="1"
                :inactive-value="0"
                size="24px"
                active-color="#07c160"
                inactive-color="#eeeff1"
                style="transform: scale(0.8)"
            />
        </view>

        <!-- 是否启用 -->
        <view class="switch-container">
            <text class="input-label">是否启用:</text>
            <switch
                :checked="enable == 1"
                @change="onChangeQi"
                :active-value="1"
                :inactive-value="0"
                size="24px"
                active-color="#07c160"
                inactive-color="#eeeff1"
                style="transform: scale(0.8)"
            />
        </view>
        <!-- 保存按钮 -->
        <view class="save-button" @click="saveTemplate">
            <text class="save-button-text">保存</text>
        </view>
        <!-- 区域选择 -->
        <view v-if="areaModle" class="areaModleClass">
            <view
                class="airCantInfo"
                :style="{
                    width: `${length / 150}px`,
                    height: `${width / 150}px`,
                }"
            >
                <view
                    v-for="(item, index) in modules"
                    :key="index"
                    class="module-content"
                >
                    <view
                        :class="item.type"
                        :style="{
                            width: `${item.width / 2}px`,
                            height: `${item.length / 2}px`,
                            top: `${item.top / 2}px`,
                            left: `${item.left / 2}px`,
                            transform: `rotate(${item.rotate}deg)`,
                            'transform-origin': 'center center',
                        }"
                    >
                        <image
                            style="width: 100%; height: 100%; display: block"
                            :src="`../../static/furnitures/${item.type}.png`"
                            mode=""
                        />
                    </view>
                </view>
                <view
                    class="areaModleArea"
                    :style="{
                        width: `${areaModleWidth / 2}px`,
                        height: `${areaModLength / 2}px`,
                        top: `${areaModLeTop / 2}px`,
                        left: `${areaModLeLeft / 2}px`,
                        transform: `rotate(${item.rotate}deg)`,
                        'transform-origin': 'center center',
                    }"
                    @touchmove.prevent="onTouchMove($event)"
                    @touchstart="onTouchStart($event)"
                    @touchend="onTouchEnd($event)"
                ></view>
            </view>

            <view style="display: flex; margin: 20rpx auto">
                <view style="display: flex">
                    <text>长:</text>
                    <input
                        type="number"
                        placeholder="请输入区域长"
                        v-model="areaModLength"
                    />
                </view>
                <view style="display: flex">
                    <text>宽:</text>
                    <input
                        type="number"
                        placeholder="请输入区域宽"
                        v-model="areaModleWidth"
                    />
                </view>
            </view>
            <view
                style="
                    margin: 20rpx auto;
                    width: 200rpx;
                    height: 100rpx;
                    text-align: center;
                    line-height: 100rpx;
                    background: #f3e2dd;
                    color: #000;
                    border-radius: 20rpx;
                "
                @click="saveRegion()"
                >确定区域</view
            >
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            planName: "",
            selectedEventType: 0,
            startDate: "2025-01-01",
            stopDate: "2025-11-01",
            effectiveStart: "00:00",
            effectiveEnd: "23:59",
            isAlarmActive: true,
            isEnabled: true,
            planInfo: {},
            warmTypeList: [],
            eventType: "",
            linkagePushWechatService: 1,
            enable: 1,
            timeRange: [],
            thresholdTime: 300,
            mergeTime: 30,
            judgeFlage: "",
            remark: "",
            areaModle: false,
            devInfo: "",
            modules: [],
            length: 0,
            width: 0,
            xOffset: 0,
            yOffset: 0,
            areaModleWidth: 100,
            areaModLength: 100,
            areaModLeTop: 0,
            areaModLeLeft: 0,
            areaModLeX: 0,
            areaModLeY: 0,
            initTop: 0,
            initLeft: 0,
            region: [],
            judgeFlagFlag: false,
            selectedPlan: {},
        };
    },
    methods: {
        saveRegion() {
            this.region[0] = this.areaModLeX;
            this.region[1] = this.areaModLeY;
            this.region[2] = this.areaModleWidth;
            this.region[3] = this.areaModLength;
            this.areaModle = false;
            this.selectedPlan.region = JSON.stringify(this.region);
            console.log(this.selectedPlan, 9999);
            this.$http
                .post(
                    "wap/alarm/plan/save",
                    { ...this.selectedPlan },
                    {
                        header: {
                            "Content-Type": "application/json",
                            token: uni.getStorageSync("tokenValue") || "",
                        },
                    }
                )
                .then((res) => {
                    if (res.data.code == 200) {
                        uni.showToast({
                            title: "修改成功",
                            icon: "success",
                        });
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1,
                            });
                        }, 1000);
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: "none",
                            duration: 1500,
                        });
                    }
                });
        },
        saveTemplate() {
            // 1 2 3 9
            // 允许多个时间
            // 5 7
            // 只有一个时间
            // 4 6 8
            // 不配生效时间
            // 1 2 6 9  需要配置区域
            if (this.judgeFlage == "noneFlag") {
                this.timeRange = [
                    {
                        start_time: "00:00",
                        end_time: "23:59",
                    },
                ];
            } else if (this.judgeFlage == "one" && this.timeRange.length > 1) {
                uni.showModal({
                    title: "提示",
                    content: "此事件类型只能选择一个生效时段",
                    showCancel: false,
                });
                return;
            }
            if (this.enable == true) {
                this.enable = 1;
            } else {
                this.enable = 0;
            }
            if (this.linkagePushWechatService == true) {
                this.linkagePushWechatService = 1;
            } else {
                this.linkagePushWechatService = 0;
            }

            let planInfo = {
                alarmPlanId: this.planInfo.id,
                name: this.planInfo.name,
                clientId: this.planInfo.clientId,
                eventVal: this.planInfo.eventVal,
                thresholdTime: this.thresholdTime,
                mergeTime: this.mergeTime,
                linkagePushWechatService: this.linkagePushWechatService,
                enable: this.enable,
                region: JSON.stringify(this.region),
                alarmTimePlan: {
                    id: this.planInfo.alarmTimePlan.id,
                    startDate: this.startDate,
                    stopDate: this.stopDate,
                    timeRange: JSON.stringify(this.timeRange),
                    monthDays: this.planInfo.alarmTimePlan.monthDays,
                    weekdays: this.planInfo.alarmTimePlan.weekdays,
                },
            };
            if (this.region.length > 0) {
                planInfo.region = JSON.stringify(this.region);
            }
            if (
                this.planInfo.eventVal == 1 ||
                this.planInfo.eventVal == 2 ||
                this.planInfo.eventVal == 6 ||
                this.planInfo.eventVal == 9
            ) {
                this.selectedPlan = planInfo;
                this.areaModle = true;
                return;
            }
            if (
                this.planInfo.eventVal == 5 ||
                this.planInfo.eventVal == 4 ||
                this.planInfo.eventVal == 8
            ) {
                planInfo.param = JSON.stringify(this.timeRange);
            }

            console.log(planInfo, 9999);
            this.$http
                .post(
                    "wap/alarm/plan/save",
                    { ...planInfo },
                    {
                        header: {
                            "Content-Type": "application/json",
                            token: uni.getStorageSync("tokenValue") || "",
                        },
                    }
                )
                .then((res) => {
                    if (res.data.code == 200) {
                        uni.showToast({
                            title: "修改成功",
                            icon: "success",
                        });
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1,
                            });
                        }, 1000);
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: "none",
                            duration: 1500,
                        });
                    }
                    // if (
                    //     this.planInfo.eventVal == 1 ||
                    //     this.planInfo.eventVal == 2 ||
                    //     this.planInfo.eventVal == 3 ||
                    //     this.planInfo.eventVal == 9
                    // ) {
                    //     uni.showModal({
                    //         title: "提示",
                    //         content: "该计划需要到web端配置区域",
                    //         success: (res) => {
                    //             if (res.confirm) {
                    //             }
                    //             if (res.cancel) {
                    //             }
                    //         },
                    //     });
                    // }
                });
        },
        handlePlanInfo() {
            console.log(this.planInfo, 9999999);
        },
        getWarnType() {
            this.$http.get("wap/stats/queryEventType").then((res) => {
                if (res.data.data) {
                    this.warmTypeList = res.data.data;
                    this.eventType = this.warmTypeList.find(
                        (item) => item.eventVal == this.planInfo.eventVal
                    );
                }
            });
        },
        bindStartChange(val) {
            this.startDate = val.detail.value;
            this.planInfo.startDate = this.startDate + " 00:00:00";
        },
        bindEndChange(val) {
            this.stopDate = val.detail.value;
            this.planInfo.stopDate = this.stopDate + " 23:59:59";
        },
        bindEffectiveStartChange(val) {
            this.effectiveStart = val.detail.value;
            console.log(this.effectiveStart, val.detail.value, 88887);
        },
        bindEffectiveEndChange(val) {
            this.effectiveEnd = val.detail.value;
            console.log(this.effectiveEnd, 9999);
            this.timeRange.push({
                start_time: this.effectiveStart,
                end_time: this.effectiveEnd,
            });
        },
        removeTime(index) {
            this.timeRange.splice(index, 1);
        },
        onChangeLian(e) {
            let newValue = e.detail.value == true ? 1 : 0;
            this.linkagePushWechatService = newValue.toString();
        },
        onChangeQi(e) {
            let newValue = e.detail.value == true ? 1 : 0;
            this.enable = newValue.toString();
        },
        getdevRoomInfo(devId) {
            this.$http
                .get(`wap/room/readRoom`, {
                    devId: devId,
                })
                .then((res) => {
                    if (res.data.data) {
                        this.modules = res.data.data.furnitures;
                    }
                });
        },

        onTouchMove(event) {
            const currentX = event.touches[0].clientX;
            const currentY = event.touches[0].clientY;
            const deltaX = currentX - this.startX;
            const deltaY = currentY - this.startY;
            this.areaModLeLeft = this.initLeft + deltaX;
            this.areaModLeTop = this.initTop + deltaY;
            this.areaModLeX = Math.round(
                (this.devInfo?.xxStart || 0) +
                    event.currentTarget.offsetLeft * 2
            );
            this.areaModLeY = Math.round(
                (this.devInfo?.yyEnd || 0) - event.currentTarget.offsetTop * 2
            );
        },
        onTouchStart(event) {
            this.startX = event.touches[0].clientX;
            this.startY = event.touches[0].clientY;
            this.initTop = this.areaModLeTop;
            this.initLeft = this.areaModLeLeft;
        },
        onTouchEnd(index, event) {},
    },
    onLoad(options) {
        this.planInfo = JSON.parse(options.planInfo);
        this.devInfo = JSON.parse(options.devInfo);

        this.width = Math.abs(this.devInfo.yyEnd - this.devInfo.yyStart) * 100;
        this.length = Math.abs(this.devInfo.xxEnd - this.devInfo.xxStart) * 100;

        this.xOffset = (this.devInfo.xxStart + this.devInfo.xxEnd) * 50;
        this.yOffset = -(this.devInfo.yyStart + this.devInfo.yyEnd) * 50;

        console.log(this.xOffset, this.yOffset, 9999);
        console.log(this.devInfo, 9999999);

        this.getdevRoomInfo(this.devInfo.devId);
        this.startDate =
            this.planInfo?.alarmTimePlan.startDate?.slice(0, 10) || "";
        this.stopDate =
            this.planInfo?.alarmTimePlan.stopDate?.slice(0, 10) || "";

        if (this.planInfo.alarmTimePlan.timeRange) {
            this.timeRange = JSON.parse(this.planInfo.alarmTimePlan.timeRange);
        }
        this.eventType = this.planInfo.eventVal;
        this.linkagePushWechatService = this.planInfo.linkagePushWechatService;
        this.enable = this.planInfo.enable;

        if (this.eventType == 4 || this.eventType == 6 || this.eventType == 8) {
            this.judgeFlage = "noneFlag";
        } else if (this.eventType == 5 || this.eventType == 7) {
            this.judgeFlage = "one";
        } else if (
            this.eventType == 1 ||
            this.eventType == 2 ||
            this.eventType == 3 ||
            this.eventType == 9
        ) {
            this.judgeFlage = "more";
        }
    },
    onShow() {
        this.linkagePushWechatService =
            this.planInfo.linkagePushWechatService == 1 ? true : false;
        this.enable = this.planInfo.enable == 1 ? true : false;
        this.getWarnType();
    },
};
</script>

<style scoped>
.container {
    padding: 20px;
    height: 100vh;
    background-color: #f9eee3;
    border-radius: 12px;
}
.input-container {
    margin-bottom: 25px;
}
.input-label {
    font-size: 16px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 600;
}
.time-picker-container {
    margin-top: 20rpx;
    align-items: center;
    display: flex;
    justify-content: space-between;
}
.input-field {
    width: 92%;
    padding: 14px;
    margin-top: 20rpx;
    border: 1px solid #ccc;
    border-radius: 10px;
    font-size: 16px;
    background-color: #fff;
}
.input-counter {
    font-size: 12px;
    color: #999;
    text-align: right;
    margin-top: 4px;
}
.select-container {
    margin-bottom: 25px;
}
.picker-content {
    padding: 14px;
    border: 1px solid #ccc;
    border-radius: 10px;
    font-size: 16px;
    color: #333;
    background-color: #fff;
}
.time-range-wrapper {
    margin-top: 20rpx;
    display: flex;
    flex-wrap: wrap; /* 多行换行显示 */
    gap: 10rpx; /* 间距 */
    padding: 10rpx;
}

.time-item {
    position: relative;
    display: flex;
    align-items: center;
    padding: 10rpx 20rpx;
    background-color: #f5f5f5;
    border-radius: 12rpx;
}

.time-text {
    font-size: 28rpx;
    color: #333;
}

.delete-btn {
    position: absolute;
    top: -6rpx;
    right: -6rpx;
    width: 30rpx;
    height: 30rpx;
    line-height: 30rpx;
    text-align: center;
    background-color: #ff4d4f;
    color: #fff;
    border-radius: 50%;
    font-weight: bold;
    font-size: 20rpx;
}

.switch-container {
    margin-bottom: 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 新的保存按钮样式 */
.save-button {
    width: 750rpx;
    height: 120rpx;
    position: fixed;
    display: flex;
    justify-content: center;
    align-items: center;
    bottom: 0;
    left: 0;
    line-height: 120rpx;
    background: #f3e2dd;
    border-radius: 12px;
}
.save-button-text {
    font-size: 18px;
    /* font-weight: bold; */
}
.areaModleClass {
    z-index: 111;
    position: absolute;
    width: 650rpx;
    padding: 20rpx 0;
    /* height: 650rpx; */
    top: -8%;
    left: -37%;
    background: #fff;
    transform: translate(50%, 50%);
    border-radius: 12px;
}
.airCantInfo {
    background-image: url("https://hflnxx.oss-cn-shanghai.aliyuncs.com/IMAGE/20250919/toilet_bg.png");
    margin: 0 auto 0 auto;
    border: 18rpx solid #1f1f1f;
    position: relative;
}
.airCantInfo .module-content > view {
    position: absolute;
}
.airCantInfo .areaModleArea {
    border: 2rpx solid #000;
    background: #f8efe4;
    position: absolute;
}
</style>
