import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';
import { Select, Space, Image, Line, Button, Card, Col, Row, RangePicker, Input } from 'antd';

import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';

import dayjs from 'dayjs';

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

import AuthConsumer from '@/components/Authority';

import BonusFormModal from './components/BonusFormModal';
import RefundFormModal from './components/RefundFormModal';
import CreateFormModal from './components/CreateFormModal';

import services from '@/services/admin';

const { shopOrderItems, shopOrderRefund, shopOrderCreate } = services.ShopOrderController;
const { shopItems } = services.ShopController;

export default () => {

  const [bonusFormModal, setBonusFormModal] = useState(false);
  const [refundFormModal, setRefundFormModal] = useState(false);
  const [createFormModal, setCreateFormModal] = useState(false);

  const [searchParams, setSearchParams] = useState(null);

  const actionRef = useRef();

  const initRow = {
    id: '',
    admin_note: '',
    proof: '',
    is_pay: false
  };

  const [config, setConfig] = useState();
  const [count, setCount] = useState(null);

  const [row, setRow] = useState(initRow);
  const [shopOption, setShopOption] = useState([]);

  const handleRefund = async (fields) => {
    const { success } = await shopOrderRefund({ ...fields });

    if (success) {
      actionRef.current?.reload();
      setRefundFormModal(false);
    }
  };

  const handleCreate = async (fields) => {
    const { success } = await shopOrderCreate({ ...fields });

    if (success) {
      actionRef.current?.reload();
      setCreateFormModal(false);
    }
  };

  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 columns = [
    {
      title: '订单号',
      dataIndex: 'order_no',
      search: true,
      render: (_, record) => {
        return <Space>
          <div>{record?.order_no}</div>
          {/* <Button
            type="link"
            onClick={() => {
              setRow(record);
              setBonusFormModal(true);
            }}
          >
            查看
          </Button> */}
        </Space>;
      },
    },
    {
      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: 'goods',
      search: false,
      render: (_, record) => {
        return <>
          <Image src={record?.goods?.cover[0]} width={50} />
          <div>商品数量：{record?.num}</div>
          <div>商品名称：{record?.goods?.name}</div>
        </>
      },
    },
    {
      title: '订单金额',
      dataIndex: 'pay_money',
      search: false,
    },
    {
      title: '支付方式',
      dataIndex: 'pay_type',
      search: false,
      render: (_, record) => {
        return <>
          {config?.pay_type[record?.pay_type]}
        </>
      },
    },
    {
      title: '付款时间',
      dataIndex: 'pay_time',
      valueType: 'dateRange',
      // initialValue: [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            start_date: value[0],
            end_date: value[1],
          };
        },
      },
      render: (_, record) => {
        return record?.pay_time ? dayjs(record?.pay_time * 1000).format('YYYY-MM-DD HH:mm:ss') : ''
      },
    },
    {
      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: 'refund_note',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>


        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <Row gutter={10}>
          <Col span={6}>
            <Card>
              <div>汇总</div>
              <div>金额: {count?.all0?.money}</div>
              <div className='flex '>
                <div>订单数：{count?.all0?.order_num}</div>
                <div className='w-6'></div>
                <div>商品数：{count?.all0?.goods_num}</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div>微信支付</div>
              <div>金额: {count?.all1?.money}</div>
              <div className='flex '>
                <div>订单数：{count?.all1?.order_num}</div>
                <div className='w-6'></div>
                <div>商品数：{count?.all1?.goods_num}</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div>余额支付</div>
              <div>金额: {count?.all3?.money}</div>
              <div className='flex '>
                <div>订单数：{count?.all3?.order_num}</div>
                <div className='w-6'></div>
                <div>商品数：{count?.all3?.goods_num}</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div>线下支付</div>
              <div>金额: {count?.all4?.money}</div>
              <div className='flex '>
                <div>订单数：{count?.all4?.order_num}</div>
                <div className='w-6'></div>
                <div>商品数：{count?.all4?.goods_num}</div>
              </div>
            </Card>
          </Col>
        </Row>
        <div className='h-3.5'></div>
        <BonusFormModal
          values={row}
          modalOpenState={bonusFormModal}
          onModalOpenState={setBonusFormModal}
        />
        <RefundFormModal
          modalOpenState={refundFormModal}
          onModalOpenState={setRefundFormModal}
          onSubmit={handleRefund}
        />
        <CreateFormModal
          modalOpenState={createFormModal}
          onModalOpenState={setCreateFormModal}
          onSubmit={handleCreate}
        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            defaultCollapsed: false,
          }}
          toolBarRender={() => [
            <AuthConsumer action={'admin/shop_order/create'} key="admin/shop_order/create">
              <Button
                onClick={() => {
                  setCreateFormModal(true);
                }}
              >
                下单
              </Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/shop_order/refund'} key="admin/shop_order/refund">
              <Button

                danger
                onClick={() => {
                  setRefundFormModal(true);
                }}
              >
                退单
              </Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/shop_order/export'} key="admin/shop_order/export">
              <Button type="primary" onClick={() => {
                window.location.href = exportLink(searchParams, '/admin/shop_order/export');
              }}>导出表格</Button>
            </AuthConsumer>,
          ]}
          request={async (params, sorter, filter) => {
            if (!params?.status) {
              params.status = 1;
            }
            setSearchParams({ token: '', ...params });
            const { data, success } = await shopOrderItems({
              ...params,
              sorter,
              filter,
            });
            setConfig(data?.config);
            setCount(data?.count);
            return {
              data: data.items || [],
              total: data.total,
              success,
            };
          }}
          columns={columns}
        />
      </>
    </PageContainer >
  );
};
