import React, { useState, useEffect } from 'react';
import { Segmented } from 'antd';
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
import './index.less';
import { useSelector } from 'react-redux';
// import styled from 'styled-components';

const OrderTab = () => {
  const { operationPermissionsList } = useSelector((state) => state.user);
  const navigate = useNavigate();

  // const [selectedOption, setSelectedOption] = useState(1);
  const [selectedOption, setSelectedOption] = useState(() => {
    return parseInt(localStorage.getItem('selectedOption'), 10) || 1;
  });

  useEffect(() => {
    if (selectedOption !== parseInt(localStorage.getItem('selectedOption'), 10)) {
      localStorage.setItem('selectedOption', selectedOption.toString());
    }
  }, [selectedOption]);

  const location = useLocation();

  useEffect(() => {
    // 当路由改变时，根据当前路径设置selectedOption
    if (location.pathname === '/books/order-management/dataset') {
      setSelectedOption(1);
      localStorage.setItem('selectedOption', '1');
    } else if (location.pathname === '/books/order-management/sale-statistics') {
      setSelectedOption(2);
      localStorage.setItem('selectedOption', '2');
    }
  }, [location.pathname, setSelectedOption]);

  let options = [];
  if (
    operationPermissionsList.includes('/books/order-management/getOrderList') &&
    operationPermissionsList.includes('/books/order-management/salesStatistics')
  ) {
    options = [
      {
        label: '订单列表',
        value: 1,
      },
      {
        label: '销售统计',
        value: 2,
      },
    ];
  } else if (operationPermissionsList.includes('/books/order-management/getOrderList1')) {
    options = [
      {
        label: '订单列表',
        value: 1,
      },
    ];
  } else if (operationPermissionsList.includes('/books/order-management/salesStatistics')) {
    options = [
      {
        label: '销售统计',
        value: 2,
      },
    ];
  }

  const onChange = (value) => {
    setSelectedOption(value);
    localStorage.setItem('selectedOption', value.toString());

    switch (value) {
      case 1: {
        navigate('/books/order-management/dataset');
        break;
      }
      case 2: {
        navigate('/books/order-management/sale-statistics');
        break;
      }
    }
  };

  return (
    <div style={{ maxHeight: 790 }} className='salesTop'>
      <Segmented
        options={options}
        onChange={onChange}
        value={selectedOption}
        style={{ marginBottom: 20 }}
      ></Segmented>
      <Outlet />
    </div>
  );
};

export default OrderTab;
