import React from 'react';

import {
  Anchor,
  message,
} from 'antd';
import classNames from 'classnames';
import { encode } from 'js-base64';
import Cookies from 'js-cookie';

import CitySelector from '../components/CitySelector';
import Login from '../pages/user/login/login';
import cityJson from './city.json';
import styles from './UserLayout.less';

const { Link } = Anchor;

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

    init(config) {
        // this.initWeatherCity();
    }

    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() {
        const loginName = this.globalConfig.userInfo.loginName;
        const self = this;
        return new Promise((resolve, reject) => {
            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 = [];
                    self.showStations = []
                    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) {
                        self.currentStationName = arr[arr.length - 1];
                        self.citySelector = self.AvailableofRegionName(projectStation);
                        self.siteCityList = self.buildCitySelectTemple(projectStation);
                    }
                    //只有演示环境出现友好提示
                    if (allStation.length === self.showStations.length) {
                        self.isOnlyDisplay = true;
                    } else {
                        self.citySelector = self.AvailableofRegionName(projectStation);
                        self.siteCityList = self.buildCitySelectTemple(projectStation);
                    }

                    self.updateConfig && self.updateConfig(self.globalConfig)
                    
                    const stations = self.insertYSStation();
    
                    if(city) {
                        Http.getWeather({
                            city: city,
                            'request.preventCache': new Date().getTime()
                        },{
                            ignoreSite: true
                        }).then(res => {
                            if(res.say.statusCode === ERR_OK) {
                                const firtValue = res.getMe[0];
                                console.log("firtValue", firtValue)
                                if(firtValue.cityName) {
                                    const text = firtValue.forcastFirst.split(' ')[1];
                                    const imgPath = firtValue.presentPictureFirst.replace('gif', 'svg')
                                    resolve({
                                        stations: stations,
                                        weathers: {
                                            icon: `https://panda-water.cn/web4/assets/images/weather2/${imgPath}`,
                                            text: firtValue.temperatureFirst
                                        },
                                        siteCityList: self.siteCityList,
                                        citySelector: self.citySelector,
                                        currentStationName: self.currentStationName
                                    })
                                }
                            } else {
                                resolve({
                                    stations: stations,
                                    siteCityList: self.siteCityList,
                                    citySelector: self.citySelector,
                                    currentStationName: self.currentStationName,
                                    weathers: {}
                                })
                            }
                        }).catch(error => {
                            resolve({
                                stations: stations,
                                currentStationName: self.currentStationName,
                                weathers: {},
                                siteCityList: self.siteCityList,
                                citySelector: self.citySelector,
                            })
                        })
                    } else {
                       resolve({
                            stations: stations,
                            currentStationName: self.currentStationName,
                            weathers: {},
                            siteCityList: self.siteCityList,
                            citySelector: self.citySelector,
                       })
                    }
                }
            })
        })
    }

    insertYSStation() {
        const hot = ["HOT", "县", "市", "New"];
        this.showStations.sort((a, b) => a.promoteIndex - b.promoteIndex);
        return this.showStations.map((item, index) => {
            let marginRight = 20
            let style = {};
            switch(item.promoteTip) {
                case hot[3]:
                case hot[0]: 
                    marginRight = 40;
                    break;
                case hot[1]:
                case hot[2]:
                    marginRight = 30;
                    break;
                default:
                    marginRight = 20;
                    break;           
            }
            style.marginRight = marginRight
            item.style = style
            if(item.promoteTip && hot.includes(item.promoteTip)) {
                item.promoteTip = item.promoteTip
            } else if(index === this.showStations.length){
                item.style.marginRight = "-20px"
            }
            return item
        })
    }

    getNumberofRegion(data, index) {
        let arr = [], pNames = [];
        for (let i = 0; i < data.length; i++) {
            const pName = data[i].city.split('/')[index];
            if (pNames.indexOf(pName) < 0) {
                pNames.push(pName);
            }
        }

        pNames.forEach((item, index) => {
            arr[arr.length] = {
                proviceName: item,
                num: 0
            }
        })

        for (let j = 0; j < data.length; j++) {
            const itemJ = data[j];
            const itemJ_pName = itemJ.city.split("/")[index];
            for (let k = 0; k < arr.length; k++) {
                const itemK = arr[k];
                if (itemJ_pName === itemK.proviceName) {
                    arr[k].num++;
                }
            }
        }
        return arr;
    }

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

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

        const loginSite = this.getLocalSites()
        loginSite[token] = site
        localStorage.setItem("loginSite", JSON.stringify(loginSite));
        const login = new Login(this.props, () => {
            window.location.reload();
        });
        login.init()
        

    }

    changeGroup(event, item) {
        event.persist();
        const site = item ? item.site : event.target.dataset.site
        const loginName = this.globalConfig.userInfo.loginName
        Http.generateTokenQuick({
            loginName: loginName
        }, {
            ignoreSite: true
        }).then(res => {
            const token = res.token
            if(token) {
                this.beforeChangeCheck(token, site)
            }
        }).catch(error => {
            message.warning("切换企业失败")
        })
    }

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

    pySegSort (data) {
        if (!String.prototype.localeCompare)
            return null;
        let letters;
        let segs = []; // 存放数据
        let py = []; // 存放首字母
        let res = {};
        letters = "ABCDEFGHJKLMNOPQRSTWXYZ".split('');
        const ref = {
            "A": {
                pName: ['安徽省'],
                data: []
            },
            'B': {
                pName: ['北京市'],
                data: []
            },
            'C': {
                pName: ['重庆市'],
                data: []
            },
            "F": {
                pName: ['福建省'],
                data: []
            },
            "G": {
                pName: ["甘肃省", "广东省", "广西壮族自治区", "贵州省"],
                data: []
            },
            "H": {
                pName: ["海南省", "河北省", "河南省", "黑龙江省", "湖北省", "湖南省"],
                data: []
            },
            "J": {
                pName: ["吉林省", "江苏省", "江西省"],
                data: []
            },
            "L": {
                pName: ["辽宁省",],
                data: []
            },
            "N": {
                pName: ["内蒙古自治区", "宁夏回族自治区"],
                data: []
            },
            "Q": {
                pName: ["青海省"],
                data: []
            },
            "S": {
                pName: ["山东省", "山西省", "陕西省", "上海市", "四川省"],
                data: []
            },
            'T': {
                pName: ['天津市'],
                data: []
            },
            "X": {
                pName: ["新疆维吾尔自治区", "西藏藏族自治区"],
                data: []
            },
            "Y": {
                pName: ["云南省"],
                data: []
            },
            "Z": {
                pName: ["浙江省"],
                data: []
            }
        }
        data.map((item) => {
            var proviceName = item.proviceName
            for (let key in ref) {
                if (ref[key].pName.includes(proviceName)) {
                    ref[key].data.push(item);
                    break;
                }
            }
        })
        letters.map((item) => {
            if (ref[item] && ref[item].data.length) {
                py.push(item);
                segs.push({
                    letter: item,
                    data: ref[item].data
                })
            }
        })
        res["segs"] = segs;
        res["py"] = py;
        return res;
    }

    handEnd = (event, item) => {
        debugger
        event.persist();
        const self = this;
        if(item) {
            Http.generateTokenQuick({
                loginName: self.globalConfig.userInfo.loginName
            }, {
                ignoreSite: true
            }).then(res => {
                const token = res.token;
                if(token) {
                    self.beforeChangeCheck(token, item.site)
                }
            }).catch(error => {
                console.log(error);
                message.warning("切换企业失败")
            })
        }
    }

    AvailableofRegionName(data) {
        const options = {
            proviceOption: this.getNumberofRegion(data, 0),
            cityOption: this.getNumberofRegion(data, 1),
            siteOption: data
        }
        return (
            <CitySelector simple={true} Clickable={options} handEnd={(event, item) => this.handEnd(event, item)}/>
        )

    }

    buildCitySelectTemple(data) {
        let arr = [];
        let pNames = [];
        for (var i = 0; i < data.length; i++) {
            var pName = data[i].city.split('/')[0];
            if (pNames.indexOf(pName) < 0) {
                pNames.push(pName);
            }
        }

        pNames.forEach((item, index) => {
            arr[arr.length] = {
                proviceName: item,
                stations: []
            }
        })

        for (let j = 0; j < data.length; j++) {
            const itemJ = data[j];
            const itemJ_pName = itemJ.city.split("/")[0];
            for (var k = 0; k < arr.length; k++) {
                var itemK = arr[k];
                if (itemJ_pName == itemK.proviceName) {
                    arr[k].stations[itemK.stations.length] = {
                        stationID: itemJ.groupID,
                        site: itemJ.site,
                        cityName: itemJ.city,
                        groupName: itemJ.groupName,
                        isDeployed: itemJ.isDeployed
                    }
                }
            }
        }

        const cities = this.pySegSort(arr);


        let letters = [];

        for(let i = 0; i < cities.py.length; i++) {
            letters.push(
                <li key={cities.py[i][0]}>
                    <Link className={styles.cityLetter} href={`#${cities.py[i][0]}`} dataHref={cities.py[i][0]} title={cities.py[i][0]}/>
                </li>
            )
        }
        let children = [];
        for (var j = 0; j < cities.segs.length; j++) {
            const item = cities.segs[j];

            children.push(
                <div key={item.letter}>
                    <a className={styles.letter} dataName={item.letter} href={`${item.letter}`} title={item.letter} id={item.letter}>{item.letter}</a>
                    {
                        item.data.map((k, i) => {
                            const city = k;
                            let pName = "";
                            if (city.proviceName.indexOf('黑龙江' || '内蒙古') < 0) {
                                pName = city.proviceName.substr(0, 2);
                            } else {
                                pName = city.proviceName.substr(0, 3);
                            }
                            return (
                                <div className={styles.Provice} key={i}>
                                    <span className={styles.proviceName}>{pName}</span>
                                    <ul className={styles.city_list}>
                                        {
                                            city.stations.map((item, index) => {
                                                // const flag = item;
                                                // const cityArr = flag.cityName.split("/");
                                                return (
                                                    <li key={index}>
                                                        <a className={ classNames(styles.city_select, !item.isDeployed ? styles.noData: '')}  title={item.cityName} onClick={(event) => this.changeGroup(event, item)}>{item.groupName}</a>
                                                    </li>
                                                )
                                            })
                                        }
                                    </ul>
                                </div>
                            )
                        })
                    }
                </div>
            )
        }
        return {
            letters: letters,
            content: children
        }
    }

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

export default Site;