import { operatorPage, deleteBatchByIds, operatorAdd, operatorUpdate, changeStatus } from '@/services/operator/index';
import { merchantPage } from '@/services/merchant/index';

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, Image, Popover, Switch } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import UpdateForm from './edit';
import { PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import CardTable from './cardTable';

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

    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: 'keywords',
            valueType: 'text',
            hideInTable: true
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            valueType: 'text',
            search: false,
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            valueType: 'text',
            search: false,
        },
        {
            title: '余额',
            dataIndex: 'balance',
            valueType: 'text',
            search: false,
        },

        {
            title: '分成比例配置',
            dataIndex: 'name',
            valueType: 'text',
            search: false,
            render: (_: any, record: any) => {
                return <div>
                    <div>名称：{record?.name}</div>
                    <div>电费分成比例：{record?.electricityRate}</div>
                    <div>服务费分成比例：{record?.serviceRate}</div>
                </div>
            },
        },
        // {
        //     title: '版本',
        //     dataIndex: 'version',
        //     valueType: 'text',
        //     search: false,
        // },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'text',
            search: true,
            width: 120,
            render: (_, data) => {
                let onChange = async (e) => {
                    let _res = await changeStatus({ 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} />
            },
            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: 'dateRange',
            search: {
                transform: (value) => {
                    return {
                        startTime: value[0],
                        endTime: value[1],
                    };
                },
            },
            render: (_: any, record: any) => {
                return record.createTime
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: 120,
            valueType: 'option',
            render: (_, record: any) => [
                <Button
                    type="link"
                    size="small"
                    // hidden={!access.hasPerms('/api/sys/user/update')}
                    onClick={async () => {
                        setRow1(record)
                        setModalVisit(true)
                    }}
                >
                    设备信息
                </Button>,
                <Button
                    type="link"
                    size="small"
                    // hidden={!access.hasPerms('/api/sys/user/update')}
                    onClick={async () => {
                        setModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    编辑
                </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) {
                                        message.success('删除成功');
                                        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 { data } = await operatorPage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                />
            </div>
            <UpdateForm
                onSubmit={async (values) => {
                    let success = false;
                    if (values.id) {
                        success = await operatorUpdate({ ...values });
                        message.success('修改成功');
                    } else {
                        success = await operatorAdd({ ...values });
                        message.success('添加成功');
                    }
                    if (success) {
                        setModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    setModalVisible(false);
                    setCurrentRow(undefined);
                }}
                open={modalVisible}
                values={currentRow || {}}
            />
            <CardTable modalVisit={modalVisit} values={row1} setModalVisit={setModalVisit} />
        </PageContainer>
    );
};

export default LogTableList;
