import { useRef, useState } from 'react';
import { Button, message, Modal, Image } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Access, useAccess } from 'umi';
import {
  addBatchRecommendPurchaseAgentUsingPost,
  deleteBatchRecommendPurchaseAgentUsingPost,
  getRecommendPurchaseAgentListForAdminUsingGet,
  getUnRecommendPurchaseAgentListUsingGet,
  moveRecommendPurchaseAgentUsingGet
} from '@/services/pop-b2b2c/pbcRecommendPurchaseAgentController';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const addActionRef = useRef<ActionType>();
  const access: any = useAccess();

  const [selectModalVisible, setSelectModalVisible] = useState<boolean>(false);
  const [selectedAgentIds, setSelectedAgentIds] = useState<number[]>([]);
  
  const handleAddRecommend = async () => {
    const res = await getUnRecommendPurchaseAgentListUsingGet();
    if (res.retcode && res.data) {
      if (res.data.length === 0) {
        message.warning('没有可推荐的小哥');
        return;
      }
      setSelectModalVisible(true);
      actionRef.current?.reload();
    }
  };
  
  const handleConfirmAdd = async () => {
    if (selectedAgentIds.length === 0) {
      message.warning('请选择要添加的小哥');
      return;
    }
    Modal.confirm({
      title: '确认添加',
      content: `确定要添加${selectedAgentIds.length}个小哥到推荐列表吗？`,
      onOk: async () => {
        const result = await addBatchRecommendPurchaseAgentUsingPost(selectedAgentIds);
        if (result.retcode) {
          message.success('添加成功');
          setSelectModalVisible(false);
          setSelectedAgentIds([]);
          actionRef.current?.reload();
        } else {
          message.error(result.retmsg);
        }
      },
    });
  };

  const handleMove = async (id: number, type: 'up' | 'down') => {
    const res = await moveRecommendPurchaseAgentUsingGet({ recommendPurchaseAgentId: id, type });
    if (res.retcode) {
      message.success('移动成功');
      actionRef.current?.reload();
    } else {
      message.error(res.retmsg);
    }
  };

  const handleDelete = async (ids: number[]) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的${ids.length}个推荐小哥吗？`,
      onOk: async () => {
        const res = await deleteBatchRecommendPurchaseAgentUsingPost(ids);
        if (res.retcode) {
          message.success('删除成功');
          actionRef.current?.reload();
        } else {
          message.error(res.retmsg);
        }
      },
    });
  };

  const columns: ProColumns<API.PbcRecommendPurchaseAgent_>[] = [
    {
      title: '小哥姓名',
      dataIndex: 'pbcPurchaseAgentName',
      render: (_, record) => {
        return record.pbcPurchaseAgentInfo?.pbcPurchaseAgentName ?? '-';
      },
    },
    {
      title: '年龄',
      dataIndex: 'pbcPurchaseAgentAge',
      search: false,
      render: (_, record) => {
        return record.pbcPurchaseAgentInfo?.pbcPurchaseAgentAge ?? '-';
      },
    },
    {
      title: '联系电话',
      width: 110,
      dataIndex: 'pbcPurchaseAgentMobile',
      render: (_, record) => {
        return record.pbcPurchaseAgentInfo?.pbcPurchaseAgentMobile ?? '-';
      },
    },
    {
      title: '从业年数',
      dataIndex: 'pbcPurchaseAgentWorkingAge',
      search: false,
      render: (_, record) => record.pbcPurchaseAgentInfo?.pbcPurchaseAgentWorkingAge ? `${record.pbcPurchaseAgentInfo?.pbcPurchaseAgentWorkingAge}年` : '-'
    },
    {
      title: '常驻区域',
      dataIndex: 'pbcPurchaseAgentResidentArea',
      search: false,
      render: (_, record) => {
        return record.pbcPurchaseAgentInfo?.pbcPurchaseAgentResidentArea ?? '-';
      },
    },
    {
      title: '擅长面料用途',
      dataIndex: 'pbcPurchaseAgentFabricUse',
      ellipsis: true,
      search: false,
      render: (_, record) => {
        return record.pbcPurchaseAgentInfo?.pbcPurchaseAgentFabricUse ?? '-';
      },
    },
    {
      title: '头像',
      dataIndex: 'pbcPurchaseAgentImage',
      search: false,
      render: (_, record) => record.pbcPurchaseAgentInfo?.pbcPurchaseAgentImage ? <Image width={50} src={record.pbcPurchaseAgentInfo?.pbcPurchaseAgentImage} /> : '-'
    },
    {
      title: '操作',
      fixed: 'right',
      width: 180,
      valueType: 'option',
      render: (_, record, index, action) => [
        <Access key="switch" accessible={!!access.recommendPurchaseAgentSave}>
          <Button
            type="link"
            disabled={index === 0}
            onClick={() => handleMove(record.pbcId || 0, 'up')}
          >
            上移
          </Button>,
            <Button
            type="link"
            disabled={index === (action?.pageInfo?.total || 0) - 1}
            onClick={() => handleMove(record.pbcId || 0, 'down')}
          >
            下移
          </Button>
        </Access>,
        <Access key="delete" accessible={!!access.recommendPurchaseAgentRemove}>
          <Button
            type="link"
            danger
            onClick={() => handleDelete([record.pbcId || 0])}
          >
            删除
          </Button>
        </Access>
      ],
    },
  ];
  const addColumns: ProColumns<API.PbcPurchaseAgentInfo_>[] = [
    {
      title: '小哥姓名',
      dataIndex: 'pbcPurchaseAgentName',
    },
    {
      title: '年龄',
      dataIndex: 'pbcPurchaseAgentAge',
      search: false,
    },
    {
      title: '联系电话',
      dataIndex: 'pbcPurchaseAgentMobile',
    },
    {
      title: '从业年数',
      dataIndex: 'pbcPurchaseAgentWorkingAge',
      search: false,
      render: (text) => text ? `${text}年` : '-'
    },
    {
      title: '常驻区域',
      dataIndex: 'pbcPurchaseAgentResidentArea',
      search: false,
    },
    {
      title: '擅长面料用途',
      dataIndex: 'pbcPurchaseAgentFabricUse',
      ellipsis: true,
      search: false,
    },
    {
      title: '头像',
      dataIndex: 'pbcPurchaseAgentImage',
      search: false,
      render: (text: any) => text ? <Image width={50} src={text} /> : '-'
    },
  ];

  return (
    <PageContainer
      header={{
        title: '',
        breadcrumb: {},
      }}
    >
      <ProTable<API.PbcRecommendPurchaseAgent_>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const res = await getRecommendPurchaseAgentListForAdminUsingGet({
            ...params,
          });
          return {
            data: res.data || [],
            success: !!res.retcode,
            total: res.data?.length,
          };
        }}
        rowKey="pbcId"
        size="small"
        bordered
        search={false}
        toolbar={{
          actions: [
            <Access key="switch" accessible={!!access.recommendPurchaseAgentSave}>
              <Button key="add" type="primary" onClick={handleAddRecommend}>
                添加推荐小哥
              </Button>
            </Access>
          ],
        }}
        rowSelection={{
          onChange: (selectedRowKeys) => {
            if (selectedRowKeys.length > 0) {
              handleDelete(selectedRowKeys as number[]);
            }
          },
        }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
        scroll={{
          y: 'calc(100vh - 320px)',
        }}
        dateFormatter="string"
        options={false}
        toolBarRender={() => []}
      />
      <Modal
        title="选择推荐小哥"
        open={selectModalVisible}
        onCancel={() => {
          setSelectModalVisible(false);
          setSelectedAgentIds([]);
        }}
        width={1000}
        footer={[
          <Button
            key="cancel"
            onClick={() => {
              setSelectModalVisible(false);
              setSelectedAgentIds([]);
            }}
          >
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleConfirmAdd}>
            确定
          </Button>,
        ]}
      >
        <ProTable<API.PbcPurchaseAgentInfo_>
          columns={addColumns}
          request={async () => {
            const res = await getUnRecommendPurchaseAgentListUsingGet();
            return {
              data: res.data || [],
              success: !!res.retcode,
            };
          }}
          actionRef={addActionRef}
          rowKey="pbcId"
          size="small"
          bordered
          search={false}
          options={false}
          pagination={false}
          rowSelection={{
            selectedRowKeys: selectedAgentIds,
            onChange: (selectedRowKeys) => {
              setSelectedAgentIds(selectedRowKeys as number[]);
            },
          }}
          scroll={{
            y: 400,
          }}
        />
      </Modal>
    </PageContainer>
  );
};
export default TableList;