import React, { useRef, useState } from 'react';
import { useAccess } from '@umijs/max';
import { Button, Modal, message } from 'antd';
import { ActionType, ProColumns, ProTable, ModalForm, ProFormText, ProFormDateTimePicker } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import {
  getOutdoorFairAttendeeList,
  addOutdoorFairAttendee,
  updateOutdoorFairAttendee,
  deleteOutdoorFairAttendee,
} from '@/services/jobportal/outdoorFairAttendee';
import type {
  OutdoorFairAttendeeItem,
  OutdoorFairAttendeeForm,
} from '@/services/jobportal/outdoorFairAttendee';

interface Props {
  fairId: number;
}

const AttendeeTab: React.FC<Props> = ({ fairId }) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<OutdoorFairAttendeeItem>();

  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该签到人员吗？',
      onOk: async () => {
        const res = await deleteOutdoorFairAttendee(id);
        if (res.code === 200) {
          message.success('删除成功');
          actionRef.current?.reload();
        } else {
          message.error(res.msg || '删除失败');
        }
      },
    });
  };

  const columns: ProColumns<OutdoorFairAttendeeItem>[] = [
    { title: '人员', dataIndex: 'name', ellipsis: true },
    { title: '手机号', dataIndex: 'phone', ellipsis: true, hideInSearch: true },
    { title: '住址', dataIndex: 'address', ellipsis: true, hideInSearch: true },
    {
      title: '签到时间',
      dataIndex: 'checkInTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          hidden={!access.hasPerms('cms:outdoorFair:edit')}
          onClick={() => {
            setCurrentRow(record);
            setModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          hidden={!access.hasPerms('cms:outdoorFair:remove')}
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <>
      <ProTable<OutdoorFairAttendeeItem>
        actionRef={actionRef}
        rowKey="id"
        headerTitle="参会人员管理"
        search={{ labelWidth: 'auto' }}
        options={false}
        pagination={{ pageSize: 10 }}
        scroll={{ x: 'max-content' }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            hidden={!access.hasPerms('cms:outdoorFair:add')}
            onClick={() => {
              setCurrentRow(undefined);
              setModalVisible(true);
            }}
          >
            录入签到人员
          </Button>,
        ]}
        request={async (params) => {
          const res = await getOutdoorFairAttendeeList({
            fairId,
            current: params.current,
            pageSize: params.pageSize,
            name: params.name,
          });
          return { data: res.rows || [], total: res.total || 0, success: res.code === 200 };
        }}
        columns={columns}
      />

      <ModalForm<OutdoorFairAttendeeForm>
        title={currentRow ? '编辑签到人员' : '录入签到人员'}
        open={modalVisible}
        modalProps={{ destroyOnClose: true, onCancel: () => setModalVisible(false) }}
        initialValues={
          currentRow
            ? {
                id: currentRow.id,
                fairId,
                name: currentRow.name,
                phone: currentRow.phone,
                address: currentRow.address,
                checkInTime: currentRow.checkInTime,
              }
            : { fairId }
        }
        onFinish={async (values) => {
          const payload = { ...values, fairId };
          const res = values.id
            ? await updateOutdoorFairAttendee(payload)
            : await addOutdoorFairAttendee(payload);
          if (res.code === 200) {
            message.success(values.id ? '修改成功' : '新增成功');
            setModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
            return true;
          }
          message.error(res.msg || '操作失败');
          return false;
        }}
      >
        <ProFormText
          name="name"
          label="人员"
          placeholder="请输入人员姓名"
          rules={[{ required: true, message: '请输入人员姓名' }]}
        />
        <ProFormText name="phone" label="手机号" placeholder="请输入手机号" />
        <ProFormText name="address" label="住址" placeholder="请输入住址" />
        <ProFormDateTimePicker
          name="checkInTime"
          label="签到时间"
          placeholder="请选择签到时间"
          fieldProps={{ style: { width: '100%' } }}
        />
      </ModalForm>
    </>
  );
};

export default AttendeeTab;
