import { devicePage, deviceUpdate, deviceAdd, deleteBatchByIds, getInfo, exportExcel, deviceImport, getEnable } from '@/services/power/pile';

import { exportData } from '@/utils/func';
import React, { useRef, useEffect, useState } from 'react';
import { useIntl, useAccess } from '@umijs/max';
import { message, Tag, Select, Tooltip, Button, Modal, Popover, Upload, Switch } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import UpdateForm from './edit';
import UpdateFormUp from './editUp';



import { PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import { merchantPage } from '@/services/merchant/index';

const LogTableList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [modalVisibleUp, setModalVisibleUp] = useState<boolean>(false);

    
    const [currentRow, setCurrentRow] = useState();
    const [searchParams, setSearchParams] = useState(null);
    const [shopOption, setShopOption] = useState([]);
    const searchShop = async (value) => {
        const { success, data } = await merchantPage({
            userName: value
        });
        data.records.map((i) => {
            i.userName = i.userName + ' ' + i.phone
        })
        setShopOption(data.records)
    }

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            valueType: 'text',
            search: false,
            width: 30
        },
        {
            title: '商户信息',
            dataIndex: 'merchantId',
            valueType: 'text',
            width: 150,
            render: (_: any, record: any) => {
                return <div>
                    <div>商户ID：{record?.merchantId}</div>
                    <div>商户名称：{record?.merchantName}</div>
                    <div>商户电话：{record?.merchantPhone}</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: 'stationName',
            valueType: 'text',
            width: 120,
            hideInTable: true
        },
        {
            title: '电站信息',
            dataIndex: 'merchantName',
            valueType: 'text',
            search: false,
            width: 200,
            render: (data, _) => {
                return <div>
                    <div>
                        电站ID:{_.stationId}
                    </div>
                    <div>
                        电站名称:{_.stationName}
                    </div>
                    <div>
                        电站电话:{_.stationTel}
                    </div>
                </div>
            },
        },
        // {
        //     title: '设备名称',
        //     dataIndex: 'deviceName',
        //     valueType: 'text',
        //     // search: false,
        //     width: 150
        // },
        {
            title: '设备编号',
            dataIndex: 'deviceNo',
            valueType: 'text',
            // search: false,
            width: 150
        },
        {
            title: '设备类型',
            dataIndex: 'deviceType',
            valueType: 'text',
            // search: false,
            width: 150,
            render: (_, data) => {
                return _ == 1 ? <Tag color="green">直流</Tag> : _ == 2 ? <Tag color="blue">交流</Tag> : data
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    allowClear
                    placeholder="请选择设备类型"
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "name",
                        value: "id"
                    }}
                    options={[
                        {
                            name: '直流',
                            id: 1
                        },
                        {
                            name: '交流',
                            id: 2
                        }
                    ]}
                />
            },
        },
        {
            title: '最大功率',
            dataIndex: 'maxPower',
            valueType: 'text',
            search: false,
            width: 120
        },
        {
            title: '最大电压',
            dataIndex: 'maxVoltage',
            valueType: 'text',
            search: false,
            width: 120
        },
        {
            title: '枪数',
            dataIndex: 'gunCount',
            valueType: 'text',
            search: false,
            width: 150
        },
        {
            title: '心跳时间',
            dataIndex: 'hearTime',
            valueType: 'text',
            search: false,
            width: 150
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'text',
            // search: false,
            width: 150,
            render: (_, data) => {
                let onChange = async (e) => {
                    let _res = await getEnable({ id: data.id })
                    message.success(e ? '启用成功' : '禁用成功');
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }
                return <Switch checkedChildren="启用" value={data.status == 1 ? true : false} unCheckedChildren="禁用" defaultChecked onChange={onChange} />
                // return _ == 1 ? <Tag color="green">启用</Tag> : _ == 2 ? <Tag color="red">禁用</Tag> : data
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    allowClear
                    placeholder="请选择状态"
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "name",
                        value: "id"
                    }}
                    options={[
                        {
                            name: '启用',
                            id: 1
                        },
                        {
                            name: '禁用',
                            id: 2
                        }
                    ]}
                />
            },
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'text',
            search: false,
            width: 120
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: 120,
            valueType: 'option',
            render: (_, record: any) => [
                <Button
                    type="link"
                    size="small"
                    // hidden={!access.hasPerms('/api/sys/user/update')}
                    onClick={async () => {
                        let { data } = await getInfo({ id: record.id })
                        data.deviceExtendUpdateParams = data.deviceExtendDTO
                        setModalVisibleUp(true);
                        setCurrentRow(data);
                    }}
                >
                    编辑
                </Button>,
                <Button
                    type="link"
                    size="small"
                    danger
                    // hidden={!access.hasPerms('/api/sys/user/deleteUserBatchByIds')}
                    onClick={async () => {
                        Modal.confirm({
                            title: '删除',
                            content: '确定删除该项吗？',
                            okText: '确认',
                            cancelText: '取消',
                            onOk: async () => {
                                const success = await deleteBatchByIds([record.id]);
                                if (success) {
                                    if (actionRef.current) {
                                        actionRef.current.reload();
                                    }
                                }
                            },
                        });
                    }}
                >
                    删除
                </Button>,
            ],
        },
    ];

    const content = (
        <Button color="default" icon={<DownloadOutlined />} type="link" onClick={() => {
            window.open('https://zhongshuai-prod.oss-cn-beijing.aliyuncs.com/template/%E8%AE%BE%E5%A4%87%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx');
        }}>
            电桩导入模板
        </Button>
    );

    // const props = {
    //     name: 'file',
    //     action: process.env.API_URL + '/admin/device/import',
    //     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} 上传失败`);
    //         }
    //     },
    // };

    const props = {
        name: 'file',
        action: process.env.API_URL + '/admin/device/import',
        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>
            <div style={{ width: '100%', float: 'right' }}>
                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    key="logList"
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <Button
                            type="primary"
                            key="add"
                            //   hidden={!access.hasPerms('/api/sys/user/add')}
                            onClick={async () => {
                                setCurrentRow(undefined);
                                setModalVisible(true);
                            }}
                        >
                            <PlusOutlined /> 新增
                        </Button>,
                        <Upload {...props}>
                            <Popover content={content} title="导入模板">
                                <Button type="primary">导入</Button>
                            </Popover>
                        </Upload>,

                        <Button type="primary" onClick={async () => {
                            let _res = await exportExcel(searchParams)
                            exportData(_res, '设备列表')
                        }}>导出</Button>,
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams(params)
                        let { data } = await devicePage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                />
            </div>
            <UpdateForm
                onSubmit={async (values) => {
                    let success = false;
                    if (values.id) {
                        success = await deviceUpdate({ ...values });
                    } else {
                        success = await deviceAdd({ ...values });
                    }
                    if (success) {
                        setModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    setModalVisible(false);
                    setCurrentRow(undefined);
                }}
                open={modalVisible}
                values={currentRow || {}}
            />


            <UpdateFormUp
                onSubmit={async (values) => {
                    let success = false;
                    if (values.id) {
                        success = await deviceUpdate({ ...values });
                    }
                }}
                onCancel={() => {
                    setModalVisibleUp(false);
                    setCurrentRow(undefined);
                }}
                open={modalVisibleUp}
                values={currentRow || {}} />
        </PageContainer>
    );
};

export default LogTableList;
