/**
 * Title: 地产详情
 * Routes:
 *   - ./src/pages/routes
 */
import React, { useState, useEffect } from 'react';
import { connect, DispatchProp, routerRedux } from 'dva';
import { formatMessage } from 'umi-plugin-locale';
import { Button, Modal, Input, Select } from 'antd';
import Header from '@/components/Header';
import ChoiceModal from '@/components/ChoiceModal';
import AccountItem from '@/components/AccountItem';
import { UserModelState } from '@/models/user';

import styles from './style.less';
import { IdentityModelState } from './model';

import kycIdCover from '@/assets/kycIdCover.svg';
import kycIdBack from '@/assets/kycIdBack.svg'
import http from '@/utils/http';

const idtypes = [
  {key:'idcard', value:'身份证'},
  {key:'passport', value:'护照'}
]
const nations = [
  {key:'china', value:'中国'},
  {key:'us', value:'美国'},
  {key:'singapore', value:'新加坡'},
  {key:'hk', value:'中国香港'},
]
function getObjectURL(file) {
  var url = null ;
  if (window.createObjectURL!=undefined) { // basic
      url = window.createObjectURL(file) ;
  } else if (window.URL!=undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file) ;
  } else if (window.webkitURL!=undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file) ;
  }
  return url ;
}
const IdentityPage: React.FC<DispatchProp & UserModelState & IdentityModelState> = ({
  dispatch,
  user,
  kyc1status,
  nameInput,
  kyc1Submitting
}) => {
  const picCover = React.createRef();
  const picBack = React.createRef();
  const pic1url = React.createRef();
  const pic2url = React.createRef();
  const [idtypesVisible, setIdtypesVisible] = useState(false);
  const [nationVisible, setNationVisible] = useState(false);
  const [realname, setRealname] = useState();
  const [idNo, setIdNo] = useState();

  useEffect( () => {
    console.info('实名认证中')
    dispatch({ type: 'user/getKycInfo'})
  }, []);

  const preview = (type) => {
    const pic1 = picCover.current;
    const pic2 = picBack.current;
    const obj = type === 1 ? pic1 : pic2;
    // let x = getObjectURL(obj);
    // pic1url.current.src = x;
    var reader = new FileReader();
    reader.readAsDataURL(obj.files[0]);
    reader.onload = function(e) {
        type === 1 ? (pic1url.current.src = e.target.result) : (pic2url.current.src = e.target.result);
    }
    
  }
  const onIdTypeSelected = (key: string) => {
    setIdtypesVisible(false);
    dispatch({ type: 'user/onUpdateState', payload: key });
  };
  const onNationSelected = (key: string) => {
    setNationVisible(false);
    dispatch({ type: 'user/onUpdateState', payload: key });
  };

  const idtypeModal = (
    <ChoiceModal
      closable={false}
      data={idtypes}
      selectedKey='idcard'
      onItemSelected={onIdTypeSelected}
      visible={idtypesVisible}
      onCancel={() => setIdtypesVisible(false)}
      title={formatMessage({ id: 'identity.chooseIdtype' })}
    />
  );
  const nationModal = (
    <ChoiceModal
      closable={false}
      data={nations}
      selectedKey='idcard'
      onItemSelected={onNationSelected}
      visible={nationVisible}
      onCancel={() => setNationVisible(false)}
      title={formatMessage({ id: 'identity.chooseNation' })}
    />
  );
  const submitHandler = async () => {
    const formData = new FormData();
    const pic1 = picCover.current.files[0];
    const pic2 = picBack.current.files[0];
    // const p1 = new FileReader(pic1); // 用于预览
    // const p2 = new FileReader(pic2);
    formData.append('pic1', pic1);
    formData.append('pic2', pic2);
    formData.append('realname', realname);
    formData.append('idNo', idNo);
    if (!realname || !idNo || !pic1 || !pic2) {
      alert(formatMessage({ id: 'identity.missing' }))
      return
    }
    const data = await http.post('/user/verify', formData);
    alert(data.msg)
//    console.log(data)
  }
  return (
    <div className={styles.container}>
      <Header
        className={styles.header}
        title={formatMessage({ id: 'identity.title' })}
      />
      {user && <div className={styles.content}>
        <input className={styles.myinput}
          placeholder={formatMessage({ id: 'identity.realname' })}
          name="realname"
          value={realname}
          onChange={e => setRealname(e.target.value)}
        />
        <input className={styles.myinput}
          placeholder={formatMessage({ id: 'identity.idNo' })}
          name="idNo"
          value={idNo}
          onChange={e => setIdNo(e.target.value)}
        />
        <div style={{'display': 'flex', 'position': 'relative'}}>
          <div className={styles.uploadBox}>
            <div className={styles.imgBox}>
              <img src={kycIdCover} className={styles.idPhoto} ref={pic1url}/>
            </div>
            <input type="file" className={styles.input} ref={picCover} onChange={e => preview(1)}/>
          </div>
          <div className={styles.uploadBox}>
            <div className={styles.imgBox}>
              <img src={kycIdBack} className={styles.idPhoto} ref={pic2url}/>
            </div>
            <input type="file" className={styles.input} ref={picBack} onChange={e => preview(2)}/>
          </div>
        </div>
        {/* <AccountItem
          className="group"
          title="identity.nationality"
          message={user.nationality}
//          preview={fromLangToText(lang)}
         onClick={() => setNationVisible(true)}
        />
        <AccountItem
          className="group"
          title="identity.idtype"
          message={user.idtype}
//          preview={fromLangToText(lang)}
          onClick={() => setIdtypesVisible(true)}
        /> */}

        {/* <div className={styles.prompt}>
          <div>一级认证未能通过审核，原因为：</div>
          <div>后台返回的理由</div>
          <div>请重新提交。</div>
        </div> */}

        <Button
          className={styles.myinput}
          type="primary"
          size="large"
          loading={kyc1Submitting}
          // onClick={() => dispatch({ type: 'identity/kyc1submit' })}
          onClick={e => submitHandler(e)}
        >{formatMessage({ id: (user.kyc1status==='verifying'||user.kyc1status==='verified') ? 'identity.kyc1btn2' : 'identity.kyc1btn' })}</Button>
      </div>}
      {idtypeModal}
      {nationModal}
    </div>
  );
};

export default connect(
  ({ user, identity }: any) => ({ ...user, ...identity }),
)(IdentityPage);
