import { message } from 'antd';
import {
  decode,
  encode,
} from 'js-base64';
import Cookies from 'js-cookie';
import sha1 from 'sha1';

import SlideVerify from '../../../components/SlideVerify';

const REDIRECT_URI = "https://panda-water.com/civbase/user/login"
class Login {
  constructor(props, callback, isInit) {
    this.events = window.share.event;
    this.globalConfig = props.global;
    this.updateConfig = props.updateConfig;
    this.createContext = props.createContext;
    this.history = props.history;
    this.callback = callback
    this.hasTry = false
    if(isInit) {
      this.init();
    }
    // 
  }

  init() {
    this.loginFailed = false;
    this.guid = Math.round(Math.random() * 10000 + Date.now()).toString(16);
    this.redirect_state = Cookies.get('redirect_state');
    const token = this.globalConfig.initToken || Cookies.get('token');
    let ddCode = this.globalConfig.ddCode;
    const loginName = this.globalConfig.loginName;
    const password = this.globalConfig.password;
    const loginMode = Cookies.get("loginMode") || null;
    if(loginMode && loginMode == 'iotWechat') ddCode = null;

    const self = this;
    // self.qrcodeLogin(self.globalConfig.qrcodeData.code);
    if (!!token) {
      self.getToweb(token)
    } else if(!!ddCode) {
      
    } else if(!!loginName && !!password) {
      self.otherLoginIn(loginName, password)
    } else if(self.globalConfig.qrcodeData &&  (self.globalConfig.qrcodeData.state &&  self.globalConfig.qrcodeData.state === this.redirect_state) &&  (self.globalConfig.qrcodeData.code!=="")) {
        console.log("init iotWechat");
        self.qrcodeLogin(self.globalConfig.qrcodeData.code);
       
    } else if(!!self.globalConfig.isSingleLogin && !!!!self.globalConfig.singleLoginCode) {

    } else {
      if(self.goLogin()) {
        return false
      }
    }
  }

  getToweb(token) {
    debugger
    this.globalConfig.token = token;
    const self = this;
    Http.getUserInfo({
      token: this.globalConfig.token,
      subOID: 'subOID',
      site: this.getLocalSiteBytoken(token),
      'request.preventCache': Date.now(),
    }, {
      ignoreSite: true
    }).then(response => {
      debugger
      if (response && !response.errMsg) {
        self.globalConfig.userInfo = {};
        if (
          response.Groups &&
          response.Groups instanceof Array &&
          response.Groups.length
        ) {
          self.globalConfig.userInfo.Groups = response.Groups;
        }
        self.globalConfig.userInfo = Object.assign(
          {},
          response,
          self.globalConfig.userInfo,
        );
        self.updateConfig && self.updateConfig(self.globalConfig);
        self.getUserInfoAndConfig();
      }
    });
  }

  writeLogs() {
    if (this.globalConfig.userInfo.UserImge === '') {
      // _config.userInfo.UserImge = __webpack_public_path__ + "assets/images/icon/熊猫新2.png";
      this.globalConfig.userInfo.UserImge =
        'https://panda-water.cn/web4/assets/images/icon/熊猫新2.png';
    }

    if (this.globalConfig.userInfo.site) {
      Http.writeLogs({
        origin: window.location.origin,
        client: this.globalConfig.client,
        site:
          this.globalConfig.userInfo && this.globalConfig.userInfo.site
            ? this.globalConfig.userInfo.site
            : '',
        loginName:
          this.globalConfig.userInfo && this.globalConfig.userInfo.fullName
            ? this.globalConfig.userInfo.fullName
            : '',
      }).catch(error => {
        console.log(error);
      });
    }
  }

  getIndustry(flag, token, getIndustry) {
    this.globalConfig.userInfo.Industries = new Array;
    if ( this.globalConfig.userInfo.Groups && this.globalConfig.userInfo.Groups.length ) {
      this.globalConfig.userInfo.Groups.forEach(group => {
        if (group.industry &&this.globalConfig.userInfo.Industries.indexOf(group.industry) < 0) {
          this.globalConfig.userInfo.Industries.push(group.industry);
        }
          
      });
    }

    if (
      !flag &&
      this.isSignIn &&
      this.globalConfig.userInfo.Industries.length &&
      this.globalConfig.userInfo.Industries.length > 1
    ) {
      this.createContext(this);
      //console.log('云平台');
      this.history.push('/industry');
      return false;
    }
    this.getWebConfig(token, getIndustry);
  }

