import { Component } from 'react'
import Taro from '@tarojs/taro'
import { connect } from 'react-redux'
import { View, Input, Image } from '@tarojs/components'
import { login, setOpenId, getInfo } from '../../utils/servers/servers';

import { add, minus, asyncAdd } from '../../actions/counter'

import { AtButton, AtIcon, AtModal } from 'taro-ui'

import NavBar from '../../components/common/NavBar';

import BG from '../../image/bg.png';
import LOGO from '../../image/kdjt.png';

import 'taro-ui/dist/style/components/button.scss';
import 'taro-ui/dist/style/components/loading.scss';
import 'taro-ui/dist/style/components/icon.scss';
import 'taro-ui/dist/style/components/modal.scss';

import selectIcon from '../../image/select.png';

import './index.less'

@connect(({ counter }) => ({
  counter
}), (dispatch) => ({
  add() {
    dispatch(add())
  },
  dec() {
    dispatch(minus())
  },
  asyncAdd() {
    dispatch(asyncAdd())
  }
}))
class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      isOpened: false,
      openedType: 0,
      usernameList: Taro.getStorageSync('usernameList') || [],
      rememberPassword: true
    }
    this.login = this.login.bind(this);
    this.authorization = this.authorization.bind(this);
    this.setUsernameList = this.setUsernameList.bind(this);
    this.getUsernameList = this.getUsernameList.bind(this);
    this.getInfo = this.getInfo.bind(this);
  }

  componentDidShow() {

  }

  componentDidMount() {

  }

  authorization() {
    this.setState({
      loading: true,
    })
    let _this = this;
    Taro.getSetting({
      withSubscriptions: true,
      success: (res) => {
        if (res.subscriptionsSetting.mainSwitch) {
          if (res.subscriptionsSetting['2L9AJWl2yNfgd83Fw_f_E6HiaEvPf109iw_xFtI8PXI'] === "reject") {
            this.setState({
              isOpened: true,
              loading: false,
              openedType: 1
            })
            return;
          }
          Taro.requestSubscribeMessage({ //获取下发权限
            tmplIds: [
              '2L9AJWl2yNfgd83Fw_f_E6HiaEvPf109iw_xFtI8PXI',
            ], //此处写在后台获取的模板ID，可以写多个模板ID，看自己的需求
            success: function (s) {
              _this.setState({
                loading: false,
              })
              _this.login();
            },
            fail: function (err) {
              _this.setState({
                loading: false,
              })
              //console.log(err)
            }
          })
        } else {
          this.setState({
            isOpened: true,
            loading: false,
          })
        }
      },
      fail: () => {
        this.setState({
          loading: false,
        })
      }
    })
  }

  login() {
    if (!this.state.username) {
      Taro.showToast({
        title: '请输入用户名',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (!this.state.password) {
      Taro.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    this.setState({
      loading: true,
    })
    login({
      username: this.state.username,
      password: this.state.password
    }).then((msg) => {
      this.setState({
        loading: false
      });
      this.getInfo()
    }).catch((err) => {
      this.setState({
        loading: false
      })
    })
  }

  getInfo() {
    getInfo({}).then((msg) => {
      if (msg.code === 200) {
        if (!msg.user.openId) {
          Taro.login({
            success: (res) => {
              setOpenId({
                code: res.code,
              }).then(v => {
                if (v.error.length === 0) {
                  this.setUsernameList(this.state.username, this.state.password);
                  Taro.eventCenter.trigger('getStorageSync');
                  // this.getWorkingHours(msg.departmentId);
                } else {
                  Taro.showToast({
                    title: v.error[0].message,
                    icon: 'none',
                  })
                }
              })
            },
            fail: () => {
              Taro.showToast({ title: '系统错误,请稍后重试' })
            }
          });
        } else {
          this.setUsernameList(this.state.username, this.state.password);
          Taro.eventCenter.trigger('getStorageSync');
          // this.getWorkingHours(msg.departmentId);
        }

        // let obj = Taro.getStorageSync('userInfor');
        // obj.workTimeInfor = msg.user;
        Taro.setStorageSync('userInfor', msg.user);
        Taro.setStorageSync('roles', msg.roles);
        Taro.switchTab({
          // url: '/pages/project/index',
          url: '/pages/punchClock/index',
        })

      } else {
        Taro.showToast({ title: msg.error[0].message, icon: 'none' })
      }
    }).catch((err) => {
      // console.log(err)
    })
  }

  setUsernameList(username, password) {
    if (!this.state.rememberPassword) {
      let usernameList = Taro.getStorageSync('usernameList') || [];
      let index = usernameList.findIndex(v => v.username === username);
      if (index !== -1) {
        usernameList.splice(index, 1)
      }
      Taro.setStorageSync('usernameList', usernameList);
    } else {
      let usernameList = Taro.getStorageSync('usernameList') || [];
      let index = usernameList.findIndex(v => v.username === username);
      if (index === -1) {
        usernameList.push({
          username,
          password
        })
      } else {
        usernameList[index] = {
          username,
          password
        }
      }
      Taro.setStorageSync('usernameList', usernameList);
    }
  }

  getUsernameList(value = this.state.username) {
    let usernameList = Taro.getStorageSync('usernameList') || [];
    let arr = [];
    for (let i of usernameList) {
      if (i.username.indexOf(value) !== -1) {
        arr.push(i)
      }
    }
    this.setState({
      usernameList: arr,
      isopenUsernameList: true
    })
  }

  render() {
    return (
      <View className='login' onClick={() => {
        this.setState({
          isopenUsernameList: false
        })
      }}>
        <NavBar
          extClass='NavBar'
          title={<Image src={LOGO} mode='heightFix' />}
          background='#0000'
          color='#FFF'
          onHome={() => { }}
        />
        {/* <Image src={LOGO} className="logo" mode='heightFix' /> */}
        <View className='welcome'>
          <Image src={BG} className='bg' mode='heightFix' />
          <View className='welcomeTitle'>研发工时管理服务系统</View>
          <View className='welcomeTitle'>欢迎您!</View>
        </View>
        <privacy />
        <View className='loginContent'>
          <View className='loginItem'>
            <AtIcon value='user' size='20' color='#999999' />
            <View className='usernameContent'>
              <Input
                style={{ marginLeft: '15px', width: '100%' }}
                type='text'
                placeholder='请输入您的系统账户'
                value={this.state.username}
                onInput={(v) => {
                  this.setState({
                    username: v.detail.value
                  })
                  this.getUsernameList(v.detail.value);
                }}
                onFocus={() => {
                  this.getUsernameList();
                }}
                onBlur={() => {
                  // this.setState({
                  //   isopenUsernameList:false
                  // })
                }}
              />
            </View>
          </View>
          <View className='usernameListContent'>
            {this.state.isopenUsernameList && this.state.usernameList.length > 0 ? <View className='usernameList'>
              {
                this.state.usernameList.map((v, k) => (
                  <View key={k} className='usernameItem' onClick={() => {
                    this.setState({
                      username: v.username,
                      password: v.password,
                      isopenUsernameList: false
                    })
                  }}>
                    <AtIcon value='user' size='20' color='#c6c4c4' />
                    <View className='value'>
                      <View className='name'>{v.username}</View>
                      <View className='password'>*******</View>
                    </View>
                  </View>
                ))
              }
            </View> : null}
          </View>
          <View className='loginItem'>
            <AtIcon value='lock' size='20' color='#999999' />
            <Input
              style={{ marginLeft: '15px', width: '100%' }}
              type='password'
              placeholder='请输入密码'
              value={this.state.password}
              onInput={(v) => {
                this.setState({
                  password: v.detail.value
                })
              }}
            />
          </View>
          <View className='rememberPassword'>
            <View className='selectContent' onClick={() => {
              this.setState({
                rememberPassword: !this.state.rememberPassword
              })
            }}>
              <Image src={selectIcon} className='selectIcon' style={{ visibility: this.state.rememberPassword ? "visible" : "hidden" }} />
            </View>
            记住密码
          </View>
          <AtButton type='primary' circle loading={this.state.loading} onClick={this.authorization}>登录</AtButton>
          <View className='tips'>
            暂无账号?请联系管理员进行添加
          </View>
          <View className='company'>
            {/* 湖南科德信息咨询集团有限公司 */}
          </View>
        </View>
        <AtModal
          isOpened={this.state.isOpened}
          title='提醒'
          cancelText='取消'
          confirmText='确认'
          onClose={() => {
            this.setState({
              isOpened: false,
              openedType: 0,
            })
          }}
          onCancel={() => {
            this.setState({
              isOpened: false,
              openedType: 0
            })
          }}
          onConfirm={() => {
            this.setState({
              isOpened: false,
              openedType: 0
            }, () => {
              Taro.openSetting({
                success: (value) => {

                }
              })
            })
          }}
          content={this.state.openedType === 1 ? '您存在拒绝接收的消息类型,请点击确认按钮,前往设置页->通知管理,点击不接受的消息通知类型,调整为允许' : '您关闭了接收通知权限,将不能收到订阅通知,请点击确认按钮,前往设置页->通知管理->接收通知,打开接收通知权限'}
        />
      </View>
    )
  }
}

export default Login

