import {
  MyButtons,
  MyColumns,
  MyProTableProps,
  MyTableActions,
  MyToolBarActions,
} from '@/common';
import { showTime } from '@/common/utils/day';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import { PatrolRoutesGenerationMethodEnum } from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { Tooltip } from 'antd';
import Create from './modals/Create';
import Update from './modals/Update';

export default function Index() {
  return (
    <ProTable
      {...MyProTableProps.props}
      request={async (params, sort) =>
        MyProTableProps.request(params, sort, Apis.Patrol.PatrolRoutes.List)
      }
      toolBarRender={(action) => [
        <MyToolBarActions
          key="toolbar"
          actions={{
            create: (
              <Create key="Create" reload={action?.reload} title="路线" />
            ),
          }}
        />,
      ]}
      columns={[
        MyColumns.ID({
          search: false,
        }),
        Selects?.AssetProjects({
          title: '选择项目',
          key: 'asset_projects_id',
          hidden: true,
        }),
        {
          title: '关联项目',
          dataIndex: ['asset_project', 'name'],
          // search: {
          //   transform: (value) => {
          //     return { project_name: value };
          //   },
          // },
          search: false,
        },
        {
          title: '路线名称',
          dataIndex: 'name',
          search: true,
        },
        {
          title: '点位数',
          render: (_, item: any) => {
            const locations = item?.patrol_route_locations || [];
            const locationNames = locations
              .map((res: any) => {
                return res?.patrol_location?.name || '';
              })
              .filter(Boolean);
            const pointCount = locationNames.length;

            return (
              <Tooltip
                title={
                  locationNames.map((name: string, index: number) => (
                    <div key={index}>
                      点位{index + 1}：{name}
                    </div>
                  )) || ''
                }
              >
                <div
                  style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    maxWidth: '150px',
                  }}
                >
                  {pointCount}
                </div>
              </Tooltip>
            );
          },
        },

        MyColumns.EnumTag({
          title: '巡更周期',
          dataIndex: 'generation_method',
          valueEnum: PatrolRoutesGenerationMethodEnum,
        }),
        {
          title: '周期',
          search: false,

          render: (_, item: any) => {
            if (
              item?.generation_method ===
              PatrolRoutesGenerationMethodEnum.Daily.value
            ) {
              return '每天';
            } else if (
              item?.generation_method ===
              PatrolRoutesGenerationMethodEnum.Weekly.value
            ) {
              const dateArray = item?.date || [];
              if (dateArray.length === 0) return '每周';
              // 检查dateArray中的元素是否为对象，若是则提取weekday属性
              const weekdays = dateArray
                .map((res: any) => {
                  if (typeof res === 'object' && res !== null) {
                    return res?.weekday || '';
                  }
                  return res;
                })
                .filter(Boolean);
              return `每周${weekdays.join('/')}`;
            } else if (
              item?.generation_method ===
              PatrolRoutesGenerationMethodEnum.Monthly.value
            ) {
              const dateArray = item?.date || [];
              if (dateArray.length === 0) return '每月';
              return `每月${dateArray.join('/')}`;
            }
            return '';
          },
        },
        {
          title: '任务时段',
          search: false,
          render: (_, item: any) => {
            return `${showTime(item.task_start_time)}-${showTime(
              item.task_end_time,
            )}`;
          },
        },
        // {
        //   title: '可执行时段',
        //   search: false,
        //   render: (_, item: any) => {
        //     return `${showTime(item.clock_start_time)}-${showTime(
        //       item.clock_end_time,
        //     )}`;
        //   },
        // },
        MyColumns.Boolean({
          dataIndex: 'is_enabled',
          title: '是否启用',
        }),
        MyColumns.CreatedAt(),
        MyColumns.Option({
          render: (_, item: any, __, action) => (
            <MyTableActions
              actions={{
                update: (
                  <Update item={item} reload={action?.reload} title="路线" />
                ),
                delete: (
                  <MyButtons.Delete
                    onConfirm={() =>
                      Apis.Patrol.PatrolRoutes.Delete({ id: item.id }).then(
                        () => action?.reload(),
                      )
                    }
                  />
                ),
              }}
            />
          ),
        }),
      ]}
    />
  );
}
