import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, Col, message, Modal, Popconfirm, Row, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import PageTitleBox from "@/components/PageTitleBox";
import Draggable from "react-draggable";
import ProForm, { ProFormCheckbox, ProFormDatePicker, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import moment from "moment";
import { handleDeleteACTIVITY, handleGetACTIVITYList, handleGetSynchroACTIVITY } from "../SharedRestStationManagement/service";
import session from "@/utils/session";
import './style.less'
import { set } from "lodash";
import { compressImage } from "@/utils/imageCompress";
import { deleteAHYDPicture, uploadAHYDPicture } from "./service";
import EventRegistrationDetail from "./components/EventRegistrationDetail";



const EventRegistration: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const { confirm } = Modal;
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [collapsible, setCollapsible] = useState<boolean>(false)

    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const serverpartObj = session.get('serverpartObj')
    const serverpartList = session.get('serverpartList')
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    // 当前选择的行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 选择服务区的悬浮框
    const [selectServerpartModal, handleSelectServerpartModal] = useState<boolean>(false)

    const columns: any = [
        {
            title: '统计时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            hideInSearch: false,
            initialValue: [moment(), moment().subtract(-1, 'M')],
            search: {
                transform: (value) => {
                    return {
                        ACTIVITY_ENDDATE_Start: value[0],
                        ACTIVITY_STARTDATE_End: value[1],
                    };
                },
            },
        },
        {
            title: '服务区',
            dataIndex: "SERVERPART_IDS",
            hideInTable: true,
            valueType: 'select',
            valueEnum: serverpartObj,
            fieldProps: {
                showSearch: true, // 支持输入文字搜索
                filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>活动名称</div>,
            width: 180,
            dataIndex: "ACTIVITY_NAME",
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>活动范围</div>,
            width: 150,
            dataIndex: "SERVERPART_NAME",
            ellipsis: true,
            hideInSearch: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>活动地点</div>,
            width: 150,
            dataIndex: "ACTIVITY_LOCATION",
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>人数上限</div>,
            width: 120,
            dataIndex: "MAXIMUM_CAPACITY",
            ellipsis: true,
            hideInSearch: true,
            valueType: "digit",
            align: 'right'
        },
        {
            title: <div style={{ textAlign: 'center' }}>活动描述</div>,
            width: 250,
            dataIndex: "ACTIVITY_INFO",
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>活动时间</div>,
            width: 170,
            dataIndex: "ACTIVITY_STARTDATE",
            ellipsis: true,
            hideInSearch: true,
            align: 'center',
            render: (_, record) => {
                return record?.ACTIVITY_STARTDATE && record?.ACTIVITY_ENDDATE ? `${moment(record?.ACTIVITY_STARTDATE).format('YYYY/MM/DD')}-${moment(record?.ACTIVITY_ENDDATE).format('YYYY/MM/DD')}` : '不限时间'
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>活动状态</div>,
            width: 120,
            dataIndex: "ACTIVITY_STATE",
            ellipsis: true,
            hideInSearch: true,
            align: 'center',
            valueType: "select",
            valueEnum: {
                1: { text: '已上架', status: 'success' },
                2: { text: '未上架', status: 'error' },
                9: { text: '已下架', status: 'error' },
            }
        },
        {
            title: "操作",
            dataIndex: "option",
            width: 120,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return <Space>
                    <a onClick={() => {
                        let imgList: any = []
                        if (record?.ImageList && record?.ImageList.length > 0) {
                            record?.ImageList.forEach((item: any) => {
                                let obj = JSON.parse(JSON.stringify(item))
                                obj.url = obj.ImageUrl
                                obj.name = obj.ImageName
                                obj.uid = item.ImageId
                                obj.status = 'done'
                                imgList.push(obj)
                            })
                        }
                        setCurrentRow({
                            ...record,
                            ACTIVITY_IMG: imgList
                        })
                        setFileList(imgList);
                        handleModalVisible(true)
                    }}>编辑</a>
                    <Popconfirm
                        title="确认删除?"
                        onConfirm={async () => {
                            await handleGetDeleteActivity(record.ACTIVITY_ID)
                        }}
                    >
                        <a>删除</a>
                    </Popconfirm>
                </Space>
            }
        }
    ]

    // 删除活动的方法
    const handleGetDeleteActivity = async (activityId: string) => {
        const req: any = {
            ACTIVITYId: activityId
        }
        const data = await handleDeleteACTIVITY(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)

            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <div style={{
                    width: '100%',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 410px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6 }}
                        request={async (params) => {
                            const req: any = {
                                SearchParameter: {
                                    ACTIVITY_ENDDATE_Start: params.ACTIVITY_ENDDATE_Start,
                                    ACTIVITY_STARTDATE_End: params.ACTIVITY_STARTDATE_End,
                                    SERVERPART_IDS: params?.SERVERPART_IDS,
                                    PROVINCE_CODE: "530000",
                                    ACTIVITY_STATES: "1,2"
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                            }
                            setSearchParams(params)
                            const data = await handleGetACTIVITYList(req)
                            console.log('datadatadatadata', data);
                            if (data.List && data.List.length > 0) {
                                return { data: data.List, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [

                                <Button
                                    key="new"
                                    type="primary"
                                    onClick={(e) => {
                                        handleModalVisible(true)
                                    }}
                                >
                                    新增活动
                                </Button>
                            ]
                        }}
                    />
                </div>

                <EventRegistrationDetail parentRow={currentRow} setparentRow={setCurrentRow} onShow={modalVisible} setOnShow={handleModalVisible} currentUser={currentUser} actionRef={actionRef} fileList={fileList} setFileList={setFileList} />
            </div>
        </div >
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(EventRegistration);
