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(50);
  const [total, setTotal] = useState(0);
  const [DayConsumeInfo, setDayConsumeInfo] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [getorg, setorg] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  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 DayConsumeInfoColums = [
    {
      title: '用餐部门',
      dataIndex: 'mname',
    },
    {
      title: '用餐时段',
      dataIndex: 'timeInterval',
      render: (_, record) => {
        if (record.timeInterval === '1') {
          return '早餐'
        }
        if (record.timeInterval === '2') {
          return '午餐'
        }
        if (record.timeInterval === '3') {
          return '晚餐'
        }
      }
    },
    {
      title: '用餐数量',
      dataIndex: 'sumqty',
      sortDirections: ['ascend', 'descend'],
      sorter: (a, b) => a.value - b.value
    },
    {
      title: '预定部门',
      dataIndex: 'orgName',
    },
    {
      title: '预定人员',
      dataIndex: 'nickName',
    },
    {
      title: '预定用餐时段',
      dataIndex: 'mealType',
      render: (_, record) => {
        if (record.mealType === '1') {
          return '早餐'
        }
        if (record.mealType === '2') {
          return '午餐'
        }
        if (record.mealType === '3') {
          return '晚餐'
        }
      }
    },
    {
      title: '预定数量',
      dataIndex: 'rqty',
      sortDirections: ['ascend', 'descend'],
      sorter: (a, b) => a.value - b.value
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setorg(record);
            }}
          >
            查看详情
          </a>
        </>
      ),
    }
  ]

  useEffect(() => {
    initData();
  }, [tabIndex, currentPage]);
  const initData = () => {
    const findDepart = department.find(item => item.value === currentDepartment);
    let jsonData = {
      startTime: timeRange[0]._i,
      endTime: timeRange[1]._i,
      orgName: findDepart?.label || '',
      mealType: dinnerTime || '',
      current: currentPage,
      pageSize
    }
    if (tabIndex == 1) {
      onGetDayConsumeInfoData(jsonData);
    }
  }
  //预定用餐情况
  const onGetDayConsumeInfoData = async (jsonData) => {
    let response;
    setIsLoading(true);
    response = await API.GetDayConsumeInfo(jsonData);
    setIsLoading(false);
    if (response.succeeded) {
      let sortArr = response.data.data.sort((a, b) => b.value - a.value);
      setTotal(response.data.total);
      setDayConsumeInfo(sortArr);
    } else {
      console.log('Message:', response.msg || '获取预定商品失败');
    }
  }

  //部门
  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 getColumns = (columns) => {
//     console.log('columns',columns);
//     columns.map(column => {
//     column.render = (text, record, index) =>{
//       if(column.dataIndex === 'mname') {
//         if(index === DayConsumeInfo.length - 1) {
//           return <strong>总计</strong>
//         } else  {
//           return text
//         }
//       }
//       if(column.dataIndex === 'sumqty') {
//         if(index === DayConsumeInfo.length - 1) {
//           return <strong>{11}</strong>
//         } else  {
//           return text
//         }
//       }
//       if(column.dataIndex === 'rqty') {
//         if(index === DayConsumeInfo.length - 1) {
//           return <strong>{11}</strong>
//         } else  {
//           return text
//         }
//       }
//       else {
//         if(index === DayConsumeInfo.length - 1) {
//           return <strong>{11}</strong>
//         }else  {
//           return text
//         }
//       }
//     }
//   })
//   return columns
// }






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

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

  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={DayConsumeInfoColums}//{getColumns(DayConsumeInfoColums)}
                    dataSource={DayConsumeInfo}

                    pagination={{ current: currentPage, pageSize: pageSize,total , onChange: setCurrentPage, onShowSizeChange: (current, size) => setPageSize(size) }} />
                </>
              }
            </TabPane>
          </Tabs>
        </Card>
      </div>

      {
        createModalVisible && <DetailsList
          createModalVisible={true}
          values={getorg || {}}
          timeRange={timeRange}
          onCancel={() => {
            handleModalVisible(false);
            setorg(undefined);
          }}
        ></DetailsList>
      }
    </PageContainer>
  );
};
