import React, { useState, useEffect } from 'react';

import styles from './index.less';
import { Spin, message, Upload, Button, Table, Space } from 'antd';
import { UploadOutlined, LoadingOutlined } from '@ant-design/icons';

import { useIntl, connect, history } from 'umi';

import TitleSearch from '../../../components/TitleSearch/TitleSearch';

import { timestampToTime } from '../../../utils/time';
import { RA, getCookie, URL, filterObjbyTg, urlEncode, filterObj } from '@/utils/method';

const module = 'User';
const module2 = 'History';

// const string2mean = [[0, "未注册"], [1, "注册"], [2, "注销"]]
const string2mean = [
  [0, 'Unregistered'],
  [1, 'Registered'],
  [2, 'Deregistered'],
];

// 筛选条件对象
let readyData: any = {
  pageNum: 1,
  owerName: '',
  communityArray: [],
};

// 节流阀
let flag: boolean = false;
const Users = (props: any) => {
  const permissionArr = JSON.parse(localStorage.getItem('permission') || '');
  const { formatMessage } = useIntl();
  const { dispatch, location, Data, CommunityList } = props;
  const SA = (values: any) => {
    dispatch({ type: 'User/SA', playload: values });
  };

  const username = formatMessage({ id: 'R.charge.username' });
  const project = formatMessage({ id: 'R.charge.project' });
  const unit = formatMessage({ id: 'R.charge.unit' });
  const status = formatMessage({ id: 'R.charge.status' });
  const submissionTime = formatMessage({ id: 'R.charge.submissionTime' });
  const actions = formatMessage({ id: 'R.charge.actions' });

  const [loading, setLoading] = useState(false);
  const [fileUploading, setFileUploading] = useState(false);
  const [compent, setCompent] = useState({ loading: false, fileUploading: false });

  const userInfo = localStorage.getItem('userInfo') || '';
  const id = JSON.parse(userInfo).userModel.id;

  // 表格模块
  const columns = [
    { title: username, dataIndex: 'owerName' },
    { title: project, dataIndex: 'communityName' },
    {
      title: unit,
      render: (text: any, record: any) => (
        <div>{record.buildingNumber + ' #' + record.floorNumber + '-' + record.roomNumber}</div>
      ),
    },
    {
      title: status,
      dataIndex: 'enable',
      render: (text: any, record: any) => <div>{string2mean[text][1]}</div>,
    },
    {
      title: submissionTime,
      render: (text: any, record: any) => <div>{timestampToTime(record.createTime.time)}</div>,
    },
    {
      title: actions,
      render: (text: any, record: any) => (
        <Space size="middle">
          <Button
            type="link"
            size="small"
            onClick={goToEdit.bind(this, record)}
            disabled={record.enable == 2 ? true : false}
          >
            Edit
          </Button>
          <Button type="link" size="small" onClick={goToDetail.bind(this, record)}>
            Detail
          </Button>
        </Space>
      ),
    },
  ];

  // 上传的模块
  const propsUpload = {
    name: 'file',
    action: () => {
      // return 'http://47.74.233.180:8651/tos/excel/upload?userId=' + getCookie('id');
      return 'http://192.168.1.28:8651/tos/excel/upload?userId=' + id;
    },
    beforeUpload: (file: any) => {
      if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        message.error(`${file.name}  file format is incorrect!`);
      }
      return file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    },
    onChange(info: any) {
      if (info.file.status == 'uploading') {
        setFileUploading(true);
      }
      if (info.file.status === 'done') {
        if (info.file.response.error_code == '0000') {
          history.push(location.pathname + '/Result');
        } else {
          history.push(location.pathname + '/ResultFailed');
          message.error(
            `${info.file.name} file upload failed.` +
              'failed count is ' +
              info.file.response.data.count,
          );
          setFileUploading(false);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
        setFileUploading(false);
      }
    },
    showUploadList: false,
  };

  // 监听路由变化更新数据
  useEffect(() => {
    console.log(readyData);
    if (location.query) {
      readyData = {
        ...readyData,
        ...location.query,
      };
    }

    if (CommunityList && flag === false) {
      flag = true;
      getList(CommunityList);
    }
  }, [location]);

  // 监听小区列表是否回来
  useEffect(() => {
    if (CommunityList && flag === false) {
      readyData.serviceCommunityList = [];
      flag = true;
      getList(CommunityList);
    }
  }, [CommunityList]);

  // 请求拿取数据
  const getList = (CommunityList: []) => {
    if (readyData.communityArray.length === 0) {
      readyData.communityArray = CommunityList;
    }
    setLoading(true);
    //获取数据
    RA(
      12,
      {
        ...readyData,
      },
      module,
      dispatch,
    );
  };

  // 判断数据是否回来
  useEffect(() => {
    if (Data != null) {
      flag = false;
      setLoading(false);
    }
  }, [Data]);

  const goToDetail = (values: any, e: any) => {
    if (permissionArr.indexOf('2') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    SA(values);
    history.push(location.pathname + '/Detail');
  };

  const goToEdit = (values: any, e: any) => {
    if (permissionArr.indexOf('3') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    SA(values);
    URL({ pathname: location.pathname + '/Edit', status: 1 }, module2, dispatch);
    history.push(location.pathname + '/Edit');
  };

  const goToAdd = () => {
    if (permissionArr.indexOf('4') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    URL({ pathname: location.pathname + '/Add', status: 1 }, module2, dispatch);
    history.push(location.pathname + '/Add');
  };

  // LIFE用户管理页面的搜索按钮
  const CallBackTitleSearch = (comment: any) => {
    console.log(comment);
    readyData.communityArray = comment.serviceCommunityList;

    /*页面跳转*/
    history.push(
      location.pathname +
        urlEncode(
          filterObj({
            owerName: comment.OwnerName,
            pageNum: 1,
          }),
        ),
    );
  };

  // 切换页码
  const pageChange = (values: any) => {
    // 将当前页码存储起来
    var tmp = filterObjbyTg(location.query, ['owerName']);
    tmp['pageNum'] = values.current;
    history.push(location.pathname + urlEncode(tmp));
  };

  return (
    <div className={styles.base}>
      {/* 头部组件 */}
      <TitleSearch
        listkey={['OwnerName']}
        list={['Owner Name']}
        community={'serviceCommunityList'}
        onSubmit={CallBackTitleSearch}
        defaultValue={{ OwnerName: readyData.owerName }}
        checklist={readyData.communityArray.length !== 0 ? readyData.communityArray : null}
      />

      {/* 内容组件 */}
      <div className={styles.box2}>
        <button className={styles.buttonAdd2} onClick={goToAdd}>
          Create New Owner
        </button>
        <div className={styles.buttonAdd}>
          <Upload {...propsUpload}>
            <Button icon={compent.fileUploading ? null : <UploadOutlined />}>
              {compent.fileUploading ? (
                <>
                  <Spin indicator={<LoadingOutlined style={{ fontSize: 16 }} spin />} />
                  Uploading
                </>
              ) : (
                'Batch Upload'
              )}
            </Button>
          </Upload>
        </div>
      </div>

      {/* 列表组件 */}
      <Table
        rowKey={'id'}
        loading={loading}
        style={{ marginTop: 16 }}
        dataSource={Data != null ? Data.data.list : []}
        columns={columns}
        pagination={
          Data != null
            ? {
                current: parseInt(readyData.pageNum),
                total: Data.data.page.totalRow,
                showSizeChanger: false,
                pageSize: Data.data.page.curPageSize,
              }
            : {}
        }
        onChange={pageChange}
      />
    </div>
  );
};

function mapStateToProps(state: any) {
  const { sourceData, DataSave, Data } = state.User;
  const { history_url } = state.History;
  const { pageData } = state.PageData;
  const { CommunityList } = state.Init;
  return {
    Data,
    DataSave,
    sourceData,
    pageData,
    history_url,
    CommunityList,
  };
}

export default connect(mapStateToProps)(Users);