  getWebConfig(token, getIndustry) {
    debugger
    const self = this;
    Http.getWebSiteConfig({
      client: this.globalConfig.client,
      token: token,
      'request.preventCache': Date.now(),
    })
      .then(response => {
        debugger
        if (response && response.length > 0) {
          self.globalConfig = Object.assign(
            self.globalConfig,
            response.shift(),
            {
              theme: self.globalConfig.theme,
              menu: self.globalConfig.menu,
              style: self.globalConfig.style,
            },
          );

          self.updateConfig && self.updateConfig(self.globalConfig);

          self.getProjectItems().then(() => {
            window.subSysCfg = {};
            response.forEach(item => {
              window.subSysCfg[item.client] = item;
            });

            if (!!self.globalConfig.isShared) {
              self.globalConfig.mode = 'single';
              self.globalConfig.style = 'sandbox';
              self.globalConfig.uiwidgets = [self.globalConfig.shareWidget];
              self.globalConfig.widgets = [];
            }
            // this.events.removeAllListeners('loginSuccess')
            // this.events.removeAllListeners('toggleIndustry')
            // window.share.event = this.events;
            if (
              self.globalConfig.userInfo.site &&
              self.globalConfig.userInfo.site.length > 0
            ) {
              Http.getWebSiteConfig({
                client: self.globalConfig.client,
                token: token,
              }, {
                ignoreSite: true,
                'request.preventCache': Date.now(),
              }).then(response => {
                debugger
                if (response && response.length > 0) {
                  debugger
                  var mainConf = response.shift();
                  if (mainConf.homepage)
                    self.globalConfig.homepage = mainConf.homepage;
                  if (mainConf.bannerLogo)
                    self.globalConfig.bannerLogo = mainConf.bannerLogo;
                  if (mainConf.logo) self.globalConfig.logo = mainConf.logo;
                  if (mainConf.mdi) self.globalConfig.mdi = mainConf.mdi;
                  if (mainConf.menu) self.globalConfig.menu = mainConf.menu;
                  if (mainConf.shortcutIcon)
                    self.globalConfig.shortcutIcon = mainConf.shortcutIcon;
                }
                self.updateConfig && self.updateConfig(self.globalConfig);
                // console.log("===loginSuccess===")
                getIndustry ? self.events.emit('toggleIndustry'):self.events.emit('loginSuccess');
                window.share.event = self.events;
                self.callback && self.callback()
              });
            } else {
              //loginSuccess
              self.updateConfig && self.updateConfig(self.globalConfig);
              // console.log("===loginSuccess===")
              getIndustry ? self.events.emit('toggleIndustry'):self.events.emit('loginSuccess');
              window.share.event = self.events;
              self.callback && self.callback()
            }
          });
        } else {
          if (this.goLogin()) {
            return false;
          }
          this.handleLoginError();
          console.log('获取网络配置失败');
        }
      })
      .catch(error => {
        console.log(error);
        this.handleLoginError();
        console.log('获取网络配置失败');
      });
  }

