import React, { useEffect } from 'react';
import { connect, history } from 'umi';
import { Input, Space, Button, Form, message, Pagination, Tag } from 'antd';
import moment from 'moment';
import { PlusOutlined, SearchOutlined, ClearOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { RA, SA } from '@/utils/method';
// import { objectColumns } from '@/utils/string';
import SearchOptionsCommnity from '@/components/SearchOptions/SearchOptionsCommnity';

const module = 'CommunityAnnouncement';
const CommunityAnnouncement = (props: any) => {
  const { dispatch, Data, userListLoading, DataSaveDetail } = props;

  // 先清空 其他信息
  useEffect(() => {
    dispatch({ type: module + '/returnDataSave', playload: { DataSave: null } });
    dispatch({ type: module + '/returnDataSaveDetail', playload: { DataSaveDetail: null } });
    dispatch({ type: module + '/returnImg', playload: { DataSaveDetail: null } });
  }, [1]);

  // 表头
  const columns: any = [
    {
      title: 'Community',
      dataIndex: 'communityNum',
      width: 240,
      ellipsis: {
        showTitle: false,
      },
    },
    {
      title: 'Title',
      dataIndex: 'noticTitlel',
    },
    {
      title: 'Publisher',
      dataIndex: 'creator',
    },
    {
      title: 'Publish Time',
      dataIndex: 'noticStartTime',
      render: (record: any) => (
        <Space size="middle">
          {record != null ? moment(record.time).format('YYYY-MM-DD') : null}
        </Space>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'noticStatus',
      render: function (text: any) {
        switch (text) {
          case 1:
            return <Tag color="green">Take Effect</Tag>; // 发布中
            break;
          case 2:
            return <Tag color="red">Expired</Tag>; // 已过期
            break;
          default:
            return <Tag color="cyan">Waiting For Release</Tag>; // 等待发布
            break;
        }
      },
    },
    {
      title: 'Actions',
      render: (text: any, record: any) => (
        <Space size={0}>
          <Button
            type="link"
            onClick={() => {
              goToAdd(1, record);
            }}
          >
            Edit
          </Button>
          <Button
            type="link"
            onClick={() => {
              goToAdd(2, record);
            }}
          >
            Detail
          </Button>
        </Space>
      ),
    },
  ];

  // 分业数据
  const DetailPage = (page: any) => {
    let data = {
      Method: 'returnDataSaveDetail',
      DefaultName: 'DataSaveDetail',
      Data: page,
    };
    return data;
  };

  // 分页数据一改变就发起请求
  useEffect(() => {
    if (DataSaveDetail != null) {
      request(DataSaveDetail);
    }
  }, [DataSaveDetail]);

  // 数据请求
  const request = (data: any) => {
    RA(25, data, module, dispatch);
  };

  // 跳转到新增或编辑
  function goToAdd(num: any, record: any) {
    if (num == 0) {
      history.push('./CommunityAnnouncement/Add');
    } else if (num == 1) {
      // 传递列表信息
      dispatch({ type: module + '/returnDataSave', playload: { DataSave: record } });
      history.push('./CommunityAnnouncement/Edit');
    } else if (num == 2) {
      // 传递列表信息
      dispatch({ type: module + '/returnDataSave', playload: { DataSave: record } });
      history.push('./CommunityAnnouncement/Detail');
    }
  }

  const [form] = Form.useForm();

  // 重置
  const onReset = () => {
    form.resetFields();
    let page = {
      noticTitlel: '',
      creator: '',
      pageNum: 1,
    };
    // 把内容存进去
    SA(DetailPage(page), module, dispatch);
  };

  // 表单提交
  const onFinishContract = (value: any) => {
    // console.log(value);
    if (!value.communityNumList && !value.noticTitlel && !value.creator) {
      message.error('Please enter one of them!');
    } else {
      // 要看是哪里分页
      let mlist = { ...value };
      mlist.communityNumList =
        value.communityNumList != null && value.communityNumList.length > 0
          ? [value.communityNumList]
          : null;
      mlist.pageNum = 1;
      // 把内容存进去
      SA(DetailPage(mlist), module, dispatch);
      // requst(payload);
    }
  };

  // 选择小区名字并赋值
  const opname = (value: any) => {
    form.setFieldsValue({
      communityNumList: value,
    });
  };

  // 页面切换
  const paginationHandler = (page: number, pageSize?: number) => {
    // 要看是哪里分页
    let mlist = { ...DataSaveDetail };
    mlist.pageNum = page;
    // 把内容存进去
    SA(DetailPage(mlist), module, dispatch);
  };

  const onKeyUp = (value: any) => {
    console.log(value);
    return false;
  };

  return (
    <>
      <div style={{ width: '100%', padding: 20, marginBottom: 0, backgroundColor: '#ffffff' }}>
        <Form
          autoComplete="off"
          layout="inline"
          form={form}
          name="contract"
          onFinish={onFinishContract}
          onKeyUp={onKeyUp}
        >
          <Form.Item name="communityNumList">
            <SearchOptionsCommnity
              // ubmit={extendName}
              opname={opname}
              // type={1} // 单选还是多选  单选就直接去掉
            />
          </Form.Item>
          <Form.Item name="noticTitlel">
            <Input allowClear placeholder="Announcement Title" />
          </Form.Item>
          <Form.Item name="creator">
            <Input allowClear placeholder="Announcement Publisher" />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SearchOutlined />}
              loading={userListLoading}
            >
              Search{' '}
            </Button>
            <Button
              htmlType="button"
              onClick={onReset}
              style={{ marginLeft: '15px' }}
              icon={<ClearOutlined />}
              loading={userListLoading}
            >
              {' '}
              Reset
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div style={{ width: '100%', paddingLeft: 10, paddingRight: 10, backgroundColor: '#ffffff' }}>
        <ProTable
          loading={userListLoading}
          rowKey="id"
          dataSource={Data ? Data.rows : []}
          columns={columns}
          pagination={false} // 隐藏默认分页
          search={false}
          toolBarRender={() => [
            <Button
              key="3"
              type="primary"
              onClick={() => {
                goToAdd(0, {});
              }}
            >
              <PlusOutlined />
              Create New Announcement
            </Button>,
          ]}
          options={{
            density: false,
            fullScreen: false,
            reload: () => {
              onReset();
            },
            setting: false,
          }}
          headerTitle="Announcement list"
        />
        <div style={{ textAlign: 'right', padding: 10 }}>
          <Pagination
            current={Data ? Data.page.currentPage : 0}
            total={Data ? Data.page.totalRow : 0}
            onChange={paginationHandler}
            showSizeChanger={false}
            // showSizeChanger={false}
            pageSize={Data ? Data.page.curPageSize : 10}
          />
        </div>
      </div>
    </>
  );
};

function map(state: any) {
  // console.log(state[module]);
  const userListLoading = state.loading.models.CommunityAnnouncement;
  const { Data, DataSaveDetail } = state[module];
  return { Data, userListLoading, DataSaveDetail };
}
export default connect(map)(CommunityAnnouncement);

// function mapStateToProps(state:any) {
//   const { Data, Data2,DataSave,curString,Result } = state.FacilityBookings;
//   const { token } = state.login;
//   return {
//     Data,
//     Data2,
//     DataSave,
//     curString,
//     Result,
//     token
//   };
// }
// export default connect(mapStateToProps)(FacilityBookings);
//备注 发布人缺少 发布时间格式错误
