import React, { useState, useEffect, useRef } from 'react';
import { Input, Tabs, Tag, Form, Button, message, DatePicker } from 'antd';
const { TabPane } = Tabs;
import { connect } from 'umi';
import { objectColumns } from '@/utils/string';
import ProTable from '@ant-design/pro-table';
import { RA, SA } from '@/utils/method';
import { PlusOutlined, SearchOutlined, ClearOutlined } from '@ant-design/icons';
import './index.less';
import moment from 'moment';
import SearchOptionsCommnity from '@/components/SearchOptions/SearchOptionsCommnity';

import SelectCommunity from '@/components/SelectCommunity';

const module = 'VisitorRecord';

const VisitorRecord = (props: any) => {
  const { dispatch, Data, DataSave, loading } = props;

  const TosVisitorRecordGet = (values: any) => {
    dispatch({ type: 'tosVisitorRecord/get', playload: values });
  };

  // 新增搜索的时间  原来时间是时间戳格式
  useEffect(() => {
    if (Data != null) {
      Data.forEach((item: any) => {
        item.showTime = moment(item.updateTime).format('YYYY-MM-DD');
      });
    } else {
      RA(26, { inviterAddress: '', visitorCommunity: '' }, module, dispatch);
    }
  }, [Data]);

  // 表头
  const columns: any = [
    { title: 'Invitee', dataIndex: 'inviterName' },
    { title: 'Visitor', dataIndex: 'visitorsName' },
    { title: 'Security Guard', dataIndex: 'securityGuardName' },
    { title: 'Car Number', dataIndex: 'numberPlate' },
    { title: 'Telephone', dataIndex: 'inviterPhone' },
    // 隐藏的搜索框
    {
      title: 'Visiting Time',
      dataIndex: 'updateTime',
      valueType: 'date',
    },
    { title: 'Community', dataIndex: 'visitorCommunity' },
    // { title: 'Unit', dataIndex: 'inviterAddress' },
    {
      title: 'Unit No',
      dataIndex: 'inviterAddress',
      render: (text: any) => <span>{text}</span>,
    },
    // ["Actions",null, (text: any, record: any) => (<Space size="middle"> <a>Detail</a></Space>)],
  ];

  const CallBackTitleSearch = (values: any) => {
    console.log(values);

    // visitorCommunity
    TosVisitorRecordGet({
      visitorCommunity: values.inviterAddress,
    });
  };

  const [form] = Form.useForm();
  // 分页
  const pagination: any = {
    defaultCurrent: 1,
    total: Data != null ? Data.length : 0,
    defaultPageSize: 12,
    showSizeChanger: false,
    showTitle: false,
    showTotal: false,
    size: 'default',
  };

  // 搜索配置
  // const searchInfo = {
  //   filterType: 'light',
  //   searchText: 'Search',
  //   resetText: 'Reset',
  // };

  // 多条件筛选
  //@param condition 过滤条件
  //@param data 需要过滤的数据
  let filter = (condition: any, data: any) => {
    return data.filter((item: any) => {
      return Object.keys(condition).every((key) => {
        return String(item[key])
          .toLowerCase()
          .includes(String(condition[key]).trim().toLowerCase());
      });
    });
  };

  // 点击搜索
  const onSubmitForm = (value: any) => {
    // 小区更换为数组
    // value.visitorCommunity = value.community.value;
    let visitorCommunity = value.community.value;
    delete value.community;

    if (value.showTime) {
      value.showTime = moment(value.showTime).format('YYYY-MM-DD');
    }
    // 有的话需要先转换 否则会被清除
    // 清除 undefind
    let info = JSON.parse(stringifyNoEmptyField(value));

    if (info.showTime) {
      info.showTime = moment(info.showTime).format('YYYY-MM-DD');
    }

    // 所有字符串条件检索出来的结果
    let Datas = filter(info, DataSave);

    let newArr = [];

    // 开始数组处理
    if (visitorCommunity.length > 0) {
      for (let i in Datas) {
        if (visitorCommunity.indexOf(Datas[i].visitorCommunity) != -1) {
          newArr.push(Datas[i]);
        }
      }
    } else {
      // 没有选小区
      newArr = Datas;
    }

    SA(newArr, module, dispatch);
  };

  // 点击重置
  const onResetFrom = () => {
    form.resetFields();
    onReset();
  };

  // 刷新
  const onReset = () => {
    SA(DataSave, module, dispatch);
    RA(26, { inviterAddress: '', visitorCommunity: '' }, module, dispatch);
  };

  // 去掉null  undefined 无效字段
  function removeEmptyField(obj: any) {
    var newObj = {};
    if (typeof obj == 'string') {
      obj = JSON.parse(obj);
    }
    if (obj instanceof Array) {
      newObj = [];
    }
    if (obj instanceof Object) {
      for (var attr in obj) {
        if (
          obj.hasOwnProperty(attr) &&
          obj[attr] !== '' &&
          obj[attr] !== null &&
          obj[attr] !== undefined
        ) {
          if (obj[attr] instanceof Object) {
            newObj[attr] = removeEmptyField(obj[attr]);
          } else if (
            typeof obj[attr] == 'string' &&
            ((obj[attr].indexOf('{') > -1 && obj[attr].indexOf('}') > -1) ||
              (obj[attr].indexOf('[') > -1 && obj[attr].indexOf(']') > -1))
          ) {
            try {
              var attrObj = JSON.parse(obj[attr]);
              if (attrObj instanceof Object) {
                newObj[attr] = removeEmptyField(attrObj);
              }
            } catch (e) {
              newObj[attr] = obj[attr];
            }
          } else {
            newObj[attr] = obj[attr];
          }
        }
      }
    }
    return newObj;
  }
  function stringifyNoEmptyField(obj: any) {
    var newObj = removeEmptyField(obj);
    for (var attr in newObj) {
      if (newObj.hasOwnProperty(attr) && newObj[attr] instanceof Array) {
        newObj[attr] = JSON.stringify(newObj[attr]);
      }
    }
    return JSON.stringify(newObj);
  }

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

  return (
    <>
      <div className="VisitorRecord">
        <Form
          autoComplete="off"
          layout="inline"
          form={form}
          name="contract"
          onFinish={onSubmitForm}
        >
          {/* <Form.Item name="visitorCommunity">
            <SearchOptionsCommnity
              // ubmit={extendName}
              opname={opname}
            />
          </Form.Item> */}

          <Form.Item name="inviterName">
            <Input allowClear placeholder="Invitees Name" style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="showTime">
            <DatePicker format="YYYY-MM-DD" placeholder="Visitor Time" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
              Search{' '}
            </Button>
            <Button
              htmlType="button"
              onClick={onReset}
              style={{ marginLeft: '15px' }}
              icon={<ClearOutlined />}
              loading={loading}
            >
              {' '}
              Reset
            </Button>
          </Form.Item>
          <div style={{ marginTop: 24, marginRight: -16, width: 'calc(100% + 16px)' }}>
            <Form.Item name="community" label="">
              <SelectCommunity />
            </Form.Item>
          </div>
        </Form>
      </div>
      <div style={{ width: '100%', padding: '0px 15px 15px 15px', backgroundColor: '#ffffff' }}>
        <ProTable
          loading={loading}
          rowKey="id"
          dataSource={Data != null ? Data : ''}
          columns={columns}
          pagination={pagination}
          // pagination={{ current: 1, total: Data.total}}
          search={false}
          options={{
            density: false,
            fullScreen: false,
            reload: () => {
              onReset();
            },
            setting: false,
          }}
          headerTitle="Visitor List"
          onReset={onResetFrom}
          onSubmit={onSubmitForm}
        />
      </div>
    </>
  );
};

function map(state: any) {
  const { Data, DataSave } = state[module];
  const loading = state.loading.models.VisitorRecord;
  return { Data, DataSave, loading };
}
export default connect(map)(VisitorRecord);
// 备注
// 列表缺少访客时间
// 搜索缺少到达时间、访客姓名
