import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';

import { Select, Space, Image, Button, message, Upload } from 'antd';
import { 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 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 initRow = {
    id: ''
  };
  const [row, setRow] = useState(initRow);

  const searchShop = (value) => {
    shopItems({
      username: value
    }).then(({ data }) => {
      const arr = [];
      data?.data?.map((item) => {
        item.label = `${item.username}   ${item.mobile}`;
        arr.push(item);
      });
      setShopOption(arr);
    });
  }

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

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

      setFailFormModal(false);
    }

  }

  const columns = [
    {
      title: '订单号',
      dataIndex: 'order_no',
      search: false,
    },
    {
      title: '投资人',
      dataIndex: 'shop_id',
      renderFormItem: (
        _,
        { type, defaultRender, formItemProps, fieldProps, ...rest },
        form,
      ) => {
        return <Select
          {...fieldProps}
          allowClear
          showSearch
          placeholder="请输入用户名"
          style={{ width: "100%" }}
          filterOption={false}
          onSearch={
            (e) => {
              if (!e) {
                return;
              }
              searchShop(e);
            }
          }
          fieldNames={{
            label: "label",
            value: "id"
          }}
          options={shopOption}
        />
      },
      render: (_, record) => {
        return <>
          <div>{record?.shop?.nickname}</div>
          <div>{record?.shop?.username}</div>
          <div>{record?.shop?.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: 'cur_money',
      search: false,
    },
    {
      title: '支付方式',
      dataIndex: 'pay_type',
      search: false,
      render: (_, record) => {
        return config?.pay_type[record?.pay_type];
      },
    },
    {
      title: '提现账号',
      dataIndex: 'account',
      search: false,
      render: (_, record) => {
        return <>
          <div>{record?.account?.role === 1 ? '个人' : '企业'} ：{record?.account?.realname}</div>
          <div>{record?.account?.subname}</div>
          <div>{record?.account?.num}</div>
          <div>{record?.account?.idcard}</div>
        </>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: true,
      renderFormItem: (
        _,
        { type, defaultRender, formItemProps, fieldProps, ...rest },
        form,
      ) => {
        const data = [];

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

        return <Select
          {...fieldProps}
          allowClear
          defaultValue="1"
          style={{ width: "100%" }}
          filterOption={false}
          fieldNames={{
            label: "label",
            value: "key"
          }}
          options={data}
        />
      },
      render: (_, record) => {
        return config?.status[record?.status];
      },
    },
    {
      title: '备注',
      dataIndex: 'note',
      search: false,
    },
    {
      title: '后台备注',
      dataIndex: 'admin_note',
      search: false,
    },
    {
      title: '付款时间',
      dataIndex: 'pay_time',
      search: false,
      render: (_, record) => {
        return record?.pay_time ? dayjs(record?.pay_time * 1000).format('YYYY-MM-DD HH:mm:ss') : ''
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
      render: (_, record) => {
        return record?.created_at;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          {
            record?.status === 1 ?
              <AuthConsumer action={'admin/withdraw/fail'} key="admin/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/withdraw/import1',
    headers: {
      Authorization: `Bearer ` + getToken(),
    },
    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/withdraw/export1'} key="admin/withdraw/export1">
              <Button type="primary" onClick={() => {
                window.location.href = exportLink(searchParams, '/admin/withdraw/export1');
              }}>导出提现申请</Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/withdraw/import1'} key="admin/withdraw/import1">
              <Upload {...props}>
                <Button icon={<UploadOutlined />}>导入提现结果</Button>
              </Upload>
            </AuthConsumer>,
          ]}
          request={async (params, sorter, filter) => {
            if (!params?.status) {
              params.status = 1;
            }
            setSearchParams({ token: '', ...params });
            const { data, success } = await withdrawItems({
              ...params,
              sorter,
              filter,
            });
            setConfig(data?.config);
            return {
              data: data?.items?.data || [],
              total: data?.items?.total,
              success,
            };
          }}
          columns={columns}
        />
      </>
    </PageContainer>
  );
};
