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

import { Input, Tabs, Pagination, Space, Button } from 'antd';
const { TabPane } = Tabs;

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

import { objectColumns } from '../../../utils/string';
import { timestampToTime } from '../../../utils/time';
import TitleSearch from '../../../components/TitleSearch/TitleSearch';

// const managerFeeStatusDes= ["未交", "已交", "已退"]
// const marginFeeStatusDes = ["未交", "已交", "未退", "已退部分", "已退全部"]
// const statusDes = ["全部", "已申请", "已预订", "已使用", "已取消", "已完成"]

const managerFeeStatusDes = ['Not paid', 'Paid', 'Returned'];
const marginFeeStatusDes = ['Not paid', 'Paid', 'Not Returned', 'Returned part', 'Returned all'];
const statusDes = ['All', 'Applied', 'Reserved', 'Used', 'Cancelled', 'Completed'];

import './css/index.less';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';

import moment from 'moment';

const FacilityBookings = (props: any) => {
  const { formatMessage } = useIntl();

  const { dispatch, location, Data, Data2, token, DataSave, curString, Result, loading } = props;

  // console.log(Data2);

  const RA = (index: any, values: any) => {
    dispatch({
      type: 'FacilityBookings/RA',
      playload: { index: index, body: values },
    });
  };
  const SA = (values: any) => {
    dispatch({ type: 'FacilityBookings/SA', playload: values });
  };
  const QA = (values: any) => {
    dispatch({ type: 'FacilityBookings/QA', playload: values });
  };
  const IA = () => {
    dispatch({ type: 'FacilityBookings/IA' });
  };
  const CA = () => {
    dispatch({ type: 'FacilityBookings/CA', playload: null });
  };

  const [columns, setColumns] = useState([]);
  const [columns2, setColumns2] = useState([]);

  const goToFunction = () => {
    if (curString.tab == 2) {
      CA();
      // 先清空上传图片列表
      dispatch({ type: 'FacilityBookings/overAllImgList' });
      // 在清空详情信息
      SA(null);
    } else {
      // 清空之前的数据
      SA(null);
    }
    history.push(location.pathname + (curString.tab == 1 ? '/Booking' : '/Adding'));
  };

  // 预约详情跳转
  const goToDetail = (values: any) => {
    SA(values);
    history.push(location.pathname + '/Detail');
  };

  // 列表2 点击跳转
  const makeOperator = (values: any, index: any) => {
    const path = ['/FacilityDetail', '/FacilityEdit', '/FacilityApply'];
    SA(values);
    // 清空设施列表图
    let list: any = [];
    dispatch({ type: 'FacilityBookings/genxin', list });

    history.push(location.pathname + path[index]);
  };

  useEffect(() => {
    const key = [
      ['Service Community', 'communityName'],
      ['User Name', 'accountName'],
      ['Facility Bookings', 'categoriesName'],
      [
        'Order Time',
        null,
        (text: any, record: any) => (
          <div>{moment(record.createTime.time).format('YYYY-MM-DD')}</div>
        ),
      ],

      [
        'Booking Schedule',
        'subscribeDate',
        (text: any) => <div>{moment(text).format('YYYY-MM-DD')}</div>,
      ],
      ['Fee', 'managerFeeStatus', (text: any) => <div>{managerFeeStatusDes[text]}</div>],
      ['Deposit', 'marginFeeStatus', (text: any) => <div>{marginFeeStatusDes[text]}</div>],
      ['Status', 'status', (text: any) => <div>{statusDes[text]}</div>],

      [
        'Actions',
        null,
        (text: any, record: any) => (
          <Space size="middle">
            {' '}
            <a onClick={goToDetail.bind(this, record)}>Detail</a>
          </Space>
        ),
      ],
    ];
    const key2 = [
      ['Community', 'communityName'],
      ['Facilty', 'facilityName'],
      ['Open Time', 'categoriesOpenTime'],
      [
        'Action',
        null,
        (text: any, record: any) => (
          <Space size="middle">
            <a onClick={() => makeOperator(record, 1)}>Edit</a>
            <a onClick={() => makeOperator(record, 0)}>Detail</a>
            <a onClick={() => makeOperator(record, 2)}>Booking</a>
          </Space>
        ),
      ],
    ];
    setColumns(objectColumns(key) as any);
    setColumns2(objectColumns(key2) as any);
    if (curString.tab == 1) {
      RA(9, {
        userToken: token,
        pageNum: curString.curPage,
        subscribeDate: curString.subscribeDate,
        status: curString.status,
        communityNameList: curString.communityNameList,
      });
    } else {
      RA(8, { userToken: token, pageNum: curString.curPage2 });
    }
  }, []);

  const CallBackTitleSearch = (comment: any) => {
    if (curString.tab == 1) {
      if (comment.communityName != null || comment.key != null || comment.status != null) {
        var tmp = curString;
        tmp.subscribeDate = comment.key;
        if (comment.status == null || comment.status == undefined) {
          tmp.status = null;
        } else {
          tmp.status = comment.status;
        }
        tmp.communityNameList = comment.communityName;
        tmp.curPage = 1;
        QA(tmp);
        //中断
        RA(9, {
          userToken: token,
          pageNum: '1',
          subscribeDate: tmp.subscribeDate,
          status: tmp.status,
          communityNameList: comment.communityName,
        });
      }
    } else {
      if (comment.communityName != null || comment.facilityName != null) {
        var tmp = curString;
        tmp.communityNameList = comment.communityName;
        tmp.facilityName = comment.facilityName;
        tmp.curPage = 1;
        QA(tmp);
        RA(8, {
          communityNameList: comment.communityName,
          facilityName: comment.facilityName,
          pageNum: '1',
        });
      }
    }
  };
  function TabCallback(tab: any) {
    var tmp = curString;
    tmp.tab = tab;
    QA(tmp);
    if (tab == 1) {
      RA(9, {
        userToken: token,
        status: curString.status,
        subscribeDate: curString.subscribeDate,
        pageNum: curString.curPage,
        communityNameList: curString.communityNameList,
      });
    } else {
      RA(8, { userToken: token, pageNum: curString.curPage2 });
    }
  }
  function Pagechange(current: any, pageSize: any) {
    if (curString.tab == 1) {
      var tmp = curString;
      tmp.curPage = current;
      QA(tmp);
      RA(9, {
        userToken: token,
        pageNum: current,
        subscribeDate: curString.subscribeDate,
        status: curString.status,
        communityNameList: curString.communityNameList,
      });
    } else {
      var tmp = curString;
      tmp.curPage2 = current;
      QA(tmp);
      if (curString.communityNameList != null) {
        RA(8, {
          userToken: token,
          pageNum: current,
          communityNameList: curString.communityNameList,
        });
      } else {
        RA(8, { userToken: token, pageNum: current });
      }
    }
  }

  return (
    <>
      <div className="base">
        {/* 头部组件 */}
        {curString.tab == 1 ? (
          <>
            <TitleSearch
              status={[
                {
                  name: ['status', 'Order status'],
                  data: [
                    [0, 'All'],
                    [1, 'Applied'],
                    [2, 'Reserved'],
                    [3, 'Used'],
                    [4, 'Cancelled'],
                  ],
                },
              ]}
              time={['key', 'Booking time ']}
              community={'communityName'}
              checklist={curString.communityNameList != null ? curString.communityNameList : null}
              onSubmit={CallBackTitleSearch}
            />
          </>
        ) : (
          <>
            <TitleSearch
              listkey={['facilityName']}
              list={['Facility name']}
              community={'communityName'}
              onSubmit={CallBackTitleSearch}
            />
          </>
        )}
      </div>

      {/* 下方及搜索 */}
      <div className={'base'}>
        {/* <div style={{ position: 'relative', height: 40 }}>
          <Button type="primary" style={{ position: 'absolute', right: 0 }} onClick={goToFunction}>
            {curString.tab == 1 ? 'Booking' : 'Add Facility'}
          </Button>
        </div> */}

        <Tabs
          defaultActiveKey={curString.tab.toString()}
          onChange={TabCallback}
          className="diytabs"
        >
          <TabPane tab="Facility Bookings" key="1">
            <ProTable
              loading={loading}
              rowKey="id"
              dataSource={Data ? Data.list : null}
              columns={columns}
              // pagination={{
              //   current: curString.curPage,
              //   total: Data.total.totalRow,
              //   showSizeChanger: false,
              //   onChange: Pagechange,
              // }}
              pagination={false}
              search={false}
              toolBarRender={() => [
                <Button key="3" type="primary" onClick={goToFunction}>
                  <PlusOutlined />
                  Add Appointment
                </Button>,
              ]}
              options={{
                density: false,
                fullScreen: false,
                reload: () => {
                  // onReset();
                },
                setting: false,
              }}
              // headerTitle="预约列表"
            />

            {Data ? (
              <div className="pages">
                <Pagination
                  current={curString.curPage ? curString.curPage : 0}
                  total={Data.page.totalRow ? Data.page.totalRow : 0}
                  // pageSizeOptions={[]}
                  showSizeChanger={false}
                  pageSize={Data.page.pageSize ? Data.page.pageSize : 0}
                  onChange={Pagechange}
                />
              </div>
            ) : (
              ''
            )}
          </TabPane>

          <TabPane tab="Facility Management" key="2">
            <ProTable
              loading={loading}
              rowKey="id"
              dataSource={Data2.data}
              columns={columns2}
              // pagination={{
              //   current: curString.curPage2,
              //   total: Data2.total.totalRow,
              //   showSizeChanger: false,
              //   onChange: Pagechange,
              // }}
              pagination={false} // 隐藏默认分页
              search={false}
              toolBarRender={() => [
                <Button key="3" type="primary" onClick={goToFunction}>
                  <PlusOutlined />
                  Add Facilities
                </Button>,
              ]}
              options={{
                density: false,
                fullScreen: false,
                reload: () => {
                  // onReset();
                },
                setting: false,
              }}
              // headerTitle="Facilities List"
            />

            {curString ? (
              <div className="pages">
                <Pagination
                  current={Data2.total.currentPage}
                  total={Data2.total.totalRow}
                  // pageSizeOptions={[]}
                  showSizeChanger={false}
                  // pageSize={village.page.curPageSize}
                  onChange={Pagechange}
                />
              </div>
            ) : (
              ''
            )}
          </TabPane>
        </Tabs>
      </div>
    </>
  );
};

function mapStateToProps(state: any) {
  const { Data, Data2, DataSave, curString, Result } = state.FacilityBookings;
  const { token } = state.login;
  const loading =
    typeof state.loading.models.FacilityBookings == 'undefined'
      ? true
      : state.loading.models.FacilityBookings;

  return {
    Data,
    Data2,
    DataSave,
    curString,
    Result,
    token,
    loading,
  };
}
export default connect(mapStateToProps)(FacilityBookings);

// status：预约设施状态 0:全部 1：已申请 2：已预订 3：已使用 4：已取消 5：已完成
// manager_fee_status：管理费 0：未 1：已交 2：已退
// margin_fee_status：押金 0：未 1：已交 2：未退 3：已退部分 4：已退全部 5：
