import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Pagination, message, Modal, Tag } from 'antd';
import { connect, history } from 'umi';
import { SearchOutlined, ClearOutlined, PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { getCookie } from '@/utils/method';

import './Account.less';

import moment from 'moment';

const Account = (props: any) => {
  const { dispatch, Data, DataSave, DataSaveDetail, Result, loading } = props;
  const RA = (index: any, values: any) => {
    dispatch({ type: 'Account/RA', playload: { index: index, body: values } });
  };
  const [term, setTerm] = useState({} as any); // 拉取数据的条件存储
  const [over, setOver] = useState(false); // 关闭账号确认弹窗
  const [accountName, setaccountName] = useState(null as any); // 弹窗账号信息

  // 数据
  useEffect(() => {
    if (Data == null) {
      Refresh();
    }
  }, [Data]); //监听Data执行一次

  // 监听改变状态提交结果
  useEffect(() => {
    if (Result != null) {
      // console.log('改变取消弹窗重新加载，在清空结果');
      // let obj = {
      //   userStatus: accountName.userStatus == 0 ? 1 : 0,
      //   userID: accountName.tosUserId,
      // };
      // RA(52, obj);
      setOver(false);
      // 清除结果
      dispatch({ type: 'Account/ResultClear' });
      dispatch({ type: 'Account/ReData' });
    }
  }, [Result]);

  const [form] = Form.useForm(); // 表单标识

  // 刷新加载
  const Refresh = () => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '[]');

    let obj = {
      creatorId: userInfo.userModel.id ? userInfo.userModel.id : '',
      pageNum: 1,
    };
    // RA(45, obj);
    form.resetFields();
    setTerm(obj);
    RA(51, obj);
  };

  // 列表刷新加载
  const Refresh2 = () => {
    RA(51, term);
  };

  // 表头
  const columns = [
    {
      title: 'Account Name',
      dataIndex: 'tosUserName',
      key: 'userAccount',
    },
    {
      title: 'Grade',
      dataIndex: 'tosUserLevel',
      key: 'userLevel',
      render: (text: any) => (
        <span>
          {text == 0 ? 'Administrator' : ''}
          {text == 1 ? 'First Level' : ''}
          {text == 2 ? 'Two Level' : ''}
          {text == 3 ? 'Three Level' : ''}
        </span>
      ),
    },

    {
      title: 'Status',
      dataIndex: 'userStatus',
      key: 'userStatus',
      render: (text: any) => {
        return (
          <Tag color={text != 1 ? '#87d068' : '#f20'} key={text}>
            <span> {text != 1 ? 'Normal' : 'Deregistered'}</span>
          </Tag>
        );
      },
    },
    // {
    //   title: 'Created By',
    //   dataIndex: 'tosUserServiceCell',
    //   key: 'createAccount',
    //   width: 280,
    //   ellipsis: true,
    // },
    {
      title: 'Creator',
      dataIndex: 'creatorName',
      key: 'creator',
      ellipsis: true,
    },
    {
      title: 'Creation Time',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text: any) => {
        return moment(text).format('YYYY-MM-DD');
      },
    },

    {
      title: 'Actions',
      dataIndex: 'action',
      key: 'action',
      render: (text: any, record: any) => (
        <span>
          <Button
            type="link"
            onClick={() => {
              edit(record);
            }}
            disabled={record.userStatus == 1 ? true : false}
          >
            Edit
          </Button>
          <Button
            type="link"
            onClick={() => {
              detail(record);
            }}
          >
            Detail
          </Button>

          {/* <Button
            type="link"
            onClick={() => {
              lockS(record);
            }}
          >
            {record.userStatus != 1 ? 'Close' : 'Open'}
          </Button> */}
          {/*{record.userID == 1||record.userID == this.props.currentUser.userid?'':
          <Button style={{background: 'transparent', border: 0, color: '#1890FF'}}
                  onClick={() => this.changeStatus(record)}>
            {record.userStatus == 1 ? "lock" : "unlock"}</Button>}*/}
        </span>
      ),
    },
  ];

  // 编辑- 新增
  const edit = (item: any) => {
    // console.log(item);
    if (item == 1) {
      history.push('/AccountManagement/account/Add');
    } else {
      let DataSave = item;
      dispatch({ type: 'Account/SA', DataSave });
      history.push('/AccountManagement/account/edit');
    }
  };

  // 详情
  const detail = (item: any) => {
    let DataSave = item;
    dispatch({ type: 'Account/SA', DataSave });
    history.push('/AccountManagement/account/Detail');
  };

  // 停用账号弹窗
  const lockS = (item: any) => {
    setOver(true);
    setaccountName(item);
    console.log(item);
  };

  // 表头单搜索
  const onFinishContract = (value: any) => {
    if (value.tosUserName || value.creatorName) {
      let t = { ...term, ...value };

      delete t.pageNum; // 搜索的时候 删除页码
      setTerm(t);
      RA(51, t);
    } else {
      message.error('Enter At Least One Entry！');
    }
  };

  // 页码切换
  const sopens = (page: any) => {
    let p = {
      pageNum: page,
    };
    let t = { ...term, ...p };
    setTerm(t);
    RA(51, t);
  };

  // 弹窗 提交确认账号打开关闭
  const handleOk = (e: any) => {
    //
    let obj = {
      userStatus: accountName.userStatus == 0 ? 1 : 0,
      userID: accountName.tosUserId,
    };
    RA(52, obj);
    // setOver(false);
  };
  // 关闭弹窗
  const handleCancel = (e: any) => {
    setOver(false);
  };

  return (
    <>
      <div className="contop">
        <Form
          autoComplete="off"
          layout="inline"
          form={form}
          name="contract"
          onFinish={onFinishContract}
        >
          <Form.Item name="tosUserName">
            <Input allowClear placeholder="Account Name" />
          </Form.Item>
          <Form.Item name="creatorName">
            <Input allowClear placeholder="Account Creator" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
              Search{' '}
            </Button>
            <Button
              htmlType="button"
              onClick={Refresh}
              style={{ marginLeft: '15px' }}
              icon={<ClearOutlined />}
              loading={loading}
            >
              {' '}
              Reset
            </Button>
          </Form.Item>
        </Form>
      </div>

      <div className="contop contop2">
        <ProTable
          // request={requestHeadl}
          rowKey={'id'}
          dataSource={Data ? Data.list.filter((item: any) => item.userStatus != 1) : null}
          columns={columns}
          pagination={false} // 隐藏默认分页
          search={false}
          loading={loading}
          toolBarRender={() => [
            <Button
              type="primary"
              loading={loading}
              icon={<PlusOutlined />}
              onClick={() => {
                edit(1);
              }}
            >
              Add Account
            </Button>,
          ]}
          options={{
            density: false,
            fullScreen: false,
            reload: () => {
              Refresh();
            },
            setting: false,
          }}
          headerTitle="Account list"
          // pagination={{ defaultCurrent: 1, total: Data.totalRow }}
        />

        <div className="pages">
          <Pagination
            // onShowSizeChange={pageSizeHandler}
            current={Data ? Data.page.currentPage : 0}
            onChange={sopens}
            total={Data ? Data.page.totalRow : 0}
            pageSize={Data ? Data.page.curPageSize : 0}
            showSizeChanger={false}
          />
        </div>
      </div>
    </>
  );
};

const AccountProps = (styte: any) => {
  const { Data, DataSave, DataSaveDetail, Result } = styte.Account;
  const loading = styte.loading.models.Account || false;
  return {
    Data,
    DataSave,
    DataSaveDetail,
    Result,
    loading,
  };
};

export default connect(AccountProps)(Account);
