import React from 'react';
import { createForm } from 'rc-form';
import { InputItem, Button, WhiteSpace, Toast, Modal, Picker, List } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import styles from './LoginSrm.less';
import LoginIcon from '../../assets/mobile/logoSrm.png';
import LoginUser from '../../assets/mobile/User.svg';
import loginCompanyPic from '../../assets/oee/loginCompany.png';
import LoginPassword from '../../assets/mobile/Password.svg';
import commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import * as commonFunc from '../../components/Common/commonFunc';
import AppUtil from '../../utils/AppUtil';
import * as commonUtils from '../../utils/utils';


// eslint-disable-next-line prefer-destructuring
const alert = Modal.alert;

class LoginSrm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // eslint-disable-next-line react/no-unused-state
      companys: [],
      sParentId: '',
      sId: '',
      username: localStorage.getItem(`${commonConfig.prefix}username`) || '',
      userpwd: localStorage.getItem(`${commonConfig.prefix}userpwd`) || '',
      loginCompany: JSON.parse(localStorage.getItem(`${commonConfig.prefix}loginCompany`)) || [],
    };
  }
  async componentWillMount() {
    const configUrl = `${commonConfig.server_host}sysbrands/getSysbrands`;
    const configReturn = (await commonServices.getService(null, configUrl)).data;
    if (configReturn.code === 1) {
      const companys = configReturn.dataset.rows;
      const companysLabel = [];
      // const sParentId = commonUtils.isNotEmptyObject(this.state.sParentId) ? this.state.sParentId : companys[0].sParentId;
      // const sId = commonUtils.isNotEmptyObject(this.state.sId) ? this.state.sId : companys[0].sId;
      if (commonUtils.isNotEmptyArr(companys)) {
        // eslint-disable-next-line array-callback-return
        companys.map((item) => {
          const map = { ...item };
          map.label = item.sName;
          map.value = item.sId;
          companysLabel.push(map);
        });
      }
      // eslint-disable-next-line react/no-unused-state
      this.setState({ companys: companysLabel });
    } else {
      Toast.fail(configReturn.msg);
    }
  }
  componentDidMount() {
    if (localStorage.getItem(`${commonConfig.prefix}privacyPolicy`) !== 'agree') {
      alert(
        '用户协议与隐3私政策',
        <p>感谢您选择小羚羊EBC！<br />
          我们非常重视您的个人信息和隐私保护。为了更好地保障您的个人权益，在您使用我们的产品前，请务必审慎阅读
          <a href="serviceAgreement.html">《小羚羊EBC服务协议》</a>与
          <a href="privacyPolicy.html">《小羚羊EBC隐私政策》</a>内的所有条款，尤其是:<br />
          1.我们对您的个人信息的收集/保存/使用/对外提供/保护等规则条款，以及您的用户权利等条款;<br />
          2.约定我们的限制责任、免责条款。<br />
          3.其他以颜色或加粗进行标识的重要条款。<br />
          如您对以上协议有任何疑问，可通过人工客服或发邮件至yanghl@xlyerp.com与我们联系。您点击“同意并继续”的行为即表示您已阅读完毕并同意以上协议的全部内容。
        </p>, [
          {
            text: '不同意',
            onPress: () => {
              const { plus } = window;
              if (plus) {
                plus.runtime.quit();
              }
            },
          },
          {
            text: '同意并继续',
            onPress: () => {
              localStorage.setItem(`${commonConfig.prefix}privacyPolicy`, 'agree');
            },
          },
        ],
      );
    }
  }

  onChange = (name, newValue) => {
    if (name === 'username') {
      this.setState({ username: newValue });
    } if (name === 'userpwd') {
      this.setState({ userpwd: newValue });
    }
  }
  handleChoodeCompanyOk = (value) => {
    this.setState({
      loginCompany: value,
    });
  }
  handleLogin = async () => {
    const { dispatch, app } = this.props;
    const { loginCompany, companys } = this.state;
    let sParentId = '';
    if (commonUtils.isNotEmptyArr(companys) && commonUtils.isNotEmptyObject(loginCompany)) {
      // eslint-disable-next-line prefer-destructuring
      sParentId = companys.filter(item => item.sId === loginCompany[0])[0].sParentId;
    } else {
      Toast.fail(commonFunc.showMessage(app.commonConst, 'chooseBranchCompany'));
      return;
    }
    this.props.form.validateFields(async () => {
      const value = {};
      value.username = this.state.username;
      value.password = this.state.userpwd;
      value.sParentId = this.state.sParentId;
      // value.company = this.state.loginCompany;
      value.sId = this.state.sId;
      const url = `${commonConfig.server_host}userlogin/${sParentId}/${loginCompany}`;
      const dataReturn = (await commonServices.postValueService(null, value, url)).data;
      if (dataReturn.code === 1) {
        if (commonUtils.isNotEmptyObject(dataReturn.msg)) {
          Toast.info(dataReturn.msg, 3);
        }
        localStorage.setItem(`${commonConfig.prefix}username`, this.state.username);
        localStorage.setItem(`${commonConfig.prefix}userpwd`, this.state.userpwd);
        localStorage.setItem(`${commonConfig.prefix}loginCompany`, JSON.stringify(loginCompany));
        const param = {};
        const {
          token, gdslogininfo: userinfo, systemData, commonConst,
        } = dataReturn.dataset.rows[0];
        const decimals = {};
        if (systemData !== undefined) {
          const dNetPrice = systemData.filter(item => (item.sName === 'NetPrice'))[0];
          const dNetMoney = systemData.filter(item => (item.sName === 'NetMoney'))[0];
          decimals.dNetPrice = dNetPrice.sValue !== undefined ? (dNetPrice.sValue) * 1 : 6;
          decimals.dNetMoney = dNetMoney.sValue !== undefined ? (dNetMoney.sValue) * 1 : 6;
        }
        param.token = token;
        param.userinfo = userinfo;
        param.systemData = systemData;
        param.commonConst = commonConst;
        param.decimals = decimals;
        param.dateFormat = commonFunc.getDateFormat(systemData);
        dispatch({
          type: 'loginSrm/login',
          payload: { ...param, dispatch },
        });
      } else {
        Toast.fail(dataReturn.msg);
      }
    });
  }

  render() {
    const { loginCompany } = this.state;
    const { getFieldProps } = this.props.form;
    return (
      <div className={styles.wraper}>
        <div className={styles.logo}>
          <img src={LoginIcon} alt="login" />
        </div>
        <div className={styles.login} >
          <WhiteSpace size="xs" />
          <InputItem
            {...getFieldProps('username')}
            placeholder="请输入用户名"
            value={this.state.username}
            onChange={this.onChange.bind(this, 'username')}
            style={{ backgroundColor: '#fff' }}
          >
            <div style={{
              backgroundImage: `url(${LoginUser})`, backgroundSize: 'cover', height: '22px', width: '22px',
            }}
            />
          </InputItem>
          <WhiteSpace size="xs" />
          <InputItem
            {...getFieldProps('userpwd')}
            type="password"
            placeholder="请输入密码"
            value={this.state.userpwd}
            onChange={this.onChange.bind(this, 'userpwd')}
          >
            <div style={{
              backgroundImage: `url(${LoginPassword})`, backgroundSize: 'cover', height: '22px', width: '22px',
            }}
            />
          </InputItem>
          <div className="chooseCompany">
            <Picker
              data={this.state.companys}
              cols={1}
              value={loginCompany}
              onChange={this.handleCompanyChange}
              onOk={this.handleChoodeCompanyOk}
            >
              <List.Item arrow="horizontal">
                <div style={{
                  backgroundImage: `url(${loginCompanyPic})`, backgroundSize: 'cover', height: '22px', width: '22px',
                }}
                />
              </List.Item>
            </Picker>
          </div>
          <WhiteSpace size="lg" />
          <WhiteSpace size="lg" />
          <div className={styles.loginSubmit}><Button type="primary" onClick={this.handleLogin.bind(this)} style={{ backgroundColor: '#5e81e5' }}>登录</Button></div>
          {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
          <a
            className={styles.setting}
            onClick={() => {
              AppUtil.openSettingPage();
            }}
          >服务器设置
          </a>
        </div>
      </div>
    );
  }
}
const LoginMobileWrapper = createForm()(LoginSrm);
export default LoginMobileWrapper;
