import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';
import { userPage } from '@/services/invest/user';
import { Select, Space, Image, Button, message, Upload } from 'antd';
import { TrophyOutlined, UploadOutlined } from '@ant-design/icons';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';

import dayjs from 'dayjs';

// import { exportLink } from '@/utils/func';

// import { getToken, setAuthority } from '@/utils/auth';

import { withdrawPage } from '@/services/invest/withdraw'


import AuthConsumer from '@/components/Authority';
import FailFormModal from './components/FailFormModal';

// import services from '@/services/admin';

// const { withdrawItems, withdrawFail } = services.WithdrawController;
// const { shopItems } = services.ShopController;

export default () => {

  const actionRef = useRef();

  const [config, setConfig] = useState();
  const [searchParams, setSearchParams] = useState(null);
  const [shopOption, setShopOption] = useState([]);
  const [failFormModal, setFailFormModal] = useState(false);

  const fetchOptions = async (keyword = '') => {
    try {
      const { data } = await userPage({ userName: keyword });

      setShopOption((data?.records || []).map(item => ({
        label: item.username + ' ' + item.mobile, // 根据实际字段调整
        value: Number(item.id),   // 根据实际字段调整
      })));
    } catch (error) {
      console.error('加载选项失败:', error);
      return []; // 失败时返回空数组
    }
  };
  const initRow = {
    id: ''
  };
  const [row, setRow] = useState(initRow);


  const handleFail = async (value) => {
    const { success } = await withdrawFail({ ...value });

    if (success) {
      actionRef.current?.reload();

      setFailFormModal(false);
    }

  }

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      search: false,
    },
    {
      title: '投资人',
      dataIndex: 'shopId',
      valueType: 'select',
      search: {
        fieldProps: {
          placeholder: '输入用户名',
          showSearch: true,
          filterOption: false,
          onSearch: async (keyword) => {
            if (!keyword) {
              return;
            }
            await fetchOptions(keyword);
          },
          options: shopOption,
        },
      },
      render: (_, record) => {
        return <>
          <div>{record?.username}</div>
          <div>{record?.mobile}</div>
        </>
      },
    },
    // {
    //   title: '类型',
    //   dataIndex: 'type',
    //   search: false,
    //   render: (_, record) => {
    //     return config?.type[record.type];
    //   },
    // },
    {
      title: '提现金额',
      dataIndex: 'money',
      search: false,
    },
    {
      title: '提现手续费',
      dataIndex: 'fee',
      search: false,
    },
    {
      title: '到账金额',
      dataIndex: 'payMoney',
      search: false,
    },

    // {
    //   title: '当前余额',
    //   dataIndex: 'cur_money',
    //   search: false,
    // },
    // {
    //   title: '支付方式',
    //   dataIndex: 'pay_type',
    //   search: false,
    //   render: (_, record) => {
    //     return config?.pay_type[record?.pay_type];
    //   },
    // },
    {
      title: '个人/企业',
      dataIndex: 'role',
      search: true,
      hideInTable: true,
      renderFormItem: (
        _,
        { type, defaultRender, formItemProps, fieldProps, ...rest },
        form,
      ) => {
        const data = [];

        for (let index in config?.role) {
          if (config?.role.hasOwnProperty(index)) {
            data.push({
              label: config?.role[index],
              key: index
            })
          }
        }

        return <Select
          {...fieldProps}
          allowClear
          style={{ width: "100%" }}
          filterOption={false}
          options={[{
            label: "个人",
            value: 1
          }, {
            label: "企业",
            value: 1
          }]}
        />
      },
    },
    {
      title: '提现信息',
      dataIndex: 'account',
      search: false,
      render: (_, record) => {
        return <>
          <div>{record?.role === 1 ? '个人' : '企业'} ：{record?.realname}</div>
          <div>{record?.subname}</div>
          <div>{record?.num}</div>
          <div>{record?.idcard}</div>
        </>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: true,
      renderFormItem: (
        _,
        { type, defaultRender, formItemProps, fieldProps, ...rest },
        form,
      ) => {

        return <Select
          {...fieldProps}
          allowClear
          style={{ width: "100%" }}
          filterOption={false}
          options={[{
            label: "提现失败",
            value: -1
          }, {
            label: "处理中",
            value: 0
          }, {
            label: "提现成功",
            value: 1
          }]}
        />
      },
      render: (_, record) => {
        return record?.statusName;
      },
    },
    {
      title: '备注',
      dataIndex: 'note',
      search: false,
    },
    {
      title: '完成时间',
      dataIndex: 'finishTimeLdt',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      search: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
      render: (_, record) => {
        return record?.createdAt;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      // render: (_, record) => (
      //   <Space>
      //     {
      //       record?.status === 1 ?
      //         <AuthConsumer action={'admin/v20/withdraw/fail'} key="admin/v20/withdraw/fail">
      //           <Button
      //             type="text"
      //             danger
      //             onClick={() => {
      //               setRow({ ...row, ...record });
      //               setFailFormModal(true);
      //             }}
      //           >
      //             驳回
      //           </Button>
      //         </AuthConsumer> : ''
      //     }
      //   </Space>
      // ),
    },
  ];

  const props = {
    name: 'file',
    action: process.env.API_URL + '/admin/api/v0/withdraw/importDeviceData',
    headers: {
      Authorization: localStorage.getItem('token'),
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 导入成功`);
        actionRef.current?.reload();
      } else if (info.file.status === 'error') {
        message.success(`${info.file.name} 上传失败`);
      }
    },
  };

  return (
    <PageContainer
      ghost
    >
      <>
        <FailFormModal
          values={row}
          modalOpenState={failFormModal}
          onModalOpenState={setFailFormModal}
          onSubmit={handleFail}
        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            defaultCollapsed: false,
          }}
          toolBarRender={() => [
            <AuthConsumer action={'admin/v20/withdraw/export1'} key="admin/v20/withdraw/export1">
              <Button type="primary" onClick={() => {
                // window.location.href = exportLink(searchParams, '/admin/v20/withdraw/export1');
                const params = new URLSearchParams(searchParams);
                fetch(`${process.env.API_URL}/admin/api/v0/withdraw/export?${params}`, {
                  method: 'GET',
                  headers: {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem('token'),
                  }
                })
                  .then(response => response.blob())
                  .then(data => {
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(data);
                    link.download = '提现记录.xlsx';
                    link.click();
                  })
                  .catch(error => console.error('Error:', error));
              }}>导出提现申请</Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/v20/withdraw/import1'} key="admin/v20/withdraw/import1">
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>导入提现结果</Button>
              </Upload>
            </AuthConsumer>,
          ]}
          request={async (params, sorter, filter) => {
            setSearchParams({ token: '', ...params });
            const { data } = await withdrawPage({
              ...params,
            });
            setConfig(data?.config);
            return {
              data: data?.records || [],
              total: data?.total,
            };
          }}
          columns={columns}
        />
      </>
    </PageContainer>
  );
};
