import { devicePage, importDeviceData, getDeviceAnalyze, deviceExport } from '@/services/piles';
import { exportData } from '@/utils/func';
import React, { useRef, useEffect, useState } from 'react';
import { useIntl, useAccess } from '@umijs/max';
import { message, Tag, Image, Button, Select, Row, Col, Card } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import BonusFormModal from './components/BonusFormModal';
import TempFormModal from './components/TempFormModal';
import { usersPage } from '@/services/user/user';


const LogTableList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [searchParams, setSearchParams] = useState(null);
    const [bonusFormModal, setBonusFormModal] = useState(false);
    const [row, setRow] = useState();
    const [tempFormModal, setTempFormModal] = useState(false);
    const access = useAccess()
    const [shopOption, setShopOption] = useState([]);
    const [count, setCountRows] = useState(false);

    const countInit = async (params) => {
        const { success, data } = await getDeviceAnalyze(params);
        if (success) {
            setCountRows(data)
        }
    }


    const handleTemp = async (fields) => {

        const { success } = await importDeviceData(fields);
        if (success) {
            message.success('导入成功');
            actionRef.current?.reload();
            setTempFormModal(false);
        }
    };

    const searchShop = async (value) => {
        const { success, data } = await usersPage({
            userId: value
        });
        data.records.map((i) => {
            i.userName = i.userName + ' ' + i.phone
        })
        setShopOption(data.records)
    }

    const columns = [
        {
            title: '设备号',
            dataIndex: 'deviceNo',
            valueType: 'text',
            search: true,
            render: (_: any, record: any) => {
                return <div className={'flex items-center'}>
                    {record.deviceNo || '-'}
                    <Button type="link" onClick={() => {
                        setRow(record);
                        setBonusFormModal(true);
                    }}>查看</Button>
                </div>
            }
        },
        {
            title: '订单号',
            dataIndex: 'orderNo',
            valueType: 'text',
            search: true,
        },
        {
            title: '用户信息',
            dataIndex: 'userId',
            valueType: 'text',
            render: (_: any, record: any) => {
                return <div>
                    <div>用户名：{record?.userName}</div>
                    <div>手机号：{record?.phone}</div>
                    <div>等级：{record?.level}</div>
                </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: "userName",
                        value: "id"
                    }}
                    options={shopOption}
                />
            },
        },
        {
            title: '设备添加天数',
            dataIndex: 'addDate',
            valueType: 'text',
            search: false,
        },
        {
            title: '设备类型',
            dataIndex: 'deviceType',
            valueType: 'text',
            search: false,
            render: (_: any, record: any) => {
                return record?.deviceType + 'KW'
            }
        },

        {
            title: '设备状态',
            dataIndex: 'deviceStatus',
            valueType: 'text',
            render: (_: any, record: any) => {
                let color = record.deviceStatus == 1 ? 'volcano' : record.deviceStatus == 2 ? 'orange' : 'red'
                return <Tag color={color}>{record.deviceStatus == 1 ? '已安装' : record.deviceStatus == 2 ? '已运营' : '未安装'}</Tag>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    allowClear
                    showSearch
                    placeholder="请输入选择"
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "label",
                        value: "value"
                    }}
                    options={[
                        {
                            label: '未安装',
                            value: '0'
                        },
                        {
                            label: '已安装',
                            value: '1'
                        },
                    ]}
                />
            },
        },
        {
            title: '安装站点名称',
            dataIndex: 'stationName',
            valueType: 'text',
            search: false,
        },
        {
            title: '安装站点地址',
            dataIndex: 'stationAddress',
            valueType: 'text',
            search: false,
        },
        {
            title: '安装时间',
            dataIndex: 'installTime',
            valueType: 'text',
            search: false,
        },
        {
            title: '交付时间',
            dataIndex: 'deliverDate',
            valueType: 'text',
            search: false,
            render: (_: any, record: any) => {
                return record?.deliverDate + '天'
            }
        },
        {
            title: '分账有效期',
            dataIndex: 'paymentValidity',
            valueType: 'text',
            search: false,
        },
        {
            title: '分账类型',
            dataIndex: 'paymentType',
            valueType: 'text',
            render: (_: any, record: any) => {
                let color = ['magenta', 'red', 'volcano', 'orange', 'gold']
                let name = ['不分账', '普通分账', '赠送桩', '冻结收益']
                return <Tag color={color[record.paymentType]}>{name[record.paymentType]}</Tag>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    placeholder="请输入选择"
                    style={{ width: "100%" }}
                    fieldNames={{
                        label: "label",
                        value: "value"
                    }}
                    options={[
                        {
                            label: '不分账',
                            value: '0'
                        },
                        {
                            label: '普通分账',
                            value: '1'
                        },
                        {
                            label: '赠送桩',
                            value: '2'
                        },
                        {
                            label: '冻结收益',
                            value: '3'
                        }
                    ]}
                />
            },
        },

        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateRange',
            search: {
                transform: (value) => {
                    return {
                        createTimeBegin: value[0],
                        createTimeEnd: value[1],
                    };
                },
            },
            render: (_: any, record: any) => {
                return record.createTime
            },
        },
    ];

    return (
        <PageContainer>
            <Row gutter={10}>
                <Col span={6}>
                    <Card>
                        <div>总数</div>
                        <div>数量: {count?.deviceTotal}</div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div>已安装</div>
                        <div>数量: {count?.installedCount}</div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div>未安装</div>
                        <div>数量: {count?.notInstalledCount}</div>
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <div>已过期</div>
                        <div>数量: {count?.expiredCount}</div>
                    </Card>
                </Col>
            </Row>
            <div className='h-3.5'></div>
            <div style={{ width: '100%', float: 'right' }}>
                <BonusFormModal
                    values={row}
                    modalOpenState={bonusFormModal}
                    onModalOpenState={setBonusFormModal}
                />
                <TempFormModal
                    modalOpenState={tempFormModal}
                    onModalOpenState={setTempFormModal}
                    onSubmit={handleTemp}
                />
                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    key="logList"
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <Button type="primary" onClick={async () => {
                            let data = JSON.parse(JSON.stringify(searchParams))
                            delete data.pageSize
                            delete data.current
                            let _res = await deviceExport(data)
                            exportData(_res, '设备记录')
                        }}>导出</Button>,
                        <Button hidden={!access.hasPerms('/api/device/importDeviceData')} onClick={async () => {
                            setTempFormModal(true)
                        }}>导入</Button>
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams({ ...params });
                        countInit(params)
                        let { data } = await devicePage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                />
            </div>
        </PageContainer>
    );
};

export default LogTableList;
