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 { ExclamationCircleOutlined, MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Col, Modal, Row, Image } from "antd";
import { Button, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnumTree, 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 { handleDeleteNOTICEINFO, handleGetNOTICEINFOList, handleSynchroNOTICEINFO } from "./service";
import moment from 'moment'
import ProForm, { ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect, ProFormUploadButton } from "@ant-design/pro-form";
import { deletePicture, uploadAHYDPicture, uploadPicture } from "@/services/picture";
import { handleGetPictureList } from "@/pages/reports/settlementAccount/service";
import { truncate } from "lodash";
import Popconfirm from "antd/es/popconfirm";
import { handleGetServerpartTree } from "../serverpartAssets/service";


const highwayHeadlines: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const { confirm } = Modal;
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())


    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    // 头条类型 对象格式
    const [NOTICEINFO_TYPES, setNOTICEINFO_TYPESOBJ] = useState<any>()
    const [NOTICEINFO_TYPESList, setNOTICEINFO_TYPESList] = useState<any>()
    // 显示新增窗口
    const [showAddModal, setShowAddModal] = useState<boolean>(false)
    // 弹出框的确认效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
    // 当前选中行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 图片列表
    const [fileList, setFileList] = useState<any>()

    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 预览上传后的图片
    const handlePreview = async () => {
        setFileList(fileList)
        setImagePreviewVisible(true)
    };

    const handleChangePreview = (val: any) => {
        setImagePreviewVisible(val)
    }

    const columns: any = [
        {
            title: '统计时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            initialValue: [moment().subtract(1, 'month'), moment()],
            search: {
                transform: (value: any) => {
                    return {
                        StartDate: value[0],
                        EndDate: value[1],
                    };
                },
            },
        },
        {
            title: <div style={{ textAlign: 'center' }}>头条类型</div>,
            dataIndex: 'NOTICEINFO_TYPES',
            valueType: 'treeSelect',
            align: 'center',
            width: 150,
            ellipsis: true,
            request: async () => {
                const list = await getFieldEnumTree({ FieldExplainField: 'NOTICEINFO_TYPE' })
                console.log('list2222', list);
                setNOTICEINFO_TYPESList(list)
                const obj: any = []
                if (list && list.length > 0) {
                    list.forEach((item: any) => {
                        item.disabled = true
                        if (item.children && item.children.length > 0) {
                            item.children.forEach((subItem: any) => {
                                obj[subItem.value] = subItem.label
                            })
                        }
                    })
                }
                console.log('obj', obj);

                setNOTICEINFO_TYPESOBJ(obj)
                return list
            },
            fieldProps: {
                treeDefaultExpandAll: true,
                allowClear: true,
            },
            render: (_, record) => {
                return record?.NOTICEINFO_TYPE && NOTICEINFO_TYPES ? NOTICEINFO_TYPES[record?.NOTICEINFO_TYPE] : '-'
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>标题</div>,
            dataIndex: "NOTICEINFO_TITLE",
            hideInSearch: true,
            width: 250,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>内容</div>,
            dataIndex: "NOTICEINFO_CONTENT",
            hideInSearch: true,
            width: 350,
            ellipsis: true,
        },
        // {
        //     title: '下发时间',
        //     dataIndex: "ISSUED_DATE",
        //     hideInSearch: true,
        //     width: 150,
        //     align: 'center',
        //     ellipsis: true,
        //     render: (_, record) => {
        //         return record?.ISSUED_DATE ? moment(record?.ISSUED_DATE).format('YYYY-MM-DD HH:mm:ss') : "-"
        //     }
        // },
        // {
        //     title: '图片列表',
        //     dataIndex: "ImageList",
        //     hideInSearch: true,
        //     width: 120,
        //     align: 'center',
        //     ellipsis: true
        // },
        {
            title: '操作人员',
            dataIndex: "STAFF_NAME",
            hideInSearch: true,
            width: 150,
            align: 'center',
            ellipsis: true
        },
        {
            title: '备注说明',
            dataIndex: "NOTICEINFO_DESC",
            hideInSearch: true,
            width: 200,
            align: 'center',
            ellipsis: true
        },
        {
            title: '操作',
            dataIndex: "options",
            hideInSearch: true,
            width: 120,
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                return <div>
                    <a onClick={() => {
                        setCurrentRow(record)
                        setShowAddModal(true)
                    }}>
                        编辑
                    </a>
                    <Popconfirm
                        title={'确认删除？'}
                        onConfirm={() => {
                            handleDeleteLine(record?.NOTICEINFO_ID)
                        }}
                    >
                        <a style={{ marginLeft: '8px' }}>删除</a>
                    </Popconfirm>

                </div>
            }
        }
    ]

    // 新增头条
    const handleAddHeadlines = async (obj: any) => {
        console.log('obj', obj);

        let req: any = {}
        if (currentRow?.NOTICEINFO_ID) {
            req = {
                ...currentRow,
                NOTICEINFO_TYPE: obj.NOTICEINFO_TYPE,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                NOTICEINFO_TITLE: obj.NOTICEINFO_TITLE,
                NOTICEINFO_CONTENT: obj.NOTICEINFO_CONTENT,
                START_DATE: obj.START_DATE ? moment(obj.START_DATE._d).format('YYYY-MM-DD HH:mm:ss') : '',
                END_DATE: obj.END_DATE ? moment(obj.END_DATE._d).format('YYYY-MM-DD HH:mm:ss') : '',
                NOTICEINFO_DESC: obj.NOTICEINFO_DESC,
                NOTICEINFO_STATE: 1,
                SERVERPART_ID: obj.SERVERPART_ID
            }
        } else {
            req = {
                NOTICEINFO_TYPE: obj.NOTICEINFO_TYPE,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                NOTICEINFO_TITLE: obj.NOTICEINFO_TITLE,
                NOTICEINFO_CONTENT: obj.NOTICEINFO_CONTENT,
                START_DATE: obj.START_DATE ? moment(obj.START_DATE._d).format('YYYY-MM-DD HH:mm:ss') : '',
                END_DATE: obj.END_DATE ? moment(obj.END_DATE._d).format('YYYY-MM-DD HH:mm:ss') : '',
                NOTICEINFO_DESC: obj.NOTICEINFO_DESC,
                NOTICEINFO_STATE: 1,
                SERVERPART_ID: obj.SERVERPART_ID
            }
        }

        console.log('req', req);
        const data = await handleSynchroNOTICEINFO(req)
        console.log('fileList', fileList);
        if (fileList && fileList.length > 0) {
            const formData = new FormData();
            fileList.forEach((item: any) => {
                formData.append('files[]', item.originFileObj);
                formData.append('ImageName', item.name);
            })
            formData.append('TableType', '1401');
            formData.append('TableId', data.Result_Data.NOTICEINFO_ID.toString());
            const success = await uploadPicture(formData)
            // const success = await uploadAHYDPicture(formData)
            console.log('success', success);
        }
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            handleModalClose()
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
            setConfirmLoading(false)
        }
    }

    // 悬浮框的关闭事件
    const handleModalClose = () => {
        setConfirmLoading(false)
        setCurrentRow(undefined)
        setFileList([])
        setShowAddModal(false)

    }

    // 删除头条
    const handleDeleteLine = async (id: any) => {
        const data = await handleDeleteNOTICEINFO({ NOTICEINFOId: id })
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }


    return (
        <div ref={(el) => {
            // 打印报表
            if (!reqDetailList || reqDetailList.length === 0) return;
            setPrintOut(el);
        }} >

            <div className={`saleReportHideBox${printIndex}`} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
                {
                    showExportTable && reqDetailList && reqDetailList.length > 0 ?
                        <ProTable
                            columns={columns}
                            dataSource={reqDetailList}
                            pagination={false}
                            expandable={{
                                defaultExpandAllRows: true
                            }}
                        /> : ''
                }
            </div>
            <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />

            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                {/* <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} /> */}
                <div style={{
                    width: '100%',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        headerTitle={<PageTitleBox props={props} />}
                        search={{ span: 6 }}
                        request={async (params) => {
                            const req: any = {
                                SearchParameter: {
                                    NOTICEINFO_TYPES: params?.NOTICEINFO_TYPES || '',
                                    // SERVERPART_IDS: selectedId || '',
                                    START_DATE_Start: params?.StartDate,
                                    END_DATE_Start: params?.EndDate,
                                    PROVINCE_CODE: currentUser?.ProvinceCode,
                                    NOTICEINFO_STATE: 1
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                            }
                            setSearchParams(params)
                            const data = await handleGetNOTICEINFOList(req)
                            console.log('data', data);

                            if (data && data.length > 0) {
                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Button type="primary" onClick={() => {
                                    setShowAddModal(true)
                                }}>新增头条</Button>
                            ]
                        }}
                    />
                </div>
            </div>

            {/* 图片预览组件 */}
            {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={currentRow ? "编辑头条" : "新增头条"}
                destroyOnClose={true}
                width={900}
                visible={showAddModal}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    handleModalClose()
                }}
                onOk={async () => { // 提交框内的数据
                    modalRef.current?.validateFields().then(async (res: any) => {
                        setConfirmLoading(true)

                        await handleAddHeadlines(res)
                        setConfirmLoading(false)
                    })
                }}
            >
                <ProForm
                    formRef={modalRef}
                    layout={'horizontal'}
                    submitter={false}
                    request={async () => {
                        if (currentRow?.NOTICEINFO_ID) {
                            const imgReq: any = {
                                TableId: currentRow?.NOTICEINFO_ID,
                                TableType: 1401,
                            }
                            const imgData = await handleGetPictureList(imgReq)
                            console.log('imgData', imgData);
                            const imgList: any = imgData.Result_Data.List
                            const realImgList: any = []
                            if (imgList && imgList.length > 0) {
                                imgList.forEach((item: any) => {
                                    realImgList.push({
                                        uid: item.ImageId,
                                        name: item.ImageName,
                                        status: 'done',
                                        url: item.ImageUrl,
                                        imgUrl: item.ImagePath,
                                    })
                                })
                            }
                            setFileList(realImgList)
                            return currentRow
                        }
                        return {}
                    }}
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <ProFormTreeSelect
                                label={'头条类型'}
                                name={'NOTICEINFO_TYPE'}
                                rules={[{
                                    required: true,
                                    message: '请选择头条类型'
                                }]}
                                fieldProps={{
                                    options: NOTICEINFO_TYPESList,
                                    treeDefaultExpandAll: true
                                }}
                            />
                        </Col>

                        <Col span={12}>
                            <ProFormText
                                label={'头条标题'}
                                name={'NOTICEINFO_TITLE'}
                                rules={[{
                                    required: true,
                                    message: '请输入标题内容'
                                }]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                label={'服务区名称'}
                                name={'SERVERPART_ID'}
                                request={async () => {
                                    const req: any = {
                                        ProvinceCode: currentUser?.ProvinceCode,
                                        ServerpartType: 1000,
                                        StatisticsType: 1000,
                                        ShowWholePower: false,
                                        ShowSPRegion: false,
                                        ShowRoyalty: false,
                                        ShowCompactCount: false,
                                    }
                                    const data = await handleGetServerpartTree(req)
                                    // 去除安徽驿达
                                    const list: any = []
                                    if (data && data.length > 0) {
                                        data.forEach((item: any) => {
                                            if (item.value !== 424) {
                                                list.push(item)
                                            }
                                        })
                                    }
                                    return list
                                }}
                            />
                        </Col>

                        <Col span={12}>
                            <ProFormDatePicker
                                label={'生效时间'}
                                name={'START_DATE'}
                                width="lg"
                                rules={[{
                                    required: true,
                                    message: '请选择生效时间'
                                }]}
                                fieldProps={{
                                    format: "YYYY-MM-DD",  // 格式化日期和时间
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDatePicker
                                label={'截止时间'}
                                name={'END_DATE'}
                                width="lg"
                                rules={[{
                                    required: true,
                                    message: '请选择截止时间'
                                }]}
                                fieldProps={{
                                    format: "YYYY-MM-DD",  // 格式化日期和时间
                                }}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                label={'头条内容'}
                                name={'NOTICEINFO_CONTENT'}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                label={'备注说明'}
                                name={'NOTICEINFO_DESC'}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                name="file"
                                label="上传头条图片"
                                labelCol={{ span: 3 }}
                                wrapperCol={{ span: 20 }}
                                fileList={fileList}
                                // rules={[
                                //     {
                                //         required: modalVisible === 3,
                                //         message: '请上传附件！',
                                //     },
                                // ]}
                                fieldProps={{
                                    // beforeUpload: (file, files) => {
                                    //     console.log('file', file);

                                    //     console.log('filesbeforeUpload', files);

                                    //     setFileList([...fileList, ...files])
                                    //     return false
                                    // },
                                    onPreview: handlePreview,
                                    onChange: async (info: any) => {
                                        console.log('info', info);
                                        console.log('fileList', fileList);
                                        if (info.file.status === 'removed') {
                                            const index = fileList.findIndex(n => n.uid === info.file.uid);
                                            confirm({
                                                title: '确认删除该文件吗？',
                                                icon: <ExclamationCircleOutlined />,
                                                async onOk() {
                                                    const deleteLoading = message.loading('正在删除...')
                                                    const success = await deletePicture(info.file?.deletepath, info.file?.uid, '', '5000')
                                                    deleteLoading()

                                                    if (success) {
                                                        const files = [...fileList]
                                                        files.splice(index, 1)
                                                        setFileList(files)
                                                    }
                                                    else {
                                                        message.error("删除失败")
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            setFileList(info.fileList)
                                        }


                                        // if (info.file.status === 'removed') {
                                        //     // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                        //     const index = fileList.findIndex(n => n.uid === info.file.uid);

                                        //     // if (info.file?.status === "removed" && ) {
                                        //     //     const newFileList = fileList.slice();
                                        //     //     newFileList.splice(index, 1);
                                        //     //     setFileList(newFileList)
                                        //     //     return
                                        //     // }
                                        //     confirm({
                                        //         title: '确认删除该文件吗？',
                                        //         icon: <ExclamationCircleOutlined />,
                                        //         async onOk() {
                                        //             const deleteLoading = message.loading('正在删除...')
                                        //             const success = await deletePicture(info.file?.deletepath, info.file?.uid, '', '5000')
                                        //             deleteLoading()

                                        //             if (success) {
                                        //                 const files = [...fileList]
                                        //                 files.splice(index, 1)
                                        //                 setFileList(files)
                                        //             }
                                        //             else {
                                        //                 message.error("删除失败")
                                        //             }
                                        //         },
                                        //         onCancel() {
                                        //         },
                                        //     });
                                        // } else {
                                        // if (currentRow?.SHOPEXPENSE_ID && info.fileList && info.fileList.length > 0) {
                                        //     const formData = new FormData();
                                        //     info.fileList.forEach((item: any) => {
                                        //         if (item.status !== "done") {
                                        //             console.log('item', item);
                                        //             formData.append('files[]', item.originFileObj);
                                        //             formData.append('ImageName', item.name);
                                        //         }
                                        //     })
                                        //     formData.append('TableType', '1401');
                                        //     formData.append('TableId', currentRow?.NOTICEINFO_ID.toString());
                                        //     const success = await uploadPicture(formData)
                                        //     console.log('success', success);
                                        // }
                                        // }
                                    }
                                }}
                            />
                        </Col>
                    </Row>

                </ProForm>
            </Modal>
        </div>
    )
}

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