import { cardPage, cardUpdate, cardAdd, deleteBatchByIds, getInfo, changeStatus } from '@/services/power/card';


import React, { useRef, useEffect, useState } from 'react';
import { useIntl, useAccess } from '@umijs/max';
import { message, Tag, Select, Tooltip, Button, Modal, Switch } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import UpdateForm from './edit';
import { PlusOutlined } from '@ant-design/icons';
import { merchantPage } from '@/services/merchant/index';
import { getMerchantSelectDevice } from '@/services/merchant/index'



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


    const [shopOption, setShopOption] = useState([]);
    const [devOption, setDevOption] = 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: 'name',
            valueType: 'text',
        },
        {
            title: '金额',
            dataIndex: 'amount',
            valueType: 'text',
            search: false,
        },
        {
            title: '赠送金额',
            dataIndex: 'giveAmount',
            valueType: 'text',
            search: false,
        },
        {
            title: '电站信息',
            dataIndex: 'maxVoltage',
            valueType: 'text',
            search: false,
            render: (_: any, record: any) => {
                return <div>
                    <div>电站ID：{record?.stationId}</div>
                    <div>电站名称：{record?.stationName}</div>
                    <div>
                        电站电话:{record?.stationTel}
                    </div>
                </div>
            },
        },
        {
            title: '商户信息',
            dataIndex: 'merchantId',
            valueType: 'text',
            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: 'status',
            valueType: 'text',
            render: (_: any, record: any) => {
                // 业务状态:0-未使用;1-充电中;2-预约中;
                let data = ['blue', 'orange', 'magenta']
                return <Tag color={data[record?.status]}>{record?.status == 0 ? '未使用' : record?.status == 1 ? '发布' : record?.status == 2 ? '取消发布' : '-'}</Tag>
            },
            // render: (_, record) => {
            //     let onChange = async (e) => {
            //         let _res = await changeStatus({id:record.id})
            //         // message.success(e ? '上架成功' : '下架成功');
            //         if (actionRef.current) {
            //             actionRef.current.reload();
            //         }
            //     }
            //     return <Switch checkedChildren="上架" unCheckedChildren="下架" defaultChecked onChange={onChange} />
            // },
            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: 0
                        },
                        {
                            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"
                    danger
                    hidden={record.status !== 0}
                    onClick={async () => {
                        Modal.confirm({
                            title: '提示',
                            content: '是否确认发布？发布后不允许修改',
                            okText: '确认',
                            cancelText: '取消',
                            onOk: async () => {
                                let _res = await changeStatus({ id: record.id })
                                message.success('发布成功');
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                            },
                        });
                    }}
                >
                    发布
                </Button>,
                <Button
                    type="link"
                    size="small"
                    danger
                    hidden={record.status !== 1}
                    onClick={async () => {
                        Modal.confirm({
                            title: '提示',
                            content: '是否确认取消发布？取消发布后不允许重新发布',
                            okText: '确认',
                            cancelText: '取消',
                            onOk: async () => {
                                let _res = await changeStatus({ id: record.id })
                                message.success('取消发布成功');
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                            },
                        });
                    }}
                >
                    取消发布
                </Button>,
                <Button
                    type="link"
                    size="small"
                    // hidden={!access.hasPerms('/api/sys/user/update')}
                    onClick={async () => {
                        let { data } = await getInfo({ id: record.id })
                        setModalVisible(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>,
            ],
        },
    ];

    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>,
                    ]}
                    request={async (params, sorter, filter) => {

                        let _res = await getMerchantSelectDevice()
                        setDevOption(_res.data)

                        let { data } = await cardPage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                />
            </div>
            <UpdateForm
                onSubmit={async (values) => {
                    let success = false;
                    if (values.id) {
                        success = await cardUpdate({ ...values });
                    } else {
                        success = await cardAdd({ ...values });
                    }
                    if (success) {
                        setModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    setModalVisible(false);
                    setCurrentRow(undefined);
                }}
                open={modalVisible}
                values={currentRow || {}}
            />
        </PageContainer>
    );
};

export default LogTableList;
