import { MyButtons } from '@/common';
import { Apis } from '@/gen/Apis';
import {
  HouseWorkOrdersAssignStatusEnum,
  HouseWorkOrdersLevelEnum,
  HouseWorkOrdersLocationEnum,
  HouseWorkOrdersStatusEnum,
  HouseWorkOrdersTypeEnum,
} from '@/gen/Enums';
import { ProDescriptions } from '@ant-design/pro-components';
import { Image, Modal, Space, Tag } from 'antd';
import { useState } from 'react';
import WorkLogslist from '../../components/WorkLogslist';
import WorkOrderAssign from './WorkOrderAssign';

interface WorkOrderShowProps {
  item: any;
  title?: string;
  reload?: () => void;
}

export default function WorkOrderShow({
  item,
  title = '工单详情',
  reload,
}: WorkOrderShowProps) {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<any>(null);

  const handleOpen = async () => {
    try {
      const res = await Apis.WorkOrder.HouseWorkOrders.Show({ id: item.id });
      setData(res.data);
      setOpen(true);
    } catch (error) {
      console.error('获取工单详情失败:', error);
    }
  };

  return (
    <>
      <MyButtons.Default onClick={handleOpen} type={'primary'} title={title} />
      <Modal
        title={title}
        open={open}
        onCancel={() => setOpen(false)}
        footer={null}
        width={800}
      >
        {data && (
          <>
            <ProDescriptions
              column={3}
              dataSource={data}
              columns={[
                {
                  title: '工单ID',
                  dataIndex: 'id',
                  span: 1,
                },
                {
                  title: '工单状态',
                  dataIndex: 'status',
                  span: 1,
                  render: (_, record) => {
                    const statusConfig =
                      HouseWorkOrdersStatusEnum[
                        record.status as keyof typeof HouseWorkOrdersStatusEnum
                      ];
                    const color =
                      record.status === 'Completed'
                        ? 'green'
                        : record.status === 'InProgress'
                        ? 'blue'
                        : 'default';
                    return (
                      <Tag color={color}>
                        {statusConfig?.text || record.status}
                      </Tag>
                    );
                  },
                },
                {
                  title: '分配状态',
                  dataIndex: 'assign_status',
                  span: 1,
                  render: (_, record) => {
                    const assignConfig =
                      HouseWorkOrdersAssignStatusEnum[
                        record.assign_status as keyof typeof HouseWorkOrdersAssignStatusEnum
                      ];
                    const color =
                      record.assign_status === 'Assigned' ? 'green' : 'orange';
                    return (
                      <Tag color={color}>
                        {assignConfig?.text || record.assign_status}
                      </Tag>
                    );
                  },
                },
                {
                  title: '工单类型',
                  dataIndex: 'type',
                  span: 1,
                  render: (_, record) => (
                    <Tag color="blue">
                      {HouseWorkOrdersTypeEnum[
                        record.type as keyof typeof HouseWorkOrdersTypeEnum
                      ]?.text || record.type}
                    </Tag>
                  ),
                },
                {
                  title: '位置信息',
                  dataIndex: ['asset_house', 'full_name'],
                  span: 3,
                  render: (_, record) => {
                    const locationConfig =
                      HouseWorkOrdersLocationEnum[
                        record.location as keyof typeof HouseWorkOrdersLocationEnum
                      ];
                    return (
                      <Space>
                        <Tag>{locationConfig?.text || record.location}</Tag>
                        {record?.asset_house?.full_name
                          ? record?.asset_house?.full_name
                          : record?.asset_project?.name}
                      </Space>
                    );
                  },
                },
                {
                  title: '工单描述',
                  dataIndex: 'content',
                  span: 3,
                },
                {
                  title: '优先级',
                  dataIndex: 'level',
                  span: 1,
                  render: (_, record) => {
                    const levelConfig =
                      HouseWorkOrdersLevelEnum[
                        record.level as keyof typeof HouseWorkOrdersLevelEnum
                      ];
                    return <Tag>{levelConfig?.text || record.level}</Tag>;
                  },
                },
                {
                  title: '处理人',
                  dataIndex: 'assign_employee_name',
                  span: 2,
                  render: (_, record) => {
                    const assigneeInfo = record?.assign_employee
                      ? `${record.assign_employee.name || ''}-${
                          record.assign_employee.phone || ''
                        }`
                      : '未分配';
                    // 根据工单状态决定按钮标题和显示逻辑
                    const status = record.status;
                    const showAssignButton =
                      status === 'Pending' || status === 'Processing';
                    const buttonTitle =
                      status === 'Pending' ? '指派' : '重新指派';
                    return (
                      <Space>
                        <span>{assigneeInfo}</span>
                        {showAssignButton && (
                          <WorkOrderAssign
                            item={data}
                            reload={handleOpen}
                            title={buttonTitle}
                          />
                        )}
                      </Space>
                    );
                  },
                },
                {
                  title: '时间要求',
                  dataIndex: 'predict_complete_at',
                  span: 1,
                  render: (_, record) => {
                    return record?.predict_complete_at?.substring(0, 10) || '-';
                  },
                },
                {
                  title: '创建时间',
                  dataIndex: 'created_at',
                  span: 1,
                  valueType: 'dateTime',
                },
                {
                  title: '更新时间',
                  dataIndex: 'updated_at',
                  span: 2,
                  valueType: 'dateTime',
                },
                {
                  title: '相关附件',
                  dataIndex: 'attachments',
                  span: 3,
                  render: (_, record) => {
                    // 检查attachments是否为数组且有数据
                    if (
                      !Array.isArray(record.attachments) ||
                      record.attachments.length === 0
                    ) {
                      return '无附件';
                    }
                    return (
                      <div
                        style={{
                          display: 'flex',
                          flexWrap: 'wrap',
                          marginRight: 10,
                        }}
                      >
                        {record.attachments.map((item: any, index: number) => {
                          if (item?.type && item?.type?.indexOf('image') > -1) {
                            return (
                              <Image
                                key={index}
                                width={80}
                                height={60}
                                src={item.url}
                                style={{
                                  marginRight: 8,
                                  marginBottom: 8,
                                  objectFit: 'cover',
                                }}
                              />
                            );
                          } else if (
                            item?.type &&
                            item?.type?.indexOf('video') > -1
                          ) {
                            return (
                              <video
                                key={index}
                                width={80}
                                height={60}
                                controls
                                style={{
                                  marginRight: 8,
                                  marginBottom: 8,
                                  objectFit: 'cover',
                                }}
                                src={item.url}
                              />
                            );
                          }
                          return null;
                        })}
                      </div>
                    );
                  },
                },
                data?.visited_remark && {
                  title: '回访记录',
                  dataIndex: 'visited_remark',
                  span: 3,
                },
                data?.visited_time && {
                  title: '回访时间',
                  dataIndex: 'visited_time',
                  span: 1,
                },
              ]}
            />

            <WorkLogslist
              workOrderId={data?.id}
              workOrderStatus={data?.status}
              workOrderProjectId={data?.asset_projects_id}
              workOrderIsVisited={data?.is_visited}
              workOrderType={data?.type}
              item={data}
              reload={() => {
                handleOpen();
                reload?.();
              }}
            />
          </>
        )}
      </Modal>
    </>
  );
}