  getProjectItems() {
    let MAX_BOTTOM = 0;
    let isScale = false;
    let widgetIndex = -1;
    this.globalConfig.uiwidgets.map((item, index) => {
      if (parseInt(item['bottom']) > MAX_BOTTOM) {
        MAX_BOTTOM = parseInt(item['bottom']);
      }
      if (!isScale && item.url.toLowerCase().indexOf('widgets/zoom') > -1)
        isScale = true;
      if (
        widgetIndex == -1 &&
        item.url.indexOf('ToggleProject/ToggleProject') > -1
      )
        widgetIndex = index;
    });

    const layers = this.globalConfig.mapsettings.layers;
    if (layers.length === 0) {
      widgetIndex != -1 && this.globalConfig.uiwidgets.splice(widgetIndex, 1);
      return Promise.resolve({});
    }

    let layer = layers[0];

    if (!layer.id) {
      layer.layerType = 'dynamic';
    } else {
      layer.layerType = 'PipenetLayer';
    }

    if (layers.length > 1 && widgetIndex == -1) {
      this.globalConfig.uiwidgets.push({
        bottom: isScale ? MAX_BOTTOM + 70 : MAX_BOTTOM + 35,
        config: '',
        label: '方案切换',
        right: 15,
        url: 'product/webgisPanda/ToggleProject/ToggleProject',
      });
    }

    if (layer.areaName)
      this.globalConfig.mapsettings.areasettings.areaName = layer.areaName;
    if (layer.backgroundColor)
      this.globalConfig.mapsettings.areasettings.backgroundColor =
        layer.backgroundColor;
    if (layer.boundColor)
      this.globalConfig.mapsettings.areasettings.boundColor = layer.boundColor;
    if (layer.boundWidth)
      this.globalConfig.mapsettings.areasettings.boundWidth = layer.boundWidth;
    if (Number.isInteger(parseInt(layer.backgroundOpacity))) {
      this.globalConfig.mapsettings.areasettings.backgroundOpacity =
        layer.backgroundOpacity;
    }
    if (layer.extent)
      this.globalConfig.mapsettings.areasettings.extent = layer.extent;
    if (layer.basemaps && layer.basemaps.length > 0)
      this.globalConfig.mapsettings.basemaps = layer.basemaps;
    this.updateConfig && this.updateConfig(this.globalConfig);
    return Promise.resolve({});
  }

  handleLoginError(callback) {
    Cookies.set(this.globalConfig.client, '', {
      path: '/',
    });

    Cookies.set('token', '', {
      path: '/',
    });
    Cookies.set('site', '', {
      path: '/',
    });
    Cookies.set('loginMode', '', {
      path: '/',
    });
    Cookies.set('redirect_state', '', {
      path: '/',
    });
    this.loginFailed = true;
    callback && callback();
  }

  goLogin() {
    if (
      this.globalConfig.style === 'ios' &&
      this.globalConfig.loginTemplate === 'IOSCloud.html'
    ) {
      window.location.href = window.location.origin + '/#login';
      return true;
    } else {
      return false;
    }
  }

  isRememberPWD(status) {
    this.isRememberPWD = status;
  }

  getLocalSiteBytoken(tk) {
    let sStr = localStorage.getItem('loginSite'),
      s = null;
    if (sStr) {
      const sObj = JSON.parse(sStr);
      if (sObj && sObj[tk]) {
        s = sObj[tk];
      }
    }
    return s;
  }

  loginByDD() {
    const gotoUrl =
      'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoakne99srqra6hldv2&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' +
      encodeURIComponent(window.location.href);
    const obj = DDLogin({
      id: 'login_container',
      goto: encodeURIComponent(gotoUrl),
      style: 'border:none;background-color:#FFFFFF;',
      width: '365',
      height: '400',
    });

    const handleMessage = function(event) {
      const origin = event.origin;
      console.log('origin', event.origin);
      if (origin == 'https://login.dingtalk.com') {
        //判断是否来自ddLogin扫码事件。
        const loginTmpCode = event.data;
        const redirectUrl =
          'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoakne99srqra6hldv2&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' +
          encodeURIComponent(window.location.href) +
          '&loginTmpCode=' +
          loginTmpCode;
        //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
        window.location.href = redirectUrl;
      }
    };
    if (typeof window.addEventListener != 'undefined') {
      window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
      window.attachEvent('onmessage', handleMessage);
    }
  }

