import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Radio, Button } from 'antd';
import { router } from 'umi';
import User from './User';
import MiniApp from './Miniapp';
import Menus from './Menus';
import { fetch, apis } from '../../../utils/request';

const getUser = fetch(apis.member.get);
const getTplTypes = fetch(apis.dict.tplType);

export default (props) => {
  const [ tab, changeTab ] = useState(props.location.query.tab - 0 || 1);
  const [ user, setUser ] = useState({});
  const [ tplTyps, setTplTypes ] = useState([])


  const handleRadioChange = e => {
    if (user.userId) {
      changeTab(e.target.value)
    }
  }

  useEffect(() => {
    getTplTypes().then(list => setTplTypes(list))
  }, [])

  useEffect(() => {
    if (props.match.params.id) {
      getUser({ urlData: { id: props.match.params.id } }).then((user) => {
        // user 中包含 miniapp 信息
        setUser(user);
      }).catch(() => {})
    }
  }, [props.match.params.id])

  const handleChangeUser = (newUser) => {
    console.log(newUser)
    setUser({
      ...user,
      ...newUser,
    });
  }

  const handleCancel = (currentTab) => () => {
    if (currentTab === 1) {
      gotoList()
    } else {
      changeTab(1)
    }
  }

  const gotoList = () => {
    router.push('/member')
  }

  return (
    <PageHeaderWrapper extra={<Button type="primary" ghost size="small" icon="close" onClick={gotoList}></Button> }>
      <div style={{ marginBottom: '24px' }}>
        <Radio.Group value={tab} buttonStyle="solid" onChange={handleRadioChange}>
          <Radio.Button value={1}>主信息</Radio.Button>
          <Radio.Button value={2}>小程序</Radio.Button>
          <Radio.Button value={3}>开通权限</Radio.Button>
        </Radio.Group>
      </div>
      <div style={{ width: '800px', margin: '0 auto' }}>
        { tab === 1 ? <User data={user} {...props} onChange={handleChangeUser} onCancel={handleCancel(1)}/> : null}
        { tab === 2 ? <MiniApp data={user} tplTyps={tplTyps} {...props} onChange={handleChangeUser} onCancel={handleCancel(2)}/> : null}
        { tab === 3 ? <Menus data={user} {...props} onCancel={handleCancel(3)}/> : null}
      </div>
    </PageHeaderWrapper>
  );
}
