import { MyButtons, MyColumns, MyProTableProps } from '@/common';
import { Apis } from '@/gen/Apis';
import {
  HouseWorkOrdersAssignStatusEnum,
  HouseWorkOrdersLevelEnum,
  HouseWorkOrdersLocationEnum,
  HouseWorkOrdersStatusEnum,
  HouseWorkOrdersTypeEnum,
} from '@/gen/Enums';
import { ProTable } from '@ant-design/pro-components';
import { useSearchParams } from '@umijs/max';
import { Image, Space } from 'antd';
import AssignQuick from '../modals/AssignQuick';
import WorkOrderAssign from '../modals/WorkOrderAssign';
import WorkOrderCreate from '../modals/WorkOrderCreate';
import WorkOrderShow from '../modals/WorkOrderShow';
import WorkOrderUpdate from '../modals/WorkOrderUpdate';

export default function Index({ title = '工单管理' }) {
  const [searchParams, setSearchParams]: any = useSearchParams();
  return (
    <ProTable<Record<any, any>>
      {...MyProTableProps.props}
      headerTitle="工单列表"
      request={async (params, sort) => {
        setSearchParams(params);
        return MyProTableProps.request(
          !searchParams?.get('page')
            ? {
                status: searchParams?.get('status') || '',
                is_rework: searchParams?.get('is_rework') || '',
                ...params,
                type: [
                  HouseWorkOrdersTypeEnum.Repair.value,
                  HouseWorkOrdersTypeEnum.Incident.value,
                ],
              }
            : params,
          sort,
          Apis.WorkOrder.HouseWorkOrders.List,
        );
      }}
      toolBarRender={(action) => [
        <WorkOrderCreate key="Create" reload={action?.reload} title={title} />,
      ]}
      columns={[
        MyColumns.ID({ search: false }),
        MyColumns.EnumTag({
          title: '工单状态',
          dataIndex: 'status',
          valueEnum: HouseWorkOrdersStatusEnum,
          fieldProps: {
            defaultValue: searchParams?.get('status') || undefined,
          },
        }),
        MyColumns.EnumTag({
          title: '工单类型',
          dataIndex: 'type',
          valueEnum: HouseWorkOrdersTypeEnum,
        }),
        MyColumns.EnumTag({
          title: '报修位置',
          dataIndex: 'location',
          valueEnum: HouseWorkOrdersLocationEnum,
        }),
        {
          title: '房屋信息',
          dataIndex: ['asset_house', 'full_name'],
          search: false,
          ellipsis: true,
        },
        {
          title: '工单描述',
          dataIndex: 'content',
          search: false,
          width: 120, // 关键：固定列宽（若父容器过窄，可设 minWidth: 200 优先保证列宽）
          render: (text) => (
            <div
              style={{
                width: '100%', // 继承列宽
                // height: '60px', // 设置固定高度，约显示3行文本
                overflow: 'hidden', // 超出隐藏
                textOverflow: 'ellipsis', // 省略号
                display: '-webkit-box',
                WebkitBoxOrient: 'vertical',
                WebkitLineClamp: 1, // 显示3行
              }}
            >
              {text}
            </div>
          ),
        },
        {
          title: '附件',
          dataIndex: 'attachments',
          search: false,
          render: (_, record) => {
            if (
              !Array.isArray(record.attachments) ||
              record.attachments.length === 0
            ) {
              return '无附件';
            }
            return (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {record.attachments.map((item: any, index: number) => {
                  if (item.type && item.type.includes('image')) {
                    return (
                      <Image
                        key={index}
                        width={40}
                        height={30}
                        src={item.url}
                        style={{
                          marginRight: 8,
                          marginBottom: 8,
                          objectFit: 'cover',
                        }}
                      />
                    );
                  } else if (item.type && item.type.includes('video')) {
                    return (
                      <video
                        key={index}
                        width={40}
                        height={30}
                        controls
                        style={{
                          marginRight: 8,
                          marginBottom: 8,
                          objectFit: 'cover',
                        }}
                        src={item.url}
                      />
                    );
                  }
                  return null;
                })}
              </div>
            );
          },
        },
        MyColumns.EnumTag({
          title: '分配状态',
          dataIndex: 'assign_status',
          valueEnum: HouseWorkOrdersAssignStatusEnum,
        }),
        MyColumns.EnumTag({
          title: '优先级',
          dataIndex: 'level',
          valueEnum: HouseWorkOrdersLevelEnum,
        }),
        {
          title: '处理人',
          dataIndex: ['assign_employee', 'name'],
          search: false,
          render: (_, record) => {
            return `${record?.assign_employee?.name || ''}-${
              record?.assign_employee?.phone || ''
            }`;
          },
        },
        {
          title: '是否回访',
          dataIndex: 'is_visited',
          render: (_, record) => {
            return `${record?.is_visited === 1 ? '是' : '否'}`;
          },
        },
        {
          title: '是否评价',
          dataIndex: 'is_rework',
          render: (_, record) => {
            return `${
              record?.is_rework === 1 || searchParams?.get('is_rework') === '1'
                ? '是'
                : '否'
            } `;
          },
        },

        MyColumns.CreatedAt(),
        MyColumns.Option({
          render: (_, item: any, index, action) => (
            <Space key={index}>
              <WorkOrderShow item={item} title="详情" reload={action?.reload} />
              {item.status !== 'Completed' && (
                <WorkOrderUpdate
                  item={item}
                  reload={action?.reload}
                  title={title}
                />
              )}
              {item.assign_status === 'Unassigned' &&
                item.type !== 'SecurityInspection' && (
                  <WorkOrderAssign
                    item={item}
                    reload={action?.reload}
                    title="指派"
                  />
                )}
              {item.assign_status === 'Unassigned' &&
                (item.type === 'Complaint' ||
                  item.type === 'SecurityInspection') && (
                  <AssignQuick
                    item={item}
                    reload={action?.reload}
                    title="指派"
                  />
                )}

              {item.is_visited === 0 && (
                <WorkOrderShow
                  item={item}
                  title="回访"
                  reload={action?.reload}
                />
              )}
              <MyButtons.Delete
                onConfirm={() =>
                  Apis.WorkOrder.HouseWorkOrders.Delete({
                    id: item.id,
                  }).then(() => action?.reload())
                }
              />
            </Space>
          ),
        }),
      ]}
    />
  );
}
