import * as React from 'react'
import { createPortal } from 'react-dom'
import * as Styled from './index.style'
import { showMessage } from '../../common/toast/toast';
import { appNavigate } from '../../utils/navigate';
import { getConsignInfo } from '../actions';


interface Props {
  show: boolean;
  color: string;
  background?: {
    topImage?: {
      url: string,
    };
    centerImage?: {
      url: string,
    };
    bottomImage?: {
      url: string,
    };
  },
  buttonImage?: {
    url: string
  },
  isEdit?: boolean,
  onCancel: () => any;
  onOk: (data: any, callback?: () => void) => void;
}
interface State {
  modalShow: boolean;
  name: string;
  phone: string;
  address: string;
  addressId: number;
}

const CONSIGN_STORE_KEY = 'lofter_market_consign_store'
class AddressModalCom extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.randomId = 'AddressModalCom_' + Math.random(); 
  }
  randomId: string
  state = {
    modalShow: this.props.show ?? false,
    name: '',
    phone: '',
    address: '',
    addressId: 0,
  }
  updateValue = (type: 'name' | 'phone' | 'address', event: React.ChangeEvent<HTMLInputElement|HTMLTextAreaElement>) => {
    const value = {
      [type]: event.target.value,
    } as {
      [K in typeof type]: State[typeof type] 
    }
    this.setState(value);
  }
  submit = () => {
    const { name, phone, address } = this.state;
    if (!name.trim() || !phone.trim() || !address.trim()) {
      showMessage('请填写完整的收货信息');
      return;
    }
    if (!/^1\d{10}$/.test(phone.trim())) {
      showMessage('请填写正确的收件电话');
      return;
    }
    // if (!/(市|地区|自治州|县|盟|旗)+.*(镇|县|区|市|旗|联合|农场|林场|乡)+/.test(address)) {
    //   showMessage('请填写完整的省市区发货地址，若未填写完整发货地区将导致无法发货哦~');
    //   return;
    // }
    this.props.onOk && this.props.onOk({
      addressId: this.state.addressId,
    })
  }
  storageListener = () => {
    const consignId = localStorage.getItem(CONSIGN_STORE_KEY);
    console.log('LocalStorage update', consignId);
    if (consignId && /^\d+$/.test(consignId)) {
      localStorage.removeItem(CONSIGN_STORE_KEY);
      getConsignInfo(consignId).then(res => {
        if (res.code === 200 && res.data) {
          const {
            receiverName = '',
            receiverPhone = '',
            receiverExt = '{\"sec\":\"\",\"city\":\"\",\"pro\":\"\"}',
            receiverAddress = '',
          } = res.data;
          const parsedReceiverExt = JSON.parse(receiverExt);
          this.setState({
            name: receiverName,
            phone: receiverPhone,
            address: `${parsedReceiverExt.pro || ''} ${parsedReceiverExt.city || ''} ${parsedReceiverExt.sec || ''} ${receiverAddress}`,
            addressId: parseInt(consignId, 10),
          })
        } else {
          showMessage('读取地址失败，请稍候重试~')
        }
      })
    }
  }
  choose = () => {
    console.log('Add localStorage listener');
    localStorage.removeItem(CONSIGN_STORE_KEY);
    window.removeEventListener('storage', this.storageListener)
    window.addEventListener('storage', this.storageListener)
    appNavigate('https://www.lofter.com/market/fe/html/consignList.html?type=choose&useStorageCallback=true')
  }
  
  componentDidUpdate(prevProps: Props) {
    if (prevProps.show !== this.props.show && this.props.show) {
      this.setState({
        modalShow: true
      })
    } else if (prevProps.show !== this.props.show && !this.props.show) {
      this.setState({
        modalShow: false
      })
    }
  }

  componentWillUnmount() {
    window.removeEventListener('storage', this.storageListener)
  }

  render() {
    const {
      onCancel,
      background,
      buttonImage,
      isEdit,
      color,
    } = this.props
    const {
      modalShow,
      name,
      address,
      phone,
    } = this.state
    return (
      createPortal((
        <Styled.Container
          isEdit={isEdit}
          show={modalShow}
        >
          <Styled.Mask onClick={onCancel} isEdit={isEdit}>
            <Styled.Content onClick={e => {e.stopPropagation()}} background={background} color={color} buttonImage={buttonImage}>
              <button className="choose" onClick={this.choose}>导入市集地址</button>
              <div className="title">填写收货信息</div>
              <div className="main">
                <div className="item">
                  <label htmlFor={`${this.randomId}_name`}>收件人</label>
                  <input readOnly value={name} placeholder="请点击选择地址" id={`${this.randomId}_name`} type="text" onChange={this.updateValue.bind(this, 'name')} />
                </div>
                <div className="item">
                  <label htmlFor={`${this.randomId}_phone`}>收件电话</label>
                  <input readOnly value={phone ? phone.toString() : ''} placeholder="请点击选择地址" id={`${this.randomId}_phone`} type="tel" onChange={this.updateValue.bind(this, 'phone')} />
                </div>
                <div className="item long">
                  <label htmlFor={`${this.randomId}_address`}>收件地址</label>
                  <textarea readOnly value={address} placeholder="请点击选择地址" id={`${this.randomId}_address`} rows={2} onChange={this.updateValue.bind(this, 'address')} />
                </div>
              </div>
              <button className="submit" onClick={this.submit}>提交</button>
            </Styled.Content>
          </Styled.Mask>
        </Styled.Container>
      ), isEdit && document.getElementById('viewport') ? document.getElementById('viewport') : document.getElementById('app')!)
    )
  }
}

const AddressModal = React.memo(AddressModalCom);
export default AddressModal;