  ddLoginIn(code) {

    Http.getOA({
      query: {
        TmpAuthCode: code,
      },
      cacheBust: true,
    }).then(response => {
      if (response && response.data && response.data.getMe) {
        const tk = response.data.getMe[0].token;
        this.globalConfig.token = tk;
        const url = window.location.href; //获取当前页面的url
        if (url.indexOf('&code') != -1) {
          //判断是否存在参数
          url = url.replace(/(\&code|#)[^'"]*/, ''); //去除参数
          window.history.pushState({}, 0, url);
        }
        this.isSignIn = true;
        this.getUserInfoAndConfig();
      } else {
        this.handleLoginError();
        // msgUtils.fault("登录失败，请检查用户名或密码");
        // msgUtils.fault("登录失败，" + error.message);
        this.hasTry = true; //已经输错过密码
      }
    });
  }
  qrcodeLogin(code) {
    const self = this;
    Http.generatetokenByqrcode({
      f: "json",
      expiration: self.globalConfig.expiration || 43200000,
      referer: self.globalConfig.client,
      skipMenuTest: 1,
      qrcode: code
    }, {
      cacheBust: true
    }).then(response => {
      if(response.token) {
        self.globalConfig.token = response.token;
        self.updateConfig && self.updateConfig(this.globalConfig);
        self.isSignIn = true;
        self.getUserInfoAndConfig();
        console.log("===getUserInfoAndConfig===")
      } else {
        message.error("登录失败,"+ response.message);
        self.events.emit('loginError',response)
        setTimeout(() => {
          self.handleLoginError(() => {
            window.location.href = REDIRECT_URI
          });
        }, 600)
      }
    }).catch(error => {
      message.error("登录失败,"+ response.message);
      self.events.emit('loginError',response)
      setTimeout(() => {
        self.handleLoginError(() => {
          window.location.href = REDIRECT_URI
        });
      }, 600)
    })
  }
  otherLoginIn(usr, pwd) {
    const uesrName = decode(usr.substring(0, usr.length - 3)),
      password = decode(pwd.substring(0, pwd.length - 3));
    Http.generateToken({
      f: 'json',
      expiration: this.globalConfig.expiration, //token过期时间(单位：秒)
      client: 'referer',
      username: uesrName,
      password: sha1(password).toUpperCase(),
      referer: this.globalConfig.client,
      skipMenuTest: 1,
    }).then(response => {
      if (response && response.token) {
        const tk = response.token;
        this.globalConfig.token = tk;
        Http.getUserInfo({
          token: tk,
          subOID: 'subOID',
          site: this.getLocalSiteBytoken(tk)
        }, { 
          cacheBust: true,
          ignoreSite: true
        }).then(function(response) {
          debugger
          if (response && response.errMsg) {
            this.globalConfig.userInfo = {};
            if (
              response.data.Groups &&
              response.data.Groups instanceof Array &&
              response.data.Groups.length
            ) {
              this.globalConfig.userInfo.Groups = response.data.Groups;
            }
            self.updateConfig && self.updateConfig(self.globalConfig);
            this.getUserInfoAndConfig();
          }
        });
      } else {
        _this.handleLoginError();
        message.error('登录失败')
        this.hasTry = true
      }
    }).catch(error => {
      _this.handleLoginError();
      message.error('登录失败')
      this.hasTry = true
    })
  }

  getUserInfoAndConfig(failCallback, flag, industry) {
    debugger
    const token = this.globalConfig.token;
    const site = Cookies.get('site');
    const self = this;
    let _industrySite = null;
    debugger
    if (industry) {
      debugger
      let userInfo =
      self.globalConfig.userInfo &&
      self.globalConfig.userInfo.Groups &&
        self.globalConfig.userInfo.Groups instanceof Array
          ? self.globalConfig.userInfo.Groups.find(enter => {
              return enter.industry === industry;
            })
          : null;
      
      if (userInfo) {
        self.globalConfig.userInfo = {
          site: userInfo.site ? userInfo.site : null,
          Groups: self.globalConfig.userInfo.Groups,
        };
        _industrySite = userInfo.site ? userInfo.site : null;
        // self.globalConfig.Industry = industry
        self.updateConfig && self.updateConfig(self.globalConfig);
      }
    } else if (!!site && self.isSignIn) {
      self.globalConfig.userInfo = {
        site: decodeURIComponent(decode(site)),
        Groups:
        self.globalConfig.userInfo &&
        self.globalConfig.userInfo.Groups &&
        self.globalConfig.userInfo.Groups instanceof Array
            ? self.globalConfig.userInfo.Groups
            : null,
      };
      self.updateConfig && self.updateConfig(self.globalConfig);
    }

   

    if (self.isSignIn || !!industry) {
      debugger
      Http.getUserInfo({
        token: token,
        subOID: 'subOID',
        industry: industry,
        site: _industrySite ? _industrySite: this.getLocalSiteBytoken(token),
        //self.globalConfig.userInfo.site ? self.globalConfig.userInfo.site: this.getLocalSiteBytoken(token),
        //industrySite ? _industrySite : this.getLocalSiteBytoken(token),
      }, {
        ignoreSite: true,
        'request.preventCache': Date.now(),
      })
        .then(response => {
          try {
            debugger
            if (response && !response.errMsg) {

              self.globalConfig.userInfo = Object.assign({}, response, self.globalConfig.userInfo);
              let  date = new Date();
              date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
              // date = date.toGMTString();
              const encodeSite = encode(encodeURIComponent(response.site));
              Cookies.set("site", encodeSite, {
                  expires: date,
                  path: "/"
              })
              self.globalConfig.Industry = industry;
              self.updateConfig && self.updateConfig(self.globalConfig);
              const loginSite = {};
              loginSite[token] = response.site
              // Cookie.set()
              localStorage.setItem("loginSite", JSON.stringify(loginSite));
              self.writeLogs();
              self.getIndustry(flag, token, industry);
            } else {
              if (self.goLogin()) {
                return false;
              }
              self.handleLoginError(failCallback);
            }
            self.updateConfig && self.updateConfig(self.globalConfig);
          } catch (error) {
            if (self.goLogin()) {
              return false;
            }
            self.handleLoginError(failCallback);
            console.log(error);
          }
        })
        .catch(error => {
          if (self.goLogin()) {
            return false;
          }
          self.handleLoginError(failCallback);
          console.log(error);
        });
    } else {
      try {
        self.writeLogs();
        self.getIndustry(flag, token);
      } catch (error) {
        if (self.goLogin()) {
          return false;
        }
        self.handleLoginError(failCallback);
        console.log(error);
      }
    }
  }

  login(usr, pwd, userPhone, isRememberPWD) {
    this.events.removeAllListeners('loginError')
    const self = this;
    Http.generateToken({
      f: 'json',
      expiration: this.globalConfig.expiration, //token过期时间(单位：秒)
      client: 'referer',
      username: usr,
      password: pwd ? sha1(pwd).toUpperCase(): "",
      referer: this.globalConfig.client,
      skipMenuTest: 1,
      userPhone: userPhone,
      'request.preventCache': Date.now(),
    }, {
      ignoreSite: true
    })
      .then(response => {
        debugger
        if (response && response.token) {
          debugger
          const token = response.token;
          Cookies.set('token', token);
          const exp = 86400000;
          this.globalConfig.token = token;
          if (isRememberPWD) {
            Cookies.set(this.globalConfig.client, token, {
              expires: exp / (24 * 60 * 60 * 1000),
              path: '/',
            });

            Cookies.set('token', token, {
              expires: exp / (24 * 60 * 60 * 1000),
              path: '/',
            });
          }
          this.isSignIn = true;
          this.updateConfig && this.updateConfig(this.globalConfig);
          this.getUserInfoAndConfig();
        } else {
          self.hasTry = true;
          self.events.emit('loginError',response)
          message.error(response.error.message)
          self.callback && self.callback(false);
        }
      })
      .catch(error => {
        self.hasTry = true;
        self.handleLoginError();
        self.events.emit('loginError',error.message)
        message.error("登录服务异常")
        console.log('登录失败', error.message);
        
      });
  }

  loginHandler(user, pwd, userPhone, isRememberPWD, ref) {
    const self = this;
    if(user && pwd ) {
      if(self.loginFailed && self.captchaObj) {
        self.captchaObj.verify()
      } else {
        if(self.hasTry) {
          self.slideVerify(ref, () => {
            self.login(user, pwd, userPhone, isRememberPWD)
          })
        } else {
          self.login(user, pwd, userPhone, isRememberPWD)
        }
      }
    }
  }

  phoneLoginFormHandler(userPhone, captcha) {
    this.login('', '', userPhone);
  }

  slideVerify(ref, onSuccess, onFail, onRefresh) {
    this.events.emit('loginVisible', true)
    
    if(this.renderVerify) {
      this.renderVerify.destroy()
    }
    this.renderVerify = new SlideVerify()
    this.renderVerify.render({
      container: ref.current,
      onSuccess: () => {
        onSuccess && onSuccess()
      }
    })

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

}

export default Login;
