import { MyButtons } from '@/common';
import { Apis } from '@/gen/Apis';
import {
  HouseWorkOrdersAssignStatusEnum,
  HouseWorkOrdersLevelEnum,
  HouseWorkOrdersStatusEnum,
} 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 '../../list/modals/WorkOrderAssign';

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

export default function ComplaintShow({
  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} title={title} />
      <Modal
        title={title}
        open={open}
        onCancel={() => setOpen(false)}
        footer={null}
        width={800}
      >
        {data && (
          <>
            <ProDescriptions
              column={2}
              dataSource={data}
              columns={[
                {
                  title: 'ID',
                  dataIndex: 'id',
                  span: 1,
                },
                {
                  title: '投诉类型',
                  dataIndex: 'complaint_type',
                  span: 1,
                },

                {
                  title: '所在项目',
                  dataIndex: ['asset_project', 'name'],
                },
                {
                  title: '投诉内容',
                  dataIndex: 'content',
                  span: 2,
                },
                {
                  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: ['reporter_name', 'reporter_phone'],
                  span: 1,
                  render: (_, record) => {
                    return `${record.reporter_name || ''} ${
                      record.reporter_phone || ''
                    }`;
                  },
                },

                {
                  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: '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: '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: '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: 2,
                  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.includes('image')) {
                            return (
                              <Image
                                key={index}
                                width={80}
                                height={60}
                                src={item.url}
                                style={{
                                  marginRight: 8,
                                  marginBottom: 8,
                                  objectFit: 'cover',
                                }}
                              />
                            );
                          } else if (item.type && item.type.includes('video')) {
                            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,
                },
              ]}
            />
            {/* <Divider orientation="left">处理记录</Divider> */}
            <WorkLogslist
              workOrderId={data.id}
              workOrderProjectId={data.asset_projects_id}
              workOrderStatus={data.status}
              workOrderIsVisited={data.is_visited}
              workOrderType={data.complaint_type}
              // 刷新处理记录
              reload={() => {
                handleOpen();
                reload?.();
              }}
            />
          </>
        )}
      </Modal>
    </>
  );
}
