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

import styles from './index.less';

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

import { Button, Tag, Table, Space, message } from 'antd';
import { timestampToTime } from '../../utils/time';

import { filterObj, urlEncode, filterObjbyTg } from '@/utils/method';

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

import ProTable, { ProColumns } from '@ant-design/pro-table';
interface readyData {
  [key: string]: any;
}

interface GithubIssueItem {
  url: string;
  id: number;
  number: number;
  title: string;
  labels: {
    name: string;
    color: string;
  }[];
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
}

let readyData = {
  tosOwnerName: '',
  communityName: '',
  pageNum: 1,
};

const ChargeManager = (props: any) => {
  const { dispatch, location, Data } = props;
  const [loading, setLoading] = useState(false);

  // 详情页
  const goToDetail = (values: any) => {
    const permissionArr = JSON.parse(localStorage.getItem('permission') || '');
    if (permissionArr.indexOf('10') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    getById(values);
    history.push('/PropertyManagementDetail');
  };

  // 存储详情页数据
  const getById = (values: any) => {
    dispatch({ type: 'PropertyManagement/getById', playload: values });
  };
  // 获取数据
  const get = (values: any) => {
    dispatch({ type: 'PropertyManagement/get', playload: values });
  };

  // 进入页面先请求一次
  useEffect(() => {
    setLoading(true);
    readyData = {
      ...readyData,
      ...location.query,
    };
    get(readyData);

    return () => {
      readyData = {
        tosOwnerName: '',
        communityName: '',
        pageNum: 1,
      };
    };
  }, [location]);

  // 监听数据返回
  useEffect(() => {
    if (Data != null) {
      setLoading(false);
    }
  }, [Data]);

  // 搜索按钮
  const TitleSearchContent = (comment: any) => {
    setLoading(true);
    console.log(comment);
    history.push(
      location.pathname +
        urlEncode(
          filterObj({
            ...comment,
            pageNum: 1,
          }),
        ),
    );
  };

  // 列表数据
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: 'User Name',
      dataIndex: 'tosOwnerName',
    },
    {
      title: 'Community Name',
      dataIndex: 'communityName',
    },
    {
      title: 'Unit',
      dataIndex: 'buildingNumber',
      render: (text: any, record: any) => (
        <div>{`${record.buildingNumber} #${record.floorNumber}-${record.roomNumber}`}</div>
      ),
    },
    {
      title: 'Submission Time',
      dataIndex: 'createTime',
      valueType: 'date',
      render: (text: any, record: any) => <div>{timestampToTime(record.createTime.time)}</div>,
    },
    {
      title: 'Actions',
      dataIndex: 'action',
      valueType: 'option',
      render: (text, record) => [<a onClick={goToDetail.bind(this, record)}>Detail</a>],
    },
  ];

  // 重置表单触发
  const resetHandler = () => {
    setLoading(true);
    readyData = {
      communityName: '',
      pageNum: 1,
      tosOwnerName: '',
    };
    history.push(location.pathname + urlEncode(filterObj(readyData)));
  };

  // 切换页码
  const changePage = (value: any) => {
    setLoading(true);
    history.push(
      location.pathname +
        urlEncode(
          filterObj({
            ...readyData,
            pageNum: value.current,
          }),
        ),
    );
  };
  console.log(Data);
  return (
    <div className={styles.base}>
      <TitleSearch
        listkey={['tosOwnerName']}
        list={['Name Of Owner']}
        communitySelect={true}
        onSubmit={TitleSearchContent}
        defaultValue={readyData}
      />

      {Data !== null ? (
        <ProTable<GithubIssueItem>
          columnEmptyText={false}
          columns={columns}
          dataSource={Data.list}
          rowKey={'id'}
          search={false}
          loading={loading}
          onChange={changePage}
          pagination={{
            pageSize: Data.page.curPageSize,
            showSizeChanger: false,
            total: Data.page.totalRow,
            current: +readyData.pageNum,
          }}
          options={{
            density: true,
            fullScreen: true,
            reload: () => {
              resetHandler();
            },
            setting: false,
          }}
        />
      ) : (
        <></>
      )}
    </div>
  );
};

function mapStateToProps(state: any) {
  const { Data } = state.PropertyManagement;
  return {
    Data,
  };
}
export default connect(mapStateToProps)(ChargeManager);
