import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Drawer, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { MemberTableListItem } from './data';
import { queryMemberList, queryMemberListV2, removeMember } from './service';
import moment from 'moment';
// import MemberAddressModal from "@/pages/ums/member/components/MemberAddressModal";
// import MemberLogModal from "@/pages/ums/member/components/MemberLoginLogModal";


const { confirm } = Modal;


/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: MemberTableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeMember({
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const MemberList: React.FC<{}> = () => {
  const [addressModalVisible, handleAddressModalVisible] = useState<boolean>(false);
  const [logModalVisible, handleLogModalVisible] = useState<boolean>(false);
  // const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<MemberTableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<MemberTableListItem[]>([]);

  const showDeleteConfirm = (item: MemberTableListItem) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined />,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove([item]).then((r) => {
          actionRef.current?.reloadAndRest?.();
        });
      },
      onCancel() {
      },
    });
  };



  const columns: ProColumns<MemberTableListItem>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      render: (dom, entity) => {
        return <a onClick={() => {
          setCurrentRow(entity);
          setShowDetail(true);
        }}>{dom}</a>;
      },
    },
    // {
    //   title: '昵称',
    //   dataIndex: 'nickname',
    //   hideInSearch: true,
    // },

    {
      title: '订阅',
      dataIndex: 'is_subscribed',
      hideInSearch: true,
      valueEnum: {
        true: { text: '是', status: true },
        false: { text: '否', status: false },
      },
    },
    {
      title: '上次登录',
      dataIndex: 'login_time',
      // valueType: 'dateTime',
      valueType: 'date',
      hideInSearch: true,
      // hideInTable: true,
      fieldProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        onChange: (value: moment.MomentInput) => moment(value).valueOf(),
      },
      // 将日期转换为格式化的字符串
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: 'IP地址',
      dataIndex: 'login_ip',
      hideInSearch: true,
    },
    // {
    //   title: '操作',
    //   dataIndex: 'option',
    //   valueType: 'option',
    //   render: (_, record) => (
    //     <>
    //       <Button
    //         type="primary"
    //         icon={<EditOutlined />}
    //         onClick={() => {
    //           handleAddressModalVisible(true);
    //           setCurrentRow(record);
    //         }}
    //       >
    //         会员地址
    //       </Button>
    //       <Divider type="vertical" />
    //       <Button
    //         type="primary"
    //         icon={<EditOutlined />}
    //         onClick={() => {
    //           handleLogModalVisible(true);
    //           setCurrentRow(record);
    //         }}
    //       >
    //         登录日志
    //       </Button>
    //       <Divider type="vertical" />
    //       <Button
    //         type="primary"
    //         danger
    //         icon={<DeleteOutlined />}
    //         onClick={() => {
    //           showDeleteConfirm(record);
    //         }}
    //       >
    //         删除
    //       </Button>
    //     </>
    //   ),
    // },
  ];

  return (
    <PageContainer>
      <ProTable<MemberTableListItem>
        headerTitle="会员列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        params={{
          current: 0
        }}
        toolBarRender={false}
        request={queryMemberListV2}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}

        pagination={{ pageSize: 10 }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      {/* <MemberAddressModal
        key={'MemberAddressModal'}
        onSubmit={async () => {
          handleAddressModalVisible(false);
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={() => {
          handleAddressModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        addressModalVisible={addressModalVisible}
        memberId={currentRow?.id || 0}
      /> */}

      {/* <MemberLogModal
        key={'MemberLogModal'}
        onSubmit={async () => {
          handleLogModalVisible(false);
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={() => {
          handleLogModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        logModalVisible={logModalVisible}
        memberId={currentRow?.id || 0}
      /> */}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false)
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<MemberTableListItem>
            column={2}
            title={currentRow?.email}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<MemberTableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default MemberList;
