import { DropboxOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import moment from 'moment';
import { getAdvertisementList, addAdvertisement, updateAdvertisement, removeAdvertisement, GetStoreInfoPageAsync, updateAdvertisementStatus } from './service';


//页面 相当于 class
const PlanManage = () => {
    /** 新建/更新窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState(false);
    /** 分布更新窗口的弹窗 */

    const [showDetail, setShowDetail] = useState(false);
    //绑定
    const actionRef = useRef();
    const [currentRow, setCurrentRow] = useState();

    //选中的行
    const [selectedRowsState, setSelectedRows] = useState([]);

    const [storeEnum, setStoreEnum] = useState();
    const [storeArray, setStoreArray] = useState([]);

    //初始化数据
    useEffect(() => {

        //初始化店铺
        const initStore = (val) => {
            var data = GetStoreInfoPageAsync({ current: 1, pageSize: 1000 }).then((data) => {
                var list = {};
                let list2 = [];
                data.data.data.forEach((item) => {
                    list2.push({
                        text: item.store_Name,
                        id: item.id,
                    });
                    list[item.id] = { text: item.store_Name };
                });
                setStoreArray(list2);
                setStoreEnum(list);
                console.log(list2);
            });
        };

        initStore();

    }, []);


    /**
     * 添加节点
     *
     * @param fields
     */
    function handleAdd(fields) {
        // message.loading('正在添加');
        try {
            addAdvertisement(JSON.stringify(fields));
            message.success('添加成功');
            //刷新数据
            actionRef.current.reload();
            return true;
        } catch (error) {
            message.error('添加失败请重试！');
            return false;
        }
    }

    /**
     * 更新节点
     *
     * @param fields
     */
    function handleUpdate(fields) {
        try {
            updateAdvertisement(JSON.stringify(fields)).then((r) => {
                if (r.data) {
                    message.success('修改成功');
                    actionRef.current.reload();
                } else {
                    message.error('修改失败请重试！');
                }
            });
            return true;
        } catch (error) {
            message.error('修改失败请重试！');
            return false;
        }
    }

    /**
     * 批量删除节点
     *
     * @param selectedRows
     */
    function handleRemove() {
        try {
            removeAdvertisement(selectedRowsState.map((item, index) => item.id)).then((r) => {
                if (r.data) {
                    message.success('删除成功，即将刷新');
                } else {
                    message.error('删除失败，请重试');
                }
            });
            //刷新数据
            actionRef.current.reload();
            return true;
        } catch (error) {
            message.error('删除失败，请重试');
        }
    }


    /** 国际化配置 */

    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            tip: '规则名称是唯一的 key',
            hideInSearch: true,
            hideInTable: true,
            render: (dom, entity) => {
                return (
                    <a
                        onClick={() => {
                            setCurrentRow(entity);
                            setShowDetail(true);
                        }}
                    >
                        {dom}
                    </a>
                );
            },
        },
        {
            title: '店铺',
            dataIndex: 'storeId',
            valueEnum: storeEnum,
        },
        {
            title: '广告类型',
            dataIndex: 'type',
            valueEnum: {
                0: { text: '图片' },
                1: { text: '视频' }
            },
            hideInSearch: true,
        },
        {
            title: '上传方式',
            dataIndex: 'uploadType',
            valueEnum: {
                0: { text: '自定义上传' },
                1: { text: '网络路径' }
            },
            hideInSearch: true,
        },
        {
            title: '广告标题',
            dataIndex: 'title',
            valueType: 'textarea',
        },
        {
            title: '轮播间隔（秒）',
            dataIndex: 'step',
            valueType: 'textarea',
            hideInSearch: true,
        },
        {
            title: '开始时间',
            hideInSearch: true,
            dataIndex: 'startTime',
            valueType: 'dateTime',
        },
        {
            title: '结束时间',
            hideInSearch: true,
            dataIndex: 'endTime',
            valueType: 'dateTime',
        },
        {
            title: '状态',
            dataIndex: 'status',
            hideInForm: true,
            hideInSearch: true,
            valueEnum: {
                0: {
                    text: '正常',
                    status: 'Processing',
                },
                1: {
                    text: '停用',
                    status: 'Success',
                },
            },
        },
        {
            title: '创建时间',
            dataIndex: 'createAt',
            valueType: 'textarea',
            hideInSearch: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        handleModalVisible(true);
                        setCurrentRow(() => {
                            if (record.startTime != null) {
                                record.startTime = moment(record.startTime);
                                record.endTime = moment(record.endTime);
                            }
                            return record;
                        });
                    }}
                >
                    更新
                </a>,
                <a
                    key="primary"
                    onClick={() => {
                        record.status = record.status == 0 ? 1 : 0;
                        updateAdvertisementStatus(record).then((r) => {
                            if (r.data) {
                                actionRef.current.reload();
                            }
                        });
                    }}
                >
                    {' '}
                    {record.status == 0 ? '停用' : '启用'}
                </a>,
            ],
        },
    ];

    return (
        <PageContainer>
            <ProTable
                headerTitle="广告列表"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                columns={columns}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                            setCurrentRow({});
                        }}
                    >
                        <PlusOutlined /> 新建
                    </Button>,
                ]}
                //数据绑定
                request={async (params) => {
                    var resultData = [];
                    var total = 0;
                    await getAdvertisementList(params).then((r) => {
                        resultData = r.data.data;
                        total = r.data.total;
                    });
                    return {
                        data: resultData,
                        success: true,
                        total: total,
                    };
                }}
                // 每行选择点击事件
                rowSelection={{
                    onChange: (_, selectedRows) => {
                        setSelectedRows(selectedRows);
                    },
                }}
            ></ProTable>
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a
                                style={{
                                    fontWeight: 600,
                                }}
                            >
                                {selectedRowsState.length}
                            </a>{' '}
                            项 &nbsp;&nbsp;
                        </div>
                    }
                >

                    <Popconfirm
                        type="primary"
                        key="primary"
                        title="确认是否删除选中项？"
                        okText="是"
                        cancelText="否"
                        onConfirm={() => {
                            handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                        onCancel={() => { }}
                    >
                        <a href="#">批量删除</a>
                    </Popconfirm>

                </FooterToolbar>
            )}
            {/* 广告(新增，修改) */}
            <CreateForm
                storeArray={storeArray}
                onFinish={async (value) => {
                    var success = false;
                    value.startTime = moment(value.planDate[0]).format('YYYY-MM-DD HH:mm:ss');
                    value.endTime = moment(value.planDate[1]).format('YYYY-MM-DD HH:mm:ss');
                    if (value.id) {
                        success = await handleUpdate(value);
                    } else {
                        success = await handleAdd(value);
                    }
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}

                onCancel={() => {
                    setCurrentRow(undefined);
                    handleModalVisible(false);
                }}

                createModalVisible={createModalVisible}
                values={currentRow || {}}
            />
            <Drawer
                width={600}
                visible={showDetail}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetail(false);
                }}
                closable={false}
            >
                {currentRow?.name && (
                    <ProDescriptions
                        column={2}
                        title={currentRow?.name}
                        request={async () => ({
                            data: currentRow || {},
                        })}
                        params={{
                            id: currentRow?.name,
                        }}
                        columns={columns}
                    />
                )}
            </Drawer>
        </PageContainer>
    );
};

export default PlanManage;
