import { DropboxOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Popconfirm,Form } 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 [form] = Form.useForm();

    /** 新建/更新窗口的弹窗 */
    const [createModalVisible, handleModalVisible] = useState(false);
    /** 分布更新窗口的弹窗 */

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

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

    const [storeList, setStoreList] = useState([]);

    useEffect(() => {
        var data = GetStoreInfoPageAsync().then((data) => {
            var list = [];
            data.data?.forEach((item) => {
                list.push({ id: item.id, text: item.name, value: item.id, label: item.name });
            });
            setStoreList(list);
        });

    }, [])


    /**
     * 添加节点
     *
     * @param fields
     */
    function handleAdd(fields) {
        // message.loading('正在添加');
        try {
            addAdvertisement(JSON.stringify(fields));
            message.success('添加成功');
            //刷新数据
            actionRef.current.reloadAndRest();
            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.reloadAndRest();
                } else {
                    message.error('修改失败请重试！');
                }
            });
            return true;
        } catch (error) {
            message.error('修改失败请重试！');
            return false;
        }
    }

    /**
     * 批量删除节点
     *
     * @param selectedRows
     */
    function handleRemove(ids) {
        try {
            removeAdvertisement(ids).then((r) => {
                if (r.data) {
                    message.success('删除成功，即将刷新');
                } else {
                    message.error('删除失败，请重试');
                }
            });
            //刷新数据
            actionRef.current.reloadAndRest();
            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',
            valueType: 'select',
            fieldProps: {
              options: storeList,
            },
        },
        {
            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',
            fixed: 'right',
            width: 150,
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        if (record.startTime != null) {
                            record.planDate=[];
                            record.planDate[0]=moment(record.startTime);
                            record.planDate[1]=moment(record.endTime);
                            record.startTime = moment(record.startTime);
                            record.endTime = moment(record.endTime);
                           
                        }
                        setCurrentRow(() => {
                            return record;
                        });
                        form.setFieldsValue(record);
                        handleModalVisible(true);
                    }}
                >
                    更新
                </a>,

                <Popconfirm
                key="delete"
                title={`确定修改状态吗？`}
                    onConfirm={async () => {
                        record.status = record.status == 0 ? 1 : 0;
                        updateAdvertisementStatus({id:record.id,status:record.status}).then((r) => {
                            if (r.data) {
                                actionRef.current.reloadAndRest();
                            }
                        });
                    }}
                okText="确定"
                cancelText="取消"
                >
                {/* <a href="#"> {record.status == 0 ? '停用' : '启用'}</a> */}
                </Popconfirm>,
                 <Popconfirm
                 key="delete"
                 title={`确定要删除吗？`}
                     onConfirm={async () => {
                         handleRemove([record.id]);
                         actionRef.current?.reloadAndRest?.();
                     }}
                 okText="确定"
                 cancelText="取消"
             >
                 <a href="#">删除</a>
             </Popconfirm>,
            ],
        },
    ];

    return (
        <PageContainer header={{
            title: '',
            breadcrumb: {},
        }}>
            <ProTable
              pagination={{
                pageSize: 10
            }}
            scroll={{
                x: 1300,
            }}
                headerTitle="广告列表"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                columns={columns}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            form.setFieldsValue({});
                            setCurrentRow({});
                            handleModalVisible(true);
                        }}
                    >
                        <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
                 form={form}
                storeArray={storeList}
                onFinish={async (value) => {
                    if(value?.imageUrl?.length<=0&&value?.uploadType==0){
                        message.error("请选择图片");
                        return;
                    }
                    
                    var success = false;
                    if(value.startTime!=null){

                        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.reloadAndRest();
                        }
                    }
                }}

                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;
