import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Pagination, Card, Button, Icon, Tooltip, notification, Modal } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import className from 'classnames';
import Cell from '../../components/Cell';
import Style from './style.less';
import { fetch, apis } from '../../utils/request';
import PasswordText from './passwordText';

const { Meta } = Card;

const getMembers = fetch(apis.member.list);
const turnMember = fetch(apis.member.turn);
const resetMemberPassword = fetch(apis.member.resetPass);

const lineTextStyle = {
  marginBottom: 0,
  lineHeight: '1.8em'
}

const colorDanger = '#ff7875';
const colorSucces = '#449d44';

const Warn = (props) => <span style={{ color: colorDanger }}>{props.children}</span>
const ABCol = (props) => (
  <div className={className(Style['flex-box'])} style={lineTextStyle}>
    <div className={className(Style['flex-item'])} style={{ width: '30%' }}>{props.header}</div>
    <div className={className(Style['flex-auto'])}>{props.children}</div>
  </div>
)

export default (props) => {
  const [members, setMembers] = useState([]);
  const [pageNavi, setPageNavi] = useState({ current: 1, pageSize: 10, total: 0, size: 0 })
  // const [pageNavi, setPageNavi] = useState({ current: 1, pageSize: 10, total: 0 })
  // const [submitting, setSubmitting] = useState(false)
  const [visibleData, setVisibleData] = useState({ visible: false, userId: '', oldPassword:'', newPassword: '', confirmPassword: '' })

  useEffect(() => {
    getMembers({ params: { pageNum: pageNavi.current, pageSize: pageNavi.pageSize } }).then((dt) => {
      const { records, ...pagenavi } = dt || {};
      setMembers(records);
      setPageNavi({
        ...pageNavi,
        ...pagenavi
      })
    }).catch()
  }, []);

  const changeMemberStatus = (member, status) => {
    setMembers(members.map((mem) => {
      return mem.userId === member.userId ? { ...member, status } : mem
    }))
  }

  /**
   *回调事件
   *
   */
  function onModalChange() {
    // getList()
    // setVisibleData({ visible: false, userId: '', oldPassword:'', newPassword: '', confirmPassword: '' })
  }

  /**
   *打开编辑页
   *
   * @param {*} record
   */
  const editPassword = (record) => () => {
    setVisibleData({ visible: true, userId: record.userId, oldPasswod: '', newPassword: '', confirmPassword: '',submitting:submitting})
  }

  const CardBody = (cbProps) => {
    const handleSwitch = (on) => () => {
      if (!on) {
        Modal.confirm({
          title: '确定禁用当前用户?',
          onOk() {
            turnMember({ urlData: { type: 'off', id: cbProps.userId } }).then(() => {
              notification.success({ message: '禁用成功'});
              // window.location.reload();
              changeMemberStatus(cbProps, 9)
            }).catch()
          },
        });
      } else {
        turnMember({ urlData: { type: 'on', id: cbProps.userId } }).then(() => {
          notification.success({ message: '开启成功'});
          // window.location.reload();
          changeMemberStatus(cbProps, 1)
        }).catch()
      }
    }

    return (
      <>
        <Cell action={
          cbProps.status != 1 ?
            (<Button type="link" onClick={handleSwitch(true)} style={{ color: colorSucces }}>开启<Icon type="check" /></Button>) :
            (<Button type="link" onClick={handleSwitch(false)} style={{ color: colorDanger }}>关闭<Icon type="delete" /></Button>)
          }>
          <h3>{cbProps.miniappId ? cbProps.miniappName : <Warn>(小程序)未设置</Warn>}</h3>
        </Cell>
        <div>
          <ABCol header={'联系人'}>{cbProps.userName}</ABCol>
          <ABCol header={'手机号'}>{cbProps.phone}</ABCol>
          <ABCol header={'服务到期时间'}>{cbProps.expireDate ? moment(cbProps.expireDate).format('YYYY-MM-DD') : <Warn>未设置</Warn>}</ABCol>
          <ABCol header={'所有用户'}>{cbProps.userCount}</ABCol>
          <ABCol header={'注册用户'}>{cbProps.registeredCount}</ABCol>
        </div>
      </>
    )
  }
  
  const createUser = () => {
    router.push('/member/new');
  }

  const handleSizeChange = (current, size) => {
    getMembers({ params: { pageNum: current, pageSize: size } }).then((dt) => {
      const { records, ...pagenavi } = dt || {};
      setMembers(records);
      setPageNavi({
        ...pageNavi,
        ...pagenavi
      })
    }).catch()
  }

  const handlePageChange = e => {
    getMembers({ params: { pageNum: e, pageSize: pageNavi.pageSize } }).then((dt) => {
      const { records, ...pagenavi } = dt || {};
      setMembers(records);
      setPageNavi({
        ...pageNavi,
        ...pagenavi
      })
    }).catch()
  }

  const gotoDetail = (member, tab) => () => {
    router.push(`/member/edit/${member.userId}?tab=${tab || 1}`)
  }

  const resetPassword = (member) => () => {
    Modal.confirm({
      title: '确定重置当前用户密码?',
      onOk() {
        resetMemberPassword({ urlData: {id: member.userId}}).then((message) => {
          notification.success({ message })
        }).catch()
      },
    });
  }

  return (
    <>
    <PageHeaderWrapper extra={<Button type="primary" icon="plus" onClick={createUser}>新建</Button>}>
      <div className={Style['flex-box']}>
        {
          members.map((member, inx) => {
            return (
              <div className={className(Style['flex-item'], Style.member)} key={inx}>
                <Card
                  style={{width: '360px', boxShadow:'3px 3px 5px #ccc', borderRadius: '12px', overflow: 'hidden'}}
                  cover={<div className={Style.square} style={{ width: '100%', background: `no-repeat center/80% url(${member.qrCode})` }} />}
                  actions={[
                    <Tooltip title="编辑">
                      <Icon type="edit" key="edit" onClick={gotoDetail(member)}/>
                    </Tooltip>,
                    <Tooltip title="权限分配">
                      <Icon type="setting" key="rights" onClick={gotoDetail(member, 3)}/>
                    </Tooltip>,
                    <Tooltip title="重置密码">
                      <Icon type="block" key="resetpass" onClick={resetPassword(member)}/>
                    </Tooltip>
                  ]}
                >
                  <CardBody {...member}/>
                </Card>
              </div>
            );
          })
        }
      </div>
      <Pagination
        showSizeChanger
        current={pageNavi.current}
        total={pageNavi.total}
        pageSize={pageNavi.size}
        onChange={handlePageChange}
        onShowSizeChange={handleSizeChange}
      />
    </PageHeaderWrapper>
    <PasswordText visibleData={visibleData} key="PasswordText" onSuccess={() => onModalChange()}/>
    </>
  )
}
