import {
  MyButtons,
  MyColumns,
  MyPageContainer,
  MyProTableProps,
  MyTableActions,
  MyToolBarActions,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import { AttendanceSchedulesStatusEnum } from '@/gen/Enums';
import AttendanceConfigs from '@/pages/attendance/attendance_configs';
import AttendanceShifts from '@/pages/attendance/attendance_shifts';
import { ProTable } from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Modal, Space, Tooltip } from 'antd';
import { useState } from 'react';
import Update from './modals/Update';
import ViewCalendar from './modals/ViewCalendar';

export default function Index({ title = '排班管理' }) {
  const navigate = useNavigate();
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [shiftModalVisible, setShiftModalVisible] = useState(false);

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="attendance_schedules"
      tabLabel={title}
    >
      <ProTable
        {...MyProTableProps.props}
        request={async (params, sort) =>
          MyProTableProps.request(
            { ...params, status: AttendanceSchedulesStatusEnum.Active.value },
            sort,
            Apis.Attendance.AttendanceSchedules.List,
          )
        }
        headerTitle="排班信息"
        toolBarRender={() => [
          <MyToolBarActions
            key="toolbar"
            actions={{
              add: (
                <MyButtons.Default
                  key="Create"
                  size="middle"
                  type="primary"
                  onClick={() => {
                    navigate('/attendance/attendance_schedules/pages/create');
                  }}
                  title="批量排班"
                />
              ),
              config: (
                <MyButtons.Default
                  key="Config"
                  size="middle"
                  onClick={() => setConfigModalVisible(true)}
                  title="打卡配置"
                />
              ),
              shift: (
                <MyButtons.Default
                  key="Shift"
                  size="middle"
                  onClick={() => setShiftModalVisible(true)}
                  title="班次管理"
                />
              ),
            }}
          />,
        ]}
        columns={[
          // MyColumns.ID({
          //   search: false,
          // }),

          Selects?.OrganizationsTree({
            title: '选择组织',
            key: 'organizations_id',
            search: {
              transform: (value) => {
                return { organizations_id: value[value.length - 1] };
              },
            },
          }),
          {
            title: '排班日期',
            dataIndex: 'schedule_date',
            valueType: 'date',
            sorter: (a, b) =>
              new Date(a.schedule_date).getTime() -
              new Date(b.schedule_date).getTime(),
          },
          {
            title: '所在组织',
            dataIndex: 'organization_path',
            search: false,
            // search: {
            //   transform: (value) => {
            //     return { organization_name: value };
            //   },
            // },
          },

          {
            title: '员工',
            dataIndex: ['company_employee', 'name'],
            sorter: (a, b) =>
              a?.company_employee?.name?.localeCompare?.(
                b?.company_employee?.name ?? '',
              ) ?? 0,
            search: {
              transform: (value) => {
                return { employee_name: value };
              },
            },
          },
          {
            title: '班次',
            dataIndex: ['attendance_shift', 'name'],
            search: false,
          },
          {
            title: '时段要求',
            dataIndex: 'shift_periods',
            search: false,
            render: (_, item: any) => {
              const periods = item?.shift_periods || [];
              const periodTexts = periods.map((res: any) => {
                return `时段${
                  res?.period_order
                }: ${res?.work_start_time?.substring(
                  0,
                  5,
                )}-${res?.work_end_time?.substring(0, 5)}`;
              });
              const allPeriodsText = periodTexts.join(' ');

              return (
                <Tooltip
                  title={
                    periodTexts.map((text: string, index: number) => (
                      <div key={index}>{text}</div>
                    )) || ''
                  }
                >
                  <div
                    style={{
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      maxWidth: '150px',
                    }}
                  >
                    {allPeriodsText}
                  </div>
                </Tooltip>
              );
            },
          },

          // MyColumns.EnumTag({
          //   title: '状态',
          //   dataIndex: 'status',
          //   valueEnum: AttendanceSchedulesStatusEnum,
          // }),
          {
            title: '排班人',
            dataIndex: ['created_employee', 'name'],
            search: false,
          },
          MyColumns.UpdatedAt(),
          MyColumns.Option({
            render: (_, item: any, index, action) => (
              <Space key={index}>
                <MyTableActions
                  actions={{
                    view: <ViewCalendar item={item} reload={action?.reload} />,
                    update: (
                      <Update
                        item={item}
                        reload={action?.reload}
                        title={title}
                      />
                    ),
                    cancel: (
                      <MyButtons.Default
                        disabled={item?.status === 'Cancelled'}
                        isConfirm
                        title="取消"
                        danger
                        description="是否确定取消排班?"
                        onConfirm={() =>
                          Apis.Attendance.AttendanceSchedules.Cancel({
                            id: item.id,
                          }).then(() => action?.reload())
                        }
                      />
                    ),
                  }}
                />
              </Space>
            ),
          }),
        ]}
      />
      <Modal
        title="打卡配置"
        open={configModalVisible}
        onCancel={() => setConfigModalVisible(false)}
        width={1200}
        footer={null}
        destroyOnClose
      >
        <AttendanceConfigs noPermission />
      </Modal>
      <Modal
        title="班次管理"
        open={shiftModalVisible}
        onCancel={() => setShiftModalVisible(false)}
        width={1200}
        footer={null}
        destroyOnClose
      >
        <AttendanceShifts noPermission />
      </Modal>
    </MyPageContainer>
  );
}
