import BaseModel from '@/components/Base/BaseModel';
import BaseTable from '@/components/Base/BaseTable';
import { _updateConnectorStatus, _uploadStationImage } from '@/services/station';
import { UploadOutlined } from '@ant-design/icons';
import { ProForm, ProFormField, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { Button, Divider, Image, message, Select, Tag, Upload } from 'antd';
import dayjs from 'dayjs';
import { useRef } from 'react';

export default function DetailModal({
  initData,
  mainTableReload,
}: {
  mainTableReload: () => Promise<void> | undefined;

  initData?: Page_Station.Station;
}) {
  /**********************************狀態管理**********************************/
  const formRef = useRef<ProFormInstance>();

  /**********************************狀態管理**********************************/
  /**********************************組件初始化**********************************/
  const groupStyle: React.CSSProperties = {
    backgroundColor: 'white',
    paddingLeft: '24px',
    paddingRight: '24px',
    paddingTop: '6px',
    borderBottom: 3,
    borderColor: 'black',
  };
  /**********************************組件初始化**********************************/
  /**********************************異步函數**********************************/

  const uploadStationImage = async (options: { filename: File; stationId: string }) => {
    try {
      const response = await _uploadStationImage(options);
      console.log(response);
      if (response.code === 200) {
        return Promise.resolve(response);
      } else {
        return Promise.reject(response);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  };
  /**********************************異步函數**********************************/
  return (
    <BaseModel<Page_Station.Station>
      modalFormProps={{
        formRef: { ...formRef },

        clearOnDestroy: true,
        onInit: async (values, form) => {
          console.log(initData);
          form.setFieldsValue(initData);
        },
        trigger: (
          <Button type="primary" key="priceAdjustment">
            查看詳情
          </Button>
        ),
        title: (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            Station Details
            <Upload
              className="mr-6"
              name="file"
              customRequest={({ file, onSuccess, onError }) => {
                // 关键点：自定义请求
                // 假设 stationId 来自父组件或当前作用域
                const stationId = initData!.id; // 这里需要替换成真实的 stationId

                uploadStationImage({
                  filename: file as File,
                  stationId,
                })
                  .then(() => {
                    onSuccess?.('上传成功', new XMLHttpRequest()); // 必须触发 onSuccess
                    mainTableReload?.();
                  })
                  .catch((error) => {
                    onError?.(error);
                  });
              }} // 使用自定义上传
              showUploadList={false}
              beforeUpload={(file) => {
                const isImage = file.type.startsWith('image/');
                if (!isImage) {
                  message.error('只能上傳圖片文件！');
                  return false;
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  message.error('圖片必須小於 2MB！');
                  return false;
                }
                return true;
              }}
              onChange={(info) => {
                if (info.file.status === 'done') {
                  message.success('圖片上傳成功');
                  // 可以从 info.file.response 获取服务器响应
                  if (info.file.response?.url) {
                    // 更新图片URL
                  }
                } else if (info.file.status === 'error') {
                  message.error('圖片上傳失敗');
                }
              }}
            >
              <Button icon={<UploadOutlined />} size="small" type="primary">
                修改圖片
              </Button>
            </Upload>
          </div>
        ),
      }}
      modalProps={{
        width: 1000,
      }}
      allowUpdate={false}
      readOnly={true}
      initData={initData}
      title="Station Details"
    >
      <Divider orientation="left" orientationMargin={20}>
        充電站信息
      </Divider>
      <ProForm.Group style={{ ...groupStyle }}>
        <ProFormText label={'充電站編號'} name="id" colProps={{ span: 8, offset: 0 }} readonly />
        <ProFormField label={'站点圖片'} name="image" colProps={{ span: 8, offset: 6 }}>
          <Image src={initData!.image} width={100} />
        </ProFormField>

        <ProFormField
          label={'價格'}
          name="price"
          colProps={{ span: 8, offset: 0 }}
          valueType="money"
        />
        <ProFormText
          label={'營業時間'}
          proFieldProps={{
            render: () => {
              return <div>{initData?.business_hours_fk}</div>;
            },
          }}
          colProps={{ span: 8, offset: 6 }}
          readonly
        />
      </ProForm.Group>
      <Divider orientation="left" orientationMargin={20}>
        站內樁信息
      </Divider>
      <ProForm.Group style={{ ...groupStyle }}>
        <ProFormText
          label={'樁總數'}
          name="equipment_count"
          colProps={{ span: 8, offset: 0 }}
          initialValue={
            initData?.Equipments?.filter((equipment: { ConnectorInfos: any[] }) =>
              equipment.ConnectorInfos?.some(
                (connector: { park: null }) => connector.park !== null,
              ),
            )?.length || 0
          }
          readonly
        />
        <ProFormField
          label={'所有樁信息'}
          tooltip="信息來源: 提供商 無法手動修改"
          name="equipment_info"
          colProps={{ span: 24, offset: 0 }}
        >
          <BaseTable
            props={{
              toolBarRender: false,
              pagination: false,
              columns: [
                {
                  title: '樁編號',
                  dataIndex: 'id',
                  width: 100, // 使用具体像素值

                  ellipsis: {
                    showTitle: true,
                  },
                  onCell: () => ({
                    style: {
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      maxWidth: 100,
                    },
                  }),

                  copyable: true,
                },
                {
                  title: '設備ID',
                  dataIndex: 'EquipmentID',
                  width: 180,
                  ellipsis: true,
                  copyable: true,
                },
                {
                  title: '設備型號',
                  dataIndex: 'EquipmentModel',
                  width: 120,
                },
                {
                  title: '設備類型',
                  dataIndex: 'EquipmentType',
                  width: 100,
                  render: (type) => (type === 1 ? '直流充電樁' : '交流充電樁'),
                },
                {
                  title: '功率',
                  dataIndex: 'Power',
                  width: 100,
                  render: (power) => `${(power as any) / 1000}kW`,
                },
              ],
              dataSource: initData?.Equipments,
            }}
          />
        </ProFormField>
      </ProForm.Group>

      <Divider orientation="left" orientationMargin={20}>
        站內槍信息
      </Divider>
      <ProForm.Group style={{ ...groupStyle }}>
        <ProFormText
          label={'槍總數'}
          name={'guns_count'}
          colProps={{ span: 8, offset: 0 }}
          initialValue={
            initData?.Equipments?.reduce((total: number, equipment: Page_Station.Equipment) => {
              const validConnectors =
                equipment.ConnectorInfos?.filter(
                  (connector: Page_Station.Connector) => connector.park !== null,
                ) || [];
              return total + validConnectors.length;
            }, 0) || 0
          }
          readonly
        />
        <ProFormField
          label={'所有槍信息'}
          tooltip="信息來源: 提供商 無法手動修改"
          name="gun_info"
          colProps={{ span: 24, offset: 0 }}
        >
          <BaseTable
            props={{
              toolBarRender: false,
              pagination: false,
              columns: [
                {
                  title: '充電槍ID',
                  dataIndex: 'ConnectorID',
                  width: 180,
                  copyable: true,
                },
                {
                  title: '充電槍名稱',
                  dataIndex: 'ConnectorName',
                  width: 100,
                },
                {
                  title: '車位號',
                  dataIndex: 'park',
                  width: 80,
                },
                {
                  title: '功率',
                  dataIndex: 'Power',
                  width: 100,
                  render: (power) => `${(power as any) / 1000}kW`,
                },
                {
                  title: '電流',
                  dataIndex: 'Current',
                  width: 100,
                  render: (current) => `${current}A`,
                },
                {
                  title: '電壓範圍',
                  dataIndex: 'VoltageLowerLimits',
                  width: 120,
                  render: (_, record) =>
                    `${record.VoltageLowerLimits as any}~${record.VoltageUpperLimits as any}V`,
                },
                {
                  title: '狀態',
                  dataIndex: 'Status',
                  width: 100,
                  render: (status) => {
                    const statusMap = {
                      待机: <Tag color="green">待機</Tag>,
                      充电中: <Tag color="blue">充電中</Tag>,
                      离线: <Tag color="default">離線</Tag>,
                      故障: <Tag color="red">故障</Tag>,
                    };
                    return statusMap[status as keyof typeof statusMap] || <Tag>未知</Tag>;
                  },
                },
                {
                  title: '車位狀態',
                  dataIndex: 'ParkStatus',
                  width: 100,
                },
                {
                  title: '鎖狀態',
                  dataIndex: 'LockStatus',
                  width: 100,
                },
                {
                  title: '更新時間',
                  dataIndex: 'updatedAt',
                  width: 160,
                  render: (time) => dayjs(time as any).format('YYYY-MM-DD HH:mm:ss'),
                },
                {
                  title: '操作',
                  dataIndex: 'action',
                  width: 100,
                  render: (_, record) => {
                    const StatusMap: Record<ConnectorStatus, StatusInfo> = {
                      1: { text: '告警', color: 'orange' },
                      2: { text: '待機', color: 'green' },
                      3: { text: '充電中', color: 'blue' },
                      4: { text: '離線', color: 'default' },
                      5: { text: '已完成', color: 'cyan' },
                      6: { text: '暫停', color: 'gold' },
                      7: { text: '已插槍', color: 'geekblue' },
                      8: { text: '預約中', color: 'purple' },
                      9: { text: '已禁用', color: 'red' },
                    };
                    const statusOptions = Object.entries(StatusMap).map(([, { text, color }]) => ({
                      value: text,
                      label: <Tag color={color}>{text}</Tag>,
                    }));

                    return (
                      <Select
                        options={statusOptions}
                        defaultValue={record.Status}
                        onChange={async (value) => {
                          await _updateConnectorStatus({
                            connectorId: record.ConnectorID,
                            status: value,
                          });
                          message.success('槍狀態更新成功');
                          mainTableReload?.();
                        }}
                      >
                        更改槍狀態
                      </Select>
                    );
                  },
                },
              ],
              dataSource: initData?.Equipments.flatMap((equipment: Page_Station.Equipment) =>
                equipment.ConnectorInfos.map((connector: Page_Station.Connector) => ({
                  ...connector,
                  EquipmentID: equipment.id,
                })),
              ),
            }}
          />
        </ProFormField>
      </ProForm.Group>
      <Divider orientation="left" orientationMargin={20}>
        提供商原始数据
      </Divider>
      <ProForm.Group style={{ ...groupStyle }}>
        {Object.entries(initData?.snapshot || {}).map(([key, value]) => {
          // 处理设备信息
          if (key === 'EquipmentInfos') {
            return <></>;
          }

          // 处理其他普通字段
          return (
            <ProFormText
              key={key}
              label={key}
              name={key}
              initialValue={typeof value === 'object' ? JSON.stringify(value) : value}
              colProps={{ span: 8 }}
              readonly
            />
          );
        })}
      </ProForm.Group>
    </BaseModel>
  );
}
