import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';
import CreateFormModal from './components/CreateFormModal';
import CancellationModal from './components/CancellationModal';
import { Select, Space, Image, Button } 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 services from '@/services/admin';

// const { shopActivityItems, shopDeleteItems } = services.ShopActivityController;
// const { shopItems } = services.ShopController;
// const { shopActivity } = services.ShopActivity;
export default () => {
    const [createFormModal, setCreateFormModal] = useState(false);

    const [cancellationModal, setCancellationModal] = useState(false)

    const initRow = {
        shop_id: '',
        todate: '',
    };

    const initRowCancellationModal = {
        username: "",
        mobile: "",
        code: ""
    }


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



    const [rowCancellationModal, setRowCancellationModal] = useState(initRowCancellationModal);


    const actionRef = useRef();

    const [config, setConfig] = useState();

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

    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 handleCreate = async (fields) => {
        setRow(fields);
        // let data = JSON.parse(JSON.stringify(fields))
        // const { m, mobile, username, ...rest } = data;
        // const extracted = { m, mobile, username };
        // const remainingData = { ...rest };
        const { success } = await shopActivity(fields);

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

    const handleCreateFormModal = async (fields) => {
        setRowCancellationModal(fields)
        const { success } = await shopDeleteItems(fields);
        if (success) {
            setRowCancellationModal(initRow);
            actionRef.current?.reload();
            setCancellationModal(false);
        }

    }

    const columns = [
        {
            title: '活动名称',
            dataIndex: 'title',
            search: false,
        },
        {
            title: '投资人',
            dataIndex: 'shop_id',
            render: (_, record) => {
                return <>
                    <div>用户名：{record?.shop?.username}</div>
                    <div>手机号：{record?.shop?.mobile}</div>
                    <div>等级：{record?.vip}</div>
                </>
            },
            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}
                />
            },
        },
        {
            title: '时间',
            dataIndex: 'm',
            search: false,
            render: (_, record) => {
                return record?.m + '个月'
            },
        },
        {
            title: '有效期',
            dataIndex: 'type',
            search: false,
            render: (_, record) => {
                return record?.valid_time ? dayjs(record?.valid_time * 1000).format('YYYY-MM-DD') : ''
            },
        },
        {
            title: '客户资料',
            dataIndex: 'type',
            search: false,
            render: (_, record) => {
                return <>
                    <div>车辆型号：{record?.info?.car_name}</div>
                    <div>车主姓名：{record?.info?.realname}</div>
                    <div>车牌号码：{record?.info?.plate_code}</div>
                    <div>车架号码：{record?.info?.car_code}</div>
                    <div>还款卡号：{record?.info?.bank_num}</div>
                    <div>银行名称：{record?.info?.bank_name}</div>
                    <div>还款日期：{record?.info?.todate}</div>
                </>
            },
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            search: false,
        }
    ];

    return (
        <PageContainer
            ghost
        >
            <>
                <CreateFormModal
                    values={row}
                    modalOpenState={createFormModal}
                    onModalOpenState={setCreateFormModal}
                    onSubmit={handleCreate}
                />
                <CancellationModal
                    values={rowCancellationModal}
                    modalOpenState={cancellationModal}
                    onModalOpenState={setCancellationModal}
                    onSubmit={handleCreateFormModal}
                />
                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    search={{
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <AuthConsumer action={'admin/shop_activity/create'} key="admin/shop_activity/create">
                            <Button
                                type="primary"
                                style={{ background: '#67c23a' }}
                                onClick={() => {
                                    setCreateFormModal(true)
                                }}
                            >
                                添加
                            </Button>
                        </AuthConsumer>,
                        <AuthConsumer action={'admin/shop_activity/export'} key="admin/shop_activity/export">
                            <Button type="primary" onClick={() => {
                                window.location.href = exportLink(searchParams, '/admin/shop_activity/export');
                            }}>导出表格</Button>
                        </AuthConsumer>,
                        <AuthConsumer action={'admin/shop_activity/delete'} key="admin/shop_activity/delete">
                            <Button
                                danger
                                type="primary"
                                onClick={() => {
                                    setCancellationModal(true)
                                }}
                            >
                                作废
                            </Button>
                        </AuthConsumer>
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams({ token: '', ...params });
                        const { data, success } = await shopActivityItems({
                            ...params,
                            sorter,
                            filter,
                        });
                        return {
                            data: data?.items || [],
                            total: data?.total,
                            success,
                        };
                    }}
                    columns={columns}
                />
            </>
        </PageContainer>
    );
};
