import { message } from 'antd';
import Cookies from 'js-cookie';

import cityJson from './city.json';

const ERR_OK = '0000'
class Site {
    constructor(props) {
        this.weatherCity = null
        this.globalConfig = props.global
    }

    init(config) {
        
    }

    initWeatherCity() {
        try {
            if(navigator.onLine && this.globalConfig && this.globalConfig.userInfo && this.globalConfig.userInfo.site) {
                http.getCity().then(res => {
                    if(res && !isNaN(res.cid)) {
                        const cityResult = JSON.parse(cityJson);
                        const city = cityResult[res.cid];
                        this.weatherCity = city ? city: null;
                    }
                })
            }
        }catch(e) {
            console.error(e)
        }
    }

    getCityStationsForUser() {
        debugger
        const loginName = this.globalConfig.userInfo.loginName;
        const self = this;
        Http.getAllGroupsInfoForUser({
            loginName: loginName,
            'request.preventCache': new Date().getTime()
        }, {
            ignoreSite: true
        }).then(res => {
            debugger
            if(res && res.say.errMsg === '' && res.say.statusCode === ERR_OK) {
                const result = res.getMe;
                let city = self.weatherCity;
                let arr = [];
                self.globalConfig.userInfo.groupType = ""
                self.globalConfig.userInfo.Groups = res.getMe;
                self.globalConfig.userInfo.Industries = new Array;
                if (self.globalConfig.userInfo.Groups && self.globalConfig.userInfo.Groups.length) {
                    self.globalConfig.userInfo.Groups.forEach(group => {
                        if (group.industry && self.globalConfig.userInfo.Industries.indexOf(group.industry) < 0) self.globalConfig.userInfo.Industries.push(group.industry);
                    });
                }
                if (self.globalConfig.userInfo && self.globalConfig.userInfo.site && self.globalConfig.userInfo.Groups && self.globalConfig.userInfo.Groups.length) {
                    var _indestryItem = self.globalConfig.userInfo.Groups.find(item => {
                        return item.site == self.globalConfig.userInfo.site;
                    });
                    if (_indestryItem && _indestryItem.industry) {
                        self.globalConfig.Industry = _indestryItem.industry;
                    }
                }

                let allStation = [];
                let projectStation = [];
                debugger
                if (self.globalConfig.Industry) {
                    
                    allStation = result.filter((item) => {
                        return item.industry == self.globalConfig.Industry;
                    })
                    self.showStations = allStation.filter((item) => {
                        return item.promoteIndex && item.promoteIndex > 0;
                    });
                    projectStation = allStation.filter((item) => {
                        return !item.promoteIndex;
                    })
                } else {
                    allStation = result;
                }

                if (allStation.length) {
                    let allChoice = false;
                    allStation.forEach( (val) => {
                        if (val.promoteIndex == 0) {
                            allChoice = true;
                        }
                    })
                    if (!allChoice) {
                        // me.$el.find('#changeCityWays').hide();
                        // me.$el.find('.LMBcityBox').hide();
                        // me.$el.find('div.cities').css('min-width', 'initial');
                        // me.$el.find('.focusStations').addClass('LMBcolumnList');
                    }
                    if (allStation.length > 120) {
                        // $(me.el).find("div.cities div.cityContent").css("height", '335px');
                    }
                    let _enterprise = null;
                    if (self.globalConfig.userInfo.site && self.globalConfig.userInfo.site.length) {
                        _enterprise = allStation.filter((enterprise) => {
                            return enterprise.site == self.globalConfig.userInfo.site;
                        });
                    }
                    if (_enterprise && _enterprise.length) {
                        if (_enterprise[0].groupName.indexOf("演示" >= 0)) {
                            arr[0] = _enterprise[0].groupName;
                        } else {
                            arr = _enterprise[0].city.split('/');
                        }
                        let tmp = _enterprise[0].city.split('/')[1];
                        city = tmp.substr(0, tmp.length - 1);
                        self.globalConfig.userInfo.groupType = _enterprise[0].groupType;
                    } else {
                        arr = allStation[0].city.split('/');
                        let tmp = arr[1];
                        city = tmp.substr(0, tmp.length - 1);
                        self.globalConfig.userInfo.groupType = allStation[0].groupType;
                    }
                }

                if (allStation.length > 1) {
                    let currentStationName = arr[arr.length - 1];
                    // $(me.el).find('span.city').html(currentStationName);
                    // $(me.el).find(".item").show();
                    // $(me.el).find("div.cityAndWeather span.Weather").css('border-left', '1px solid #aaa');
                    self.AvailableofRegionName(projectStation);
                    self.buildCitySelectTemple(projectStation);
                }
                //只有演示环境出现友好提示
                if (allStation.length == self.showStations.length) {
                    self.isOnlyDisplay = true;
                    // $(me.el).find(".city_pane").hide().siblings('.noStations').css('display', 'flex')
                } else {
                    self.AvailableofRegionName(projectStation);
                    self.buildCitySelectTemple(projectStation);
                }
                console.log("showStations", self.showStations)
                console.log("city", city)
                return city

                this.insertYSStation()


                // if(city) {
                //     Http.getWeather({
                //         city: city
                //     }).then(res => {
                //         if(res.say.statusCode === ERR_OK) {
                //             const firtValue = res.getMe[0];
                //             if(firtValue.cityName) {
                //                 const text = firtValue.forcastFirst.split(' ')[1];
                //                 const imgPath = firtValue.presentPictureFirst.replace('gif', 'svg')
                //                 return (
                //                     <>
                //                      <img src={`https://panda-water.cn/web4/assets/images/weather2/${imgPath}`}/>
                //                      <span>{text + "  " + firtValue.temperatureFirst}</span>
                //                     </>
                //                 )
                //             }
                //         }
                //     })
                // }
            }
        })
    }

    insertYSStation() {
        let list = [];
        const hot = ["HOT", "县", "市", "New"];
        this.showStations.sort((a, b) => a.promoteIndex - b.promoteIndex);
        
    }

    getNumberofRegion() {

    }

    AvailableofRegionName() {

    }

    writeCookie(tk, site) {
        const date = new Date();
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000)
        Cookies.set("token", tk, {
            expires: date.toGMTString(),
            path: "/"
        })

        const encodeSite = Base64.encode(encodeURIComponent(site));
        Cookies.set("site", encodeSite, {
            expires: date.toGMTString(),
            path: "/"
        })

        const loginSite = this.getLocalSites()
        loginSite[token] = site
        localStorage.setItem("loginSite", JSON.stringify(loginSite))
        // window.location.reload

    }

    changeGroup(event) {
        c
        Http.generateTokenQuick({
            loginName: this.globalConfig.userInfo.loginName
        }).then(res => {
            const token = res.token
            if(token) {
                this.beforeChangeCheck(token, "")
            }
        }).catch(error => {
            message.warning("切换企业失败")
        })
    }

    beforeChangeCheck(token, site) {
        Http.getUserInfo({
            token: token,
            subOID: 'subOID',
            site: site
        }).then(res => {
            if(res && !res.errMsg) {
                this.writeCookie(token, site)
            } else {
                message.warning('企业切换失败，请联系管理员排查问题！')
            }
        }).catch(e => {
            message.warning('企业切换失败，请联系管理员排查问题！')
        })
    }

    AvailableofRegionName() {}

    buildCitySelectTemple() {}

    getLocalSites() {
        const localSite = localStorage.getItem("loginSite"), value = {};
        if(localSite) {
            value = JSON.parse(localSite)
        }
        return value;
    }
}

export default Site;