import React, { useEffect, useState } from 'react';
import { Card, Select, message, Spin, Space } from 'antd';
import { DatePicker, Button, Tabs, Table, Col, Row } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import moment from 'moment';
import API from "./service";
import styles from './index.css';
import { PageContainer } from '@ant-design/pro-layout';
import  DetailsList  from './components/DetailsList';
const { RangePicker } = DatePicker;

const { TabPane } = Tabs;





export default () => {
  const [tabIndex, setTabIndex] = useState(1);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [ReservationGoods, setReservationGoods] = useState([]);
  const [ReservationOrg, setReservationOrg] = useState([]);
  const [ReservationUser, setReservationUser] = useState([]);
  const [ReservationGoodsDetailed, setReservationGoodsDetailed] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const [createModalVisible, handleModalVisible] = useState(false);
  const [getuser, setuser] = useState();
  const [timeRange, setTimeRange] = useState([
    moment(moment(new Date(Date.now() + 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 00:00:00')),
    moment(moment(new Date(Date.now() + 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 23:59:59')),
  ]);	//日期选择器

  const ReservationGoodsColums = [
    {
      title: '商品',
      dataIndex: 'name',
    },
    {
      title: '用餐时段',
      dataIndex: 'mealType',
      render: (_, record) => {
        if (record.mealType === '1') {
          return '早餐'
        }
        if (record.mealType === '2') {
          return '午餐'
        }
        if (record.mealType === '3') {
          return '晚餐'
        }
      }
    },
    {
      title: '预定数量',
      dataIndex: 'qty',
      sortDirections: ['ascend', 'descend'],
      sorter: (a, b) => a.value - b.value
    },
    {
      title: '预定时间',
      dataIndex: 'createAt',
    }
  ]

  const ReservationGoodsDetailedColums = [
    {
      title: '商品',
      dataIndex: 'name',
    },
    {
      title: '预定部门',
      dataIndex: 'orgName'
    },
    {
      title: '预定人姓名',
      dataIndex: 'realName'
    },

    {
      title: '用餐时段',
      dataIndex: 'mealType',
      render: (_, record) => {
        if (record.mealType === '1') {
          return '早餐'
        }
        if (record.mealType === '2') {
          return '午餐'
        }
        if (record.mealType === '3') {
          return '晚餐'
        }
      }
    },
    {
      title: '预定数量',
      dataIndex: 'qty',
      sortDirections: ['ascend', 'descend'],
      sorter: (a, b) => a.value - b.value
    },

    {
      title: '是否统一预定',
      dataIndex: 'qty',
      render: (_, record) => {
        if (record.qty>2) {
          return '是'
        }else { return '否'}
      }
    },
    {
      title: '预定时间',
      dataIndex: 'createAt',
    }
  ]

  const ReservationOrgColums = [
    {
      title: '部门名称',
      dataIndex: 'orgName',
    },
    {
      title: '用餐时段',
      dataIndex: 'mealType',
      render: (_, record) => {
        if (record.mealType === '1') {
          return '早餐'
        }
        if (record.mealType === '2') {
          return '午餐'
        }
        if (record.mealType === '3') {
          return '晚餐'
        }
      }
    },
    {
      title: '预定数量',
      dataIndex: 'qty',
      sortDirections: ['ascend', 'descend'],
      sorter: (a, b) => a.value - b.value
    }
  ]
  const ReservationUserColums = [
    {
      title: '预定人员名称',
      dataIndex: 'name',
    },
    {
      title: '部门',
      dataIndex: 'orgName',
    },
    {
      title: '预定数量',
      dataIndex: 'qty',
      sortDirections: ['ascend', 'descend'],
      sorter: (a, b) => a.value - b.value
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setuser(record);
            }}
          >
            查看详情
          </a>
        </>
      ),
    }
  ]



  //部门
  const [department, setDepartMent] = useState([]);
  const [currentDepartment, setCurrentDepartment] = useState();
  //用餐时间
  const [dinnerTimeSelect, setDinnerTimeSelect] = useState([
    {
      value: 1,
      label: '早餐',
    },
    {
      value: 2,
      label: '中餐',
    },
    {
      value: 3,
      label: '晚餐',
    }
  ]);
  const [dinnerTime, setDinnerTime] = useState();

  /**
   * 获取部门分页
   */
  const onFetchDetartment = async () => {
    const response = await API.GetDeparent({
      current: 1,
      pageSize: 9999,
      platformType: "4"
    });
    if (response.statusCode === 200) {
      const depart = [];
      response.data?.data?.forEach(item => {
        depart.push({
          label: item.name,
          value: item.id
        });
      });
      setDepartMent(depart);
    }
  }

  //初始化数据
  const initData = () => {
    const findDepart = department.find(item => item.value === currentDepartment);
    let jsonData = {
      beginTime: timeRange[0]._i,
      endTime: timeRange[1]._i,
      orgName: findDepart?.label || '',
      mealType: dinnerTime || '',
      current: currentPage,
      pageSize
    }
    if (tabIndex == 1) {
      onGetReservationGoodsData(jsonData);
    } else if (tabIndex == 2)  {
      onGetReservationUserData(jsonData);
    }else if (tabIndex == 3)  {
      onGetReservationOrgData(jsonData);
    }else if (tabIndex == 4)  {
      onGetReservationGoodsDetailed(jsonData);
    }
  }

  //获取预定商品
  const onGetReservationGoodsData = async (jsonData) => {
    let response;
    setIsLoading(true);
    response = await API.GetReservationGoods(jsonData);
    setIsLoading(false);
    if (response.succeeded) {
      let sortArr = response.data.data.sort((a, b) => b.value - a.value);
      setReservationGoods(sortArr);
    } else {
      console.log('Message:', response.msg || '获取预定商品失败');
    }
  }

  const onGetReservationOrgData = async (jsonData) => {
    let response;
    setIsLoading(true);
    response = await API.GetReservationOrg(jsonData);
    setIsLoading(false);
    if (response.succeeded) {
      let sortArr = response.data.data.sort((a, b) => b.value - a.value);
      setReservationOrg(sortArr);
    } else {
      console.log('Message:', response.msg || '获取预定商品失败');
    }
  }

  //获取预定人员
  const onGetReservationUserData = async (jsonData) => {
    let response;
    setIsLoading(true);
    response = await API.GetReservationUser(jsonData);
    setIsLoading(false);
    if (response.succeeded) {
      let sortArr = response.data.data.sort((a, b) => b.value - a.value);
      setReservationUser(sortArr);
    } else {
      console.log('Message:', response.msg || '获取预定人员失败');
    }
  }
  //获取预定人员
  const onGetReservationGoodsDetailed = async (jsonData) => {
    let response;
    setIsLoading(true);
    response = await API.GetReservationGoodsDetailed(jsonData);
    setIsLoading(false);
    if (response.succeeded) {
      let sortArr = response.data.data.sort((a, b) => b.value - a.value);
      setTotal(response.data.total);
      setReservationGoodsDetailed(sortArr);
    } else {
      console.log('Message:', response.msg || '获取预定人员失败');
    }
  }

  const MyLoading = () => {
    return (
      <Spin className={styles['my-loading']} size="large" />
    )
  }

  const onExportGoodsExcel = async () => {
    const findDepart = department.find(item => item.value === currentDepartment);
    let jsonData = {
      beginTime: timeRange[0]._i,
      endTime: timeRange[1]._i,
      orgName: findDepart?.label || '',
      mealType: dinnerTime || '',
      current: currentPage,
      pageSize
    }
    API.GetReservationGoodsExcel(jsonData).then((res) => {
      let url = URL.createObjectURL(new Blob([res]));
      let filename = '预定商品汇总.xlsx';
      let a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    });
  }

  const onExportUserExcel = async () => {
    const findDepart = department.find(item => item.value === currentDepartment);
    let jsonData = {
      beginTime: timeRange[0]._i,
      endTime: timeRange[1]._i,
      orgName: findDepart?.label || '',
      mealType: dinnerTime || '',
      current: currentPage,
      pageSize
    }
    API.GetReservationUserExcel(jsonData).then((res) => {
      let url = URL.createObjectURL(new Blob([res]));
      let filename = '获取预定人员明细.xlsx';
      let a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    });
  }
  const onExportOrgExcel = async () => {
    const findDepart = department.find(item => item.value === currentDepartment);
    let jsonData = {
      beginTime: timeRange[0]._i,
      endTime: timeRange[1]._i,
      orgName: findDepart?.label || '',
      mealType: dinnerTime || '',
      current: currentPage,
      pageSize
    }
    API.GetReservationOrgExcel(jsonData).then((res) => {
      let url = URL.createObjectURL(new Blob([res]));
      let filename = '预定部门汇总.xlsx';
      let a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    });
  }
  const onExportGoodsDetailedExcel = async () => {
    const findDepart = department.find(item => item.value === currentDepartment);
    let jsonData = {
      beginTime: timeRange[0]._i,
      endTime: timeRange[1]._i,
      orgName: findDepart?.label || '',
      mealType: dinnerTime || '',
      current: currentPage,
      pageSize
    }
    API.GetReservationGoodsDetailedExcel(jsonData).then((res) => {
      let url = URL.createObjectURL(new Blob([res]));
      let filename = '预定商品明细.xlsx';
      let a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    });
  }


  useEffect(() => {
    onFetchDetartment();
  }, []);
  useEffect(() => {
    initData();
  }, [tabIndex, currentPage]);

  return (
    <PageContainer>
      <div className={styles['welcome-container']}>
        {isLoading ? <MyLoading></MyLoading> : null}
        <Card style={{ marginBottom: '30px' }}>
          <Row>
            <Col xs={24} sm={12} md={12} lg={12} xl={6} style={{ margin: '10px 0' }}>
              <div className={styles['echarts-card-choose']}>
                <div className={styles['echarts-card-choose-text']}>
                  起止时间：
                </div>
                <RangePicker style={{ width: '70%' }} className={styles['my-range-picker']} value={timeRange} onChange={(date, dateStrings) => {
                  let tempDate = [
                    moment(moment(new Date(dateStrings[0])).format('YYYY-MM-DD 00:00:00')),
                    moment(moment(new Date(dateStrings[1])).format('YYYY-MM-DD 23:59:59')),
                  ]
                  setTimeRange(tempDate);
                }} />
              </div>
            </Col>
            <Col xs={24} sm={12} md={12} lg={12} xl={6} style={{ margin: '10px 0' }}>
              <div className={styles['echarts-card-choose']}>
                <div className={styles['echarts-card-choose-text']}>
                  所属部门：
                </div>
                <Select
                  placeholder='请选择部门！'
                  style={{ width: '70%' }}
                  value={currentDepartment}
                  onChange={setCurrentDepartment}
                  options={department}
                />
              </div>
            </Col>
            <Col xs={24} sm={12} md={12} lg={12} xl={6} style={{ margin: '10px 0' }}>
              <div className={styles['echarts-card-choose']}>
                <div className={styles['echarts-card-choose-text']}>
                  用餐时段：
                </div>
                <Select
                  placeholder='请选择用餐时段！'
                  style={{ width: '70%' }}
                  value={dinnerTime}
                  onChange={setDinnerTime}
                  options={dinnerTimeSelect}
                />
              </div>
            </Col>
            <Col xs={24} sm={12} md={12} lg={12} xl={6} style={{ margin: '10px 0' }}>
              <Button className={styles['echarts-card-btn']} type="primary" style={{ width: '100px', marginRight: '10px' }} onClick={() => initData()}>查询</Button>
              <Button className={styles['echarts-card-btn']} style={{ width: '100px' }} onClick={() => {
                setTimeRange([
                  moment(moment(new Date(Date.now() + 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 00:00:00')),
                  moment(moment(new Date(Date.now() + 24 * 60 * 60 * 1000)).format('YYYY-MM-DD 23:59:59')),
                ]);
                setCurrentDepartment();
                setDinnerTime();
                setCurrentPage(1);
                setPageSize(10)
              }}>重置</Button>
            </Col>
          </Row>
        </Card>
        <Card>
          <Tabs tabPosition='left' value={tabIndex} onChange={value =>  {setTabIndex(value); setTotal(0); setCurrentPage(1)}}>
            <TabPane tab="预定菜品汇总" key={1}>
              {
                tabIndex == 1 && <>
                  <Space style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                    <div className={styles['tabs-title']}>
                    预定菜品汇总
                    </div>
                    <Button type="primary" icon={<DownloadOutlined />} size="middle" onClick={onExportGoodsExcel}>
                      报表下载
                    </Button>
                  </Space>
                  <Table
                    columns={ReservationGoodsColums}
                    dataSource={ReservationGoods}
                    pagination={{ current: currentPage, pageSize: pageSize,total , onChange: setCurrentPage, onShowSizeChange: (current, size) => setPageSize(size) }} />
                </>
              }
            </TabPane>
            <TabPane tab="部门预定汇总" key={3}>
              {
                tabIndex == 3 && <>
                  <Space style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                    <div className={styles['tabs-title']}>
                    部门预定汇总
                    </div>
                    <Button type="primary" icon={<DownloadOutlined />} size="middle" onClick={onExportOrgExcel}>
                      报表下载
                    </Button>
                  </Space>
                  <Table
                    columns={ReservationOrgColums}
                    dataSource={ReservationOrg}
                    pagination={{ current: currentPage, pageSize: pageSize, total, onChange: setCurrentPage, onShowSizeChange: (current, size) => setPageSize(size) }} />
                </>
              }
            </TabPane>
            <TabPane tab="预定人员明细" key={2}>
              {
                tabIndex == 2 && <>
                  <Space style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                    <div className={styles['tabs-title']}>
                    预定人员明细
                    </div>
                    <Button type="primary" icon={<DownloadOutlined />} size="middle" onClick={onExportUserExcel}>
                      报表下载
                    </Button>
                  </Space>
                  <Table
                    columns={ReservationUserColums}
                    dataSource={ReservationUser}
                    pagination={{ current: currentPage, pageSize: pageSize, onChange: setCurrentPage, onShowSizeChange: (current, size) => setPageSize(size) }}
                  />
                </>
              }
            </TabPane> <TabPane tab="预定商品明细" key={4}>
              {
                tabIndex == 4 && <>
                  <Space style={{ display: 'flex', alignItems: 'center', marginBottom: '10px' }}>
                    <div className={styles['tabs-title']}>
                    预定商品明细
                    </div>
                    <Button type="primary" icon={<DownloadOutlined />} size="middle" onClick={onExportGoodsDetailedExcel}>
                      报表下载
                    </Button>
                  </Space>
                  <Table
                    columns={ReservationGoodsDetailedColums}
                    dataSource={ReservationGoodsDetailed}
                    pagination={{ current: currentPage, pageSize: pageSize, total, onChange: setCurrentPage, onShowSizeChange: (current, size) => setPageSize(size) }}
                  />
                </>
              }
            </TabPane>
          </Tabs>
        </Card>
      </div>
      {
        createModalVisible && <DetailsList
          createModalVisible={true}
          values={getuser || {}}
          timeRange={timeRange}
          onCancel={() => {
            handleModalVisible(false);
            setuser(undefined);
          }}
        ></DetailsList>
      }
    </PageContainer>
  );
};
