import $ from "../../utils/Tool";
import router from "../../utils/router";
import {
    getSetting,
    getLocation,
    checkHasLogined,
    authlogin,
} from "../../utils/auth";
const AUTH = require("../../utils/auth");
import icons from "../../utils/icon";
import { getUrlParams } from '../../utils/util'
import Toast from "../../vant-weapp/dist/toast/toast";
import {
    getopenId,
    comfirmCodeLogin,
    userCheck,
    getSpaceAdjustList,
    spaceTop,
    getWeather,
    deleteSpaceAdjust,
    queryUseranswer,
    getCurrentSeason,
    powerCheck,
    openSpace,
} from "../../requests/api";
var refreshTimer = null;
Page({
    data: {
        surveyShow: false, //是否显示调查问卷
        lottieShow: true, //是否显示lottie组件
        meauList: [
            {
                id: 1,
                title: "扫码调节",
                des: "扫描空间二维码",
                imgSrc: "../../static/images/qrcode.png",
            },
            {
                id: 2,
                title: "空间列表",
                des: "查找更多空间",
                imgSrc: "../../static/images/adjust.png",
            },
        ],
        envNamelist: $.store.get("envNamelist"),
        imgbaseUrl: $.store.get("imgbaseUrl"),
        picInitUrl: $.store.get("picInitUrl"),
        latitude: null,
        longitude: null,
        noDate: true,
        statusList: icons.statusList,
        spacestatusList: icons.spacestatusList,
        cardList: [],
        cardCurrent: null,
        tenantName: $.store.get("tenantName"),
        tenants: $.store.get("tenants"),
        logined: $.storage.get("logined"),
        havePower: { result: "fail", message: "未定位到您的位置" },
        temperatureNum: "--",
        guideUser: false,
        CustomBar: $.store.get("CustomBar"),
    },
    toDetail(e) {
        if (!e.currentTarget.dataset.istemp) {
            router.push("detail", e.currentTarget.dataset);
        } else {
            router.push("detail", {
                name: "温度",
                localname: "温度",
                param: "temperature",
                funcid: "Tdb",
                spaceid: e.currentTarget.dataset.spaceid,
                projectid: e.currentTarget.dataset.projectid,
            });
        }
    },
    // 关闭问卷
    surveyClose(value) {
        this.setData({ surveyShow: false, lottieShow: true });

        if (value.detail.good) {
            wx.showToast({
                title: "感谢您的反馈",
                image: "../../static/images/bixin.png",
                duration: 2000,
            });
        }
    },
    // 检查是否需要填写问卷
    async userAnswer() {
        let day = new Date();
        let year = day.getFullYear();
        let month = day.getMonth() + 1;
        month = month < 10 ? "0" + month : month;
        let today = day.getDate();
        today = today < 10 ? "0" + today : today;
        let seasonType = "";
        const dataSeason = {
            projectId: $.store.get("projectId") || $.storage.get("projectId"),
            date: `${year}${month}${today}`,
        };
        await getCurrentSeason(dataSeason).then((res) => {
            if (res.result == "success") {
                seasonType = res.data;
            }
        });
        let projectId = $.store.get("projectId");
        let tenantId = $.store.get("tenantId");
        let data = {
            criteria: {
                userId: $.store.get("userId"),
                projectId: projectId,
                tenantId: tenantId,
                startTime: {
                    $ge: `${year}${month}${today}`,
                },
                endTime: {
                    $le: `${year}${month}${today}`,
                },
                seasonType: seasonType,
            },
        };
        queryUseranswer(data).then((res) => {
            !res.count &&
                !res.content &&
                this.setData({ surveyShow: true, lottieShow: false });
        });
    },
    // 检查是否过引导
    checkGuide(value) {
        if (!this.data.tenantName) {
            return;
        }
        !$.storage.get("guideUser") &&
            !value &&
            !$.storage.get("nextRemind") &&
            this.userAnswer();
        !$.storage.get("guideUser") && this.getPageheight();
        this.setData({ guideUser: !$.storage.get("guideUser") });
    },
    // 步骤引导函数
    nextStep(e) {
        $.storage.set("guideUser", true);
        this.setData({ guideUser: false });
    },
    // 获取容器高度
    getPageheight() {
        let that = this;
        wx.createSelectorQuery()
            .select("#j_page")
            .boundingClientRect(function (rect) {
                that.setData({ pageHight: rect.height });
            })
            .exec();
    },
    swipeClick(e) {
        let that = this;
        let { spaceid } = e.currentTarget.dataset;
        wx.showModal({
            title: "删除",
            content: "是否删除该空间",
            success(res) {
                if (res.confirm) {
                    let data = {
                        projectId: $.store.get("projectId"),
                        userId: $.store.get("userId"),
                        spaceId: spaceid,
                    };
                    deleteSpaceAdjust(data).then((res) => {
                        that.getData();
                    });
                }
            },
        });
    },
    // 置顶操作
    tapItem(e) {
        let { id, top, projectId } = e.currentTarget.dataset.spaceid;
        let spaceIndex = e.currentTarget.dataset.index;
        let data = {
            projectId: projectId,
            spaceId: id,
            userId: this.data.userId,
            top: top ? 0 : 1,
        };
        spaceTop(data).then(async (res) => {
            if (res.result == "success") {
                await this.getData();
                wx.pageScrollTo({
                    scrollTop: 0,
                    duration: 300,
                });
            }
        });
    },
    settingLocation() {
        return new Promise((relove, reject) => {
            wx.showModal({
                title: "是否授权当前位置",
                content: "需要获取您的地理位置,请确认授权",
                confirmColor: "#f16765",
                success: (res) => {
                    relove(res);
                },
                fail: (err) => {
                    reject(err);
                },
            });
        });
    },
    async isGetSetting(value) {
        let { authSetting } = await getSetting();
        if (authSetting["scope.userLocation"]) {
            await this.getUserLocation();
        } else {
            await this.settingLocation().then((res) => {
                if (res.confirm) {
                    wx.openSetting({
                        success: async (data) => {
                            await this.getUserLocation();
                            value && this.remoteCheck();
                        },
                    });
                } else {
                    this.setData({
                        havePower: {
                            result: "fail",
                            message: "未定位到您的位置",
                        },
                    });
                }
            });
        }
    },
    // 获取位置信息
    async getUserLocation(cb) {
        var that = this;
        let { latitude, longitude } = await getLocation();
        this.setData({ latitude, longitude });
    },
    // 检查是否注册 是否远程调节
    async remoteCheck() {
        // if($.storage.get('wxqcode')){
        //   return
        // }
        var that = this;
        await this.isGetSetting("cb").then(async (res) => {
            if (this.data.longitude) {
                await userCheck({
                    longitude: that.data.longitude,
                    latitude: that.data.latitude,
                }).then(async (res) => {
                    if (res.result === "fail") {
                        // && !that.data.formAuth
                        $.storage.set("logined", false);
                        this.setData({ logined: false });
                        router.push("auth");
                    } else {
                        await that.getTenant(res);
                        // 第一次进入获取数据
                        // console.log($.storage.get('wxqcode'),"$.storage.get('wxqcode')")
                        !$.storage.get("wxqcode") && that.getData();
                        !$.storage.get("wxqcode") &&
                            that.autoRefresh(this.getData);
                        if (
                            $.storage.get("wxqcode") &&
                            $.storage.get("logined")
                        ) {
                            this.checkCode($.storage.get("wxqcode"));
                        }
                    }
                });
            }
        });
    },
    getTenant(res) {
        // 存入全局
        $.store.set("userInfo", res.content);
        return new Promise(async (resolve, reject) => {
            !$.store.get("openId") && $.store.set("openId", res.content.openId);
            !$.store.get("userId") && $.store.set("userId", res.content.id);
            $.store.set("tenants", res.content.tenants);
            // 检查定位哪个租户 优先定位 再根据最近使用
            let currentTenant = await this.checkTenant(res.content.tenants);
            $.store.set("projectId", currentTenant.projectId);
            $.store.set("tenantId", currentTenant.tenantId);
            $.store.set("tenantName", currentTenant.tenantName);

            // 存入Storage
            !$.store.get("logined") && $.storage.set("logined", true);
            this.setData({ logined: true });
            !$.storage.get("openId") &&
                $.storage.set("openId", res.content.openId);
            !$.storage.get("userId") && $.storage.set("userId", res.content.id);
            $.storage.set("projectId", currentTenant.projectId);
            $.storage.set("tenantId", currentTenant.tenantId);
            $.storage.set("tenantName", currentTenant.tenantName);

            this.setData({
                projectId: $.store.get("projectId"),
                tenantId: $.store.get("tenantId"),
                tenantName: $.store.get("tenantName"),
                tenants: $.store.get("tenants"),
                userId: $.store.get("userId"),
            });
            // if (this.data.wxqcode) {
            //   this.checkCode(this.data.wxqcode);
            //   this.setData({
            //     formWxcode: false
            //   });
            // }
            resolve();
        });
    },
    // 查询定位租户
    checkTenant(value = []) {
        // 首先默认选中的是定位的租户,如果小程序定位的位置就是要调节的租户对应的空间(定位距离租户200m以内),直接调节;
        return new Promise((resolve, reject) => {
            const currntProjectId = $.storage.get("projectId");
            const currntProjecttenantId = $.storage.get("tenantId");
            const currntProjecttenantName = $.storage.get("tenantName");
            let current = {};
            if ($.store.get("changeTenantId")) {
                value.length &&
                    value.forEach((item) => {
                        if (item.tenantId === currntProjecttenantId) {
                            current.projectId = item.projectId;
                            current.tenantId = item.tenantId;
                            current.tenantName = item.tenantName;
                        }
                    });
                $.store.set("changeTenantId", false);
            } else if ($.store.get("goHome")) {
                $.store.set("goHome", false);
                current.projectId = $.store.get("projectId");
                current.tenantId = $.store.get("tenantId");
                current.tenantName = $.store.get("tenantName");
            } else if (value.length) {
                // 定位到的租户id
                var currentTens = [];
                // 定位到的租户详情 可能多个
                var currentTensArr = [];
                value.forEach((item) => {
                    if (item.current) {
                        currentTens.push(item.tenantId);
                        currentTensArr.push(item);
                    }
                });
                if (currentTens.length) {
                    // 最近使用不包含定位 且没有手动切换项目
                    if (
                        !currentTens.includes(currntProjecttenantId) &&
                        !this.data.formList
                    ) {
                        //定位改变 但不是通过调节改变  切换改变
                        current = currentTensArr[0];
                    } else if (currentTens.includes(currntProjecttenantId)) {
                        currentTensArr.forEach((item) => {
                            if (item.tenantId === currntProjecttenantId) {
                                current.projectId = item.projectId;
                                current.tenantId = item.tenantId;
                                current.tenantName = item.tenantName;
                            }
                        });
                    }
                } else {
                    if (currntProjecttenantId != "") {
                        current.projectId = currntProjectId;
                        current.tenantId = currntProjecttenantId;
                        current.tenantName = currntProjecttenantName;
                    } else {
                        current = value[0];
                    }
                }
            } else {
                current.projectId = currntProjectId;
                current.tenantId = currntProjecttenantId;
                current.tenantName = currntProjecttenantName;
            }

            resolve(current);
        });
    },
    // 个人中心
    gotoUser() {
        router.push("usercenter");
    },
    // 自动刷新
    autoRefresh(fn) {
        if (refreshTimer) {
            this.clearTimer()
        }
        let refreshTime = $.store.get("autoRefreshTime");
        refreshTimer = setInterval(() => {
            fn();
            //   this.autoRefresh(fn);
        }, refreshTime);
    },
    /**
     * 获取页面服务端数据
     */
    async getData() {
        // $.loading()
        let userId = $.store.get("userId") || $.storage.get("userId");
        if (!userId) {
            return;
        }
        // wx.showLoading({
        //   title:"加载中"
        // })
        const data = {
            criteria: {
                userId: userId,
                projectId:
                    $.store.get("projectId") || $.storage.get("projectId"),
                tenantId: $.store.get("tenantId") || $.storage.get("tenantId"),
            },
        };
        // let res = await queryRotation(data);
        let res = await getSpaceAdjustList(data);
        if (res.count) {
            res.content.forEach((item) => {
                (item.humidity || item.humidity == 0) &&
                    (item.humiditylevel = this.checkLevel(
                        item.humidity,
                        "humidity"
                    ));
                (item.co2 || item.co2 == 0) &&
                    (item.co2level = this.checkLevel(item.co2, "co2"));
                (item.pm25 || item.pm25 == 0) &&
                    (item.pm25level = this.checkLevel(item.pm25, "pm25"));
                (item.hcho || item.hcho == 0) &&
                    (item.hcholevel = this.checkLevel(item.hcho, "hcho"));
                if (typeof item.isPassengerPass === "undefined") {
                    item.isPassengerPassShow = false;
                } else {
                    item.isPassengerPassShow = true;
                    item.isPassengerPass = item.isPassengerPass
                        ? "有人"
                        : "无人";
                }
            });
            this.setData({ cardList: res.content });
        } else {
            this.setData({ noDate: true, cardList: [] });
        }
        // wx.hideLoading()
        // $.hideLoading()
    },
    checkLevel(value, name) {
        let objList = {
            humidity: {
                range: [30, 70],
                text: ["干燥", "适宜", "湿润"],
            },
            co2: {
                range: [800, 1500],
                text: ["适宜", "偏高", "超标"],
            },
            pm25: {
                range: [35, 75],
                text: ["优", "良", "差"],
            },
            hcho: {
                range: [0.08, 0.1],
                text: ["适宜", "偏高", "超标"],
            },
        };
        let sortArr = [value, ...objList[name].range].sort((a, b) => {
            return a - b;
        });

        let level = sortArr.findIndex((item) => item === value);
        let levelTxt = objList[name].text[level];
        return { level, levelTxt };
    },
    /**
     * 去立即调节页面
     */
    goToadjust(e) {
        let index = e.target.dataset.index;
        let data = this.data.cardList[index];
        data.outLine && (data.outLine = "");
        router.push("adjust", data);
    },
    meauClick(e) {
        if (e.currentTarget.dataset.index === 1) {
            this.getScancode();
        } else {
            this.gotoSpacelist();
        }
    },
    // 获取扫码结果
    getScancode: function () {
        // if (!$.storage.get('logined')) {
        //   router.push('auth');
        //   return
        // }
        // 只允许从相机扫码
        wx.scanCode({
            onlyFromCamera: true,
            complete: (res) => {
                if (res.errMsg === '"scanCode:fail cancel"') {
                    Toast.fail("已取消扫描");
                }
            },
            success: (res) => {
                // let result = res.result
                this.checkCode(res.result);
            },
            fail: (res) => {
                Toast.fail("未扫描到结果");
            },
        });
    },
    gotoSpacelist() {
        router.push("spacelist");
        // router.push("ipdauth")
    },
    // 检查二维码
    async checkCode(value) {
        // debugger
        console.log(value, 381);
        let scanArr = value.split("?");
        let domain = scanArr[0];
        let qualifiedUrl = [
            "http://meos.sagacloud.cn/scan",
            "https://duoduoenv.sagacloud.cn/scan",
            "http://39.106.8.246:8008/sgipad/home"
        ];
        let type = getUrlParams(scanArr[1], 'type')
        // debugger
        if (qualifiedUrl.includes(domain)) {
            let md = scanArr[1].split("=") || [];
            let md1 = md[1];
            console.log("扫码了====")
            // router.push("adjust", { md1 });
            // debugger
            if (type === 'ipad') {
                this.confirmLogin(scanArr[1])
            } else {
                router.push("adjust", { md1 });
            }
        } else {
            Toast.fail("无效的二维码");
        }
    },
    confirmLogin(value) {
        let id = getUrlParams(value, 'id')
        let mac = getUrlParams(value, 'mac')
        let projectId = $.store.get("projectId") || $.storage.get("projectId")
        let param = {
            qrCodeId: id,
            macAddress: mac,
            status: 1,  // 0-未扫码 1-已扫描 2-已确认 3-已经失效
            projectId: projectId
        }
        comfirmCodeLogin(param).then(res => {
            if(res.result==='success'){
                router.push("ipdauth", { 'id': id, 'mac': mac })
            }else{
                Toast.fail(res.message);
            }
        }).catch(() => {
            Toast.fail("无效的二维码");
            // router.push("ipdauth", { 'id': id, 'mac': mac })
        })
    },
    async userLogin() {
        let that = this;
        let isLogined = await checkHasLogined();
        if (!isLogined) {
            await authlogin().then(async (result) => {
                await getopenId(result.code).then(async (res) => {
                    $.storage.set("openId", res.openId);
                    $.store.set("openId", res.openId);
                    await this.remoteCheck();
                });
            });
        } else {
            await this.remoteCheck();
        }
    },
    chooseTenant(e) {
        if ($.store.get("tenants").length <= 1) {
            return;
        }
        router.push("projectlist");
    },
    async inItUserdate() {
        // 用户登录
        await this.userLogin();
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        // 是否从微信直接进来
        if (options.q !== undefined) {
            let q = decodeURIComponent(options.q);
            // let q="https://duoduoenv.sagacloud.cn/scan?key=Sp110108025988e09ed4cd8c45b5a496f18622ab81ca";
            $.storage.set("wxqcode", q);
            // console.log($.storage.get('wxqcode'),"123")
        }
        $.storage.set("nextRemind", false);
        await this.inItUserdate();
        console.log($.storage.get("wxqcode"), $.storage.get("logined"), "449");
        // if($.storage.get('wxqcode')&&$.storage.get('logined')){
        //   this.checkCode($.storage.get('wxqcode'));
        // }
        this.getWeatherNum();
        this.checkGuide(options.q);
        // 加载数据
        // this.getData();
    },
    getWeatherNum() {
        let data = {
            projectId: $.store.get("projectId"),
        };
        getWeather(data).then((res) => {
            if (res.content) {
                this.setData({ temperatureNum: res.content.temperature });
            }
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        // await this.inItUserdate();
        if (
            $.storage.get("tenantId") &&
            !$.store.get("changeTenantId") &&
            !this.data.formList
        ) {
            this.getData();
            this.autoRefresh(this.getData);
        }

        if (this.data.formList) {
            this.setData(
                {
                    tenantName: $.store.get("tenantName"),
                    tenantId: $.store.get("tenantId"),
                    projectId: $.store.get("projectId"),
                    formList: false,
                },
                () => {
                    this.getData();
                    this.getWeatherNum();
                    this.userAnswer();
                }
            );
        }
        if ($.store.get("changeTenantId")) {
            await this.remoteCheck();
            this.getWeatherNum();
            this.checkGuide();
        }
    },
    clearTimer() {
        clearInterval(refreshTimer);
        refreshTimer = null;
    },
    onHide() {
        this.clearTimer();
    },
    onUnload() {
        this.clearTimer();
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        $.store.set("goHome", true);
        await this.remoteCheck();
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () { },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () { },
});