// 首页广告
// 地址管理
import React, { useRef, useState, Suspense, useEffect } from 'react';
import moment from 'moment'; // 时间相关引用，没有使用可以删除
import numeral from "numeral"; // 数字相关引用，没有使用可以删除
import { connect } from 'umi';

import useRequest from '@ahooksjs/use-request'; // 请求数据的引用
import Draggable from 'react-draggable';
import SubMenu from "antd/lib/menu/SubMenu";
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm, { ProFormDatePicker, ProFormDateTimePicker, ProFormDateTimeRangePicker, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-form';
import { MenuFoldOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Drawer, message, Row, Popconfirm, Space, Image, Modal, Form, Switch, Upload, Tooltip, Descriptions, TreeSelect, Tabs } from 'antd';

import type { CurrentUser } from "umi";
import type { ConnectState } from '@/models/connect';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { FormInstance } from 'antd';
import PageTitleBox from '@/components/PageTitleBox';
import { handeGetUSERDEFINEDTYPEList, handlDeleteUSERDEFINEDTYPE, handlSynchroUSERDEFINEDTYPE } from '../service';
import { render } from 'react-dom';
import { uploadPicture } from '@/services/picture';

const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('请上传JPEG、jpg、png格式的图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

const HomepageAds: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<any>();
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    const [province, setProvince] = useState<string>('');
    const [city, setCity] = useState<string>('');
    const [county, setCounty] = useState<string>('');
    // tab选择框 判断是查看 首页大图的内容 还是小图的内容
    const tabList: any = [{ label: "首页大图", key: "1" }, { label: "轮播图", key: "2" }]
    const [selectTab, setSelectTab] = useState<string>("1")

    const onDraggaleStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    // 拖动结束

    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片

    // 定义列表字段内容
    const columns: any = [
        {
            dataIndex: 'USERDEFINEDTYPE_NAME',
            title: '图片类型',
            width: 150,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'USERDEFINEDTYPE_ICO',
            title: '图片路径',
            width: 150,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return <img style={{ width: '50px', height: '50px', borderRadius: '50%', cursor: 'pointer' }} src={record?.USERDEFINEDTYPE_ICO} onClick={() => {
                    setFileList([{ url: record?.USERDEFINEDTYPE_ICO }])
                    handlePreview()
                }} />
            }
        },
        {
            dataIndex: 'PRESALE_STARTTIME',
            title: '显示开始时间',
            width: 170,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'PRESALE_ENDTIME',
            title: '显示结束时间',
            width: 170,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'STAFF_NAME',
            title: '操作人',
            width: 170,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '操作时间',
            width: 170,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD') : "-"
            }
        },
        {
            dataIndex: 'option',
            title: '操作',
            width: 150,
            align: 'center',
            valueType: 'option',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space>
                        <a
                            onClick={() => {
                                console.log('record', record);
                                setFileList(record?.USERDEFINEDTYPE_ICO ? [{ url: record?.USERDEFINEDTYPE_ICO }] : [])
                                setCurrentRow({ ...record });
                                handleModalVisible(true);
                            }}
                        >
                            编辑
                        </a>
                        <Popconfirm
                            title="确认删除该广告吗?"
                            onConfirm={async () => {
                                await handelDelete(record.USERDEFINEDTYPE_ID);
                            }}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                );
            },
        },
    ];

    // 预览上传后的图片
    const handlePreview = async () => {
        setImagePreviewVisible(true)
    };
    const handleChangePreview = (val: any) => {
        setImagePreviewVisible(val)
    }

    const handelDelete = async (id: number) => {
        const result = await handlDeleteUSERDEFINEDTYPE({
            USERDEFINEDTYPEId: id
        });
        console.log('resultresultresult', result);
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            actionRef.current?.reload()
        }
    };

    const handleAddUpdate = async (res: any) => {
        let req: any = {}

        if (currentRow?.USERDEFINEDTYPE_ID) {
            req = {
                ...currentRow,
                ...res,
                USERDEFINEDTYPE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                PRESALE_STARTTIME: res.PRESALE_TIME && res.PRESALE_TIME.length > 0 ? moment(res.PRESALE_TIME[0]).format('YYYY-MM-DD HH:mm:ss') : "",
                PRESALE_ENDTIME: res.PRESALE_TIME && res.PRESALE_TIME.length > 0 ? moment(res.PRESALE_TIME[1]).format('YYYY-MM-DD HH:mm:ss') : "",
                USERDEFINEDTYPE_ICO: fileList && fileList.length > 0 ? fileList[0].url : "",
                GOODSTYPE: selectTab === "1" ? 7001 : 7000,
            }
        } else {
            req = {
                ...res,
                GOODSTYPE: selectTab === "1" ? 7001 : 7000,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                USERDEFINEDTYPE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                PRESALE_STARTTIME: res.PRESALE_TIME && res.PRESALE_TIME.length > 0 ? moment(res.PRESALE_TIME[0]).format('YYYY-MM-DD HH:mm:ss') : "",
                PRESALE_ENDTIME: res.PRESALE_TIME && res.PRESALE_TIME.length > 0 ? moment(res.PRESALE_TIME[1]).format('YYYY-MM-DD HH:mm:ss') : "",
                USERDEFINEDTYPE_ICO: fileList && fileList.length > 0 ? fileList[0].url : "",
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode
            }
        }
        const data = await handlSynchroUSERDEFINEDTYPE(req);
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            formRef?.current?.resetFields()
            setCurrentRow(undefined)
            handleModalVisible(false)
            actionRef.current?.reload()
            setFileList([])
        } else {
            message.error(data.Result_Desc)
        }
    };

    return (
        <div style={{ backgroundColor: "#fff" }}>
            <div style={{ width: '100%', boxSizing: 'border-box', padding: '24px' }}>
                <Tabs activeKey={selectTab} items={tabList} onChange={(e: any) => {
                    setSelectTab(e)
                }} />
            </div>

            {
                selectTab === "1" ?
                    <ProTable
                        scroll={{ x: "100%" }}
                        formRef={formRef}
                        actionRef={actionRef}
                        search={false}
                        bordered
                        request={async (params, sorter) => {
                            console.log('params', params);
                            const req = {
                                SearchParameter: {
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    GOODSTYPE: 7001,
                                    USERDEFINEDTYPE_STATE: 1
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "OPERATE_DATE desc",
                            }
                            const data = await handeGetUSERDEFINEDTYPEList(req);
                            console.log('datadatadatadatadata', data);
                            if (data.List && data.List.length > 0) {
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        columns={columns}
                        toolbar={{
                            actions: [
                                <Button type={'primary'} onClick={() => {
                                    handleModalVisible(true)
                                }}>
                                    新增大图
                                </Button>
                            ]
                        }}
                    /> : ""
            }

            {
                selectTab === "2" ?
                    <ProTable
                        scroll={{ x: "100%" }}
                        formRef={formRef}
                        actionRef={actionRef}
                        search={false}
                        bordered
                        request={async (params, sorter) => {
                            console.log('params', params);
                            const req = {
                                SearchParameter: {
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    GOODSTYPE: 7000,
                                    USERDEFINEDTYPE_STATE: 1
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "OPERATE_DATE desc",
                            }
                            const data = await handeGetUSERDEFINEDTYPEList(req);
                            console.log('datadatadatadatadata', data);
                            if (data.List && data.List.length > 0) {
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        columns={columns}
                        toolbar={{
                            actions: [
                                <Button type={'primary'} onClick={() => {
                                    handleModalVisible(true)
                                }}>
                                    新增轮播图
                                </Button>
                            ]
                        }}
                    /> : ""
            }

            {/* 图片预览组件 */}
            {fileList && fileList.length > 0 && <div style={{ display: 'none' }}>
                <Image.PreviewGroup
                    preview={{
                        visible: imagePreviewVisible,
                        onVisibleChange: vis => {
                            handleChangePreview(vis)
                        }
                    }}>
                    {
                        fileList.map((n) => <Image src={n.url} key={n.url} />)
                    }
                </Image.PreviewGroup>
            </div>}

            <Modal
                title={
                    <div
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {currentRow ? '更新会员收货地址' : '新建会员收货地址'}
                    </div>
                }
                destroyOnClose={true}
                width={900}
                visible={modalVisible}
                confirmLoading={confirmLoading}
                afterClose={() => {
                    formRef.current?.resetFields();
                    setCurrentRow(undefined);
                }}
                onCancel={() => {
                    handleConfirmLoading(false)
                    handleModalVisible(false)
                    setFileList([])
                }}

                onOk={async () => { // 提交框内的数据
                    formRef?.current?.validateFields().then(() => {
                        handleConfirmLoading(true)
                        formRef?.current?.submit()
                    })
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    layout={'horizontal'}
                    labelCol={{ style: { width: '80px' } }}
                    formRef={formRef}
                    autoFocusFirstInput
                    submitter={false}
                    preserve={false}
                    initialValues={currentRow ? {
                        ...currentRow,
                        PRESALE_TIME: [currentRow?.PRESALE_STARTTIME, currentRow?.PRESALE_ENDTIME,]
                    } : {
                        USERDEFINEDTYPE_NAME: selectTab === "1" ? "小程序海报" : "小程序轮播图",
                        USERDEFINEDTYPE_STATE: 1
                    }}
                    onFinish={async (values) => {
                        let newValue: any = { ...values };
                        if (currentRow) {
                            // 编辑数据
                            newValue = { ...values, MEMBERADDRESS_ID: currentRow.MEMBERADDRESS_ID };
                        }
                        await handleAddUpdate(newValue);

                        handleConfirmLoading(false)
                    }}
                >
                    <Row gutter={8}>
                        <Col span={12}>
                            <ProFormText
                                name="USERDEFINEDTYPE_NAME"
                                label="图片类型"
                                disabled
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="USERDEFINEDTYPE_STATE"
                                label="有效状态"
                                options={[
                                    { label: "有效", value: 1 },
                                    { label: "无效", value: 0 },
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDateTimeRangePicker
                                name="PRESALE_TIME"
                                label="显示时间"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormUploadButton
                                name="USERDEFINEDTYPE_ICO"
                                label="上传附件"
                                fileList={fileList}
                                listType="picture-card"
                                accept="image/*"
                                fieldProps={{
                                    beforeUpload,
                                    maxCount: 1,
                                    onPreview: handlePreview,
                                    customRequest: async (info) => {
                                        const formData = new FormData();
                                        formData.append('files', info.file);
                                        formData.append('TableType', selectTab === "1" ? '1214' : "1213");
                                        formData.append('ImageName', typeof info.file !== 'string' ? info.file?.name : '');
                                        if (info.filename) {
                                            const success = await uploadPicture(formData)
                                            if (success) {
                                                const list = [{
                                                    // uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                    name: success.Result_Data.ImageName,
                                                    // status: 'done',
                                                    url: success.Result_Data.ImageUrl, // url 是展示在页面上的绝对链接
                                                    // imgUrl: success.ImagePath  // + success.ImageUrl,
                                                }]


                                                setFileList(list)
                                            }
                                        } else {
                                            message.error("您上传的图片不存在.")
                                        }
                                    }
                                }}
                            />
                        </Col>
                    </Row>
                </ProForm>
            </Modal>
        </div>
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(HomepageAds);
