import { connect, useRequest } 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 { Popconfirm, Space, Tree, Image, Modal, Divider, Row, Col, message, Button } from "antd";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import PageTitleBox from "@/components/PageTitleBox";
import { getFieldEnumTreeNoSession, handleGetFIELDENUMList } from "@/services/options";
import { handeGetPictureList } from "../service";
import { hanleDeletePICTURE, hanleGetPictureListPost, hanleSaveImgFile, hanleSynchroPICTURE, uploadAHYDPicture } from "@/services/picture";
import ModalFooter from "../scenicSpotConfig/component/modalFooter";
import ProForm, { ProFormSelect, ProFormText, ProFormUploadButton } from "@ant-design/pro-form";
import moment from 'moment'

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 LibraryInformationManager: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    // 左侧树的枚举
    const [treeViewObj, setTreeViewObj] = useState<any>()
    // 拿到headerTitle
    const { loading: imageLibraryLoading, data: imageLibrary } = useRequest(async () => {
        const req: any = {
            SearchParameter: {
                FIELDENUM_IDS: "11462,11423,11422,11473,11472",
            },
            requestEncryption: true
        }
        const data = await handleGetFIELDENUMList(req)
        setTreeView(data)
        let obj: any = {}
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                obj[item.FIELDENUM_ID] = item.FIELDENUM_NAME
            })
        }
        setTreeViewObj(obj)
        return data
    })
    // 图片信息
    const [fileList, setFileList] = useState<any>()
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    const handleChangePreview = (val: any) => {
        setImagePreviewVisible(val)
    }
    // 详情
    const [showDetail, setShowDetail] = useState<boolean>(false)
    const [currentRow, setCurrentRow] = useState<any>()
    const [modalLoading, setModalLoading] = useState<boolean>(false)
    const ModalFormRef = useRef<FormInstance>();

    const columns: any = [
        {
            dataIndex: "PICTURE_URL",
            hideInSearch: true,
            width: 200,
            align: 'center',
            ellipsis: true,
            render: (_, record) => {
                return record?.PICTURE_URL ? <img style={{ width: '50px', height: '50px', borderRadius: '50%', cursor: 'pointer' }} onClick={() => {
                    let list: any = [{ url: record?.PICTURE_URL }]
                    setFileList(list)
                    handleChangePreview(true)
                }} src={record?.PICTURE_URL} alt="" /> : "-"
            }
        },
        {
            dataIndex: 'PICTURE_NAME',
            title: '图片名称',
            width: 200,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.PICTURE_NAME ? <a onClick={() => {
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>
                    {`${record?.PICTURE_NAME ? record?.PICTURE_NAME : ""}${record?.PICTURE_TYPE && treeViewObj[record?.PICTURE_TYPE] ? `【${treeViewObj[record?.PICTURE_TYPE]}】` : ""}`}
                </a> : ""
            }
        },
        {
            dataIndex: 'STAFF_NAME',
            title: '操作人',
            width: 200,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '操作时间',
            width: 200,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     dataIndex: 'option',
        //     title: '操作',
        //     width: 150,
        //     align: 'center',
        //     valueType: 'option',
        //     hideInSearch: true,
        //     render: (_, record) => {
        //         return (
        //             <Space>
        //                 <a
        //                     onClick={() => {
        //                         setCurrentRow(record)
        //                         setShowDetail(true)
        //                     }}
        //                 >
        //                     编辑
        //                 </a>
        //                 <Popconfirm
        //                     title="确认删除该图片吗?"
        //                     onConfirm={async () => {
        //                         await handleDeleteImg(record?.PICTURE_ID)
        //                     }}
        //                 >
        //                     <a>删除</a>
        //                 </Popconfirm>
        //             </Space>
        //         );
        //     },
        // },
    ]

    // 同步图片信息
    const handleSynchroImage = async (obj: any) => {
        let req: any = {}
        if (currentRow?.PICTURE_ID) {
            req = {
                ...currentRow,
                ...obj,
                requestEncryption: true
            }
        } else {
            req = {
                ...obj,
                PICTURE_URL: fileList[0].url,
                PICTURE_INDEX: 0,
                STAFF_ID: currentUser.ID,
                STAFF_NAME: currentUser.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                requestEncryption: true
            }
        }
        const data = await hanleSynchroPICTURE(req)
        console.log('datadatadatadatadata', data);
        if (data.Result_Code === 100) {
            message.success('同步成功！')
            setCurrentRow(null)
            setShowDetail(false)

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

    // 删除图片信息
    const handleDeleteImg = async (id: any) => {
        const req: any = {
            PICTUREId: id,
            requestEncryption: true
        }
        const data = await hanleDeletePICTURE(req)
        if (data.Result_Code === 100) {
            message.success('同步成功！')
            setCurrentRow(null)
            setShowDetail(false)

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


    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <ProCard
                    style={{ width: !collapsible ? "300px" : "60px" }}
                    className="pageTable-leftnav"
                    bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
                    extra={
                        <MenuFoldOutlined onClick={() => {
                            setCollapsible(!collapsible);
                        }} />
                    }
                    colSpan={!collapsible ? "300px" : "60px"}
                    title={!collapsible ? "请选择图库类型" : ""}
                    headerBordered
                    collapsed={collapsible}
                >
                    {treeView && treeView.length > 0 ? <Tree
                        checkable
                        treeData={[{
                            FIELDENUM_NAME: '全部',
                            FIELDENUM_ID: 0,
                            key: '0-0',
                            children: treeView
                        }]}
                        blockNode
                        defaultExpandedKeys={['0-0']}
                        defaultExpandAll={true}
                        onCheck={(checkedKeys: React.Key[] | any, info) => {
                            // 多选逻辑
                            const selectedIds = info.checkedNodes.filter((n: any) => n?.key !== '0-0')
                            setSelectedId(selectedIds.map((n: any) => n?.FIELDENUM_ID)?.toString() || '')
                        }}
                        fieldNames={{
                            title: "FIELDENUM_NAME",
                            key: "FIELDENUM_ID"
                        }}
                    /> : ''}
                </ProCard>
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 420px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6 }}
                        request={async (params) => {
                            if (!selectedId) {
                                return
                            }
                            const req: any = {
                                SearchParameter: {
                                    PICTURE_TYPES: selectedId,
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                requestEncryption: true
                            }

                            setSearchParams(params)
                            const data = await hanleGetPictureListPost(req)
                            if (data && data.length > 0) {
                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Button type={'primary'} onClick={() => {
                                    setShowDetail(true)
                                }}>添加图片</Button>
                            ]
                        }}
                    />
                </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
                    open={showDetail}
                    onCancel={() => {
                        ModalFormRef?.current?.resetFields()
                        setCurrentRow(null)
                        setShowDetail(false)
                        setFileList([])
                    }}
                    confirmLoading={modalLoading}
                    width={1400}
                    bodyStyle={{
                        height: '700px', // 你可以根据需要调整高度
                        overflowY: 'auto',
                    }}
                    destroyOnClose
                    title={currentRow?.PICTURE_ID ? '编辑图片' : "新增卡券"}
                    onOk={() => {
                        ModalFormRef?.current?.validateFields().then(async (res) => {
                            await handleSynchroImage(res)
                        })
                    }}
                    footer={<ModalFooter
                        hideDelete={!currentRow?.PICTURE_ID}
                        handleDelete={async () => {
                            // await handleDeleteShopRule(currentRow?.PICTURE_ID)
                            await handleDeleteImg(currentRow?.PICTURE_ID)
                        }}
                        handleCancel={() => {
                            ModalFormRef?.current?.resetFields()
                            setCurrentRow(null)
                            setShowDetail(false)
                            setFileList([])
                        }}
                        handleOK={() => {
                            ModalFormRef?.current?.validateFields().then(async (res) => {
                                await handleSynchroImage(res)
                            })
                        }}

                    />}
                >
                    <ProForm
                        formRef={ModalFormRef}
                        layout={'horizontal'}
                        submitter={false}
                        labelCol={{ style: { width: 80 } }}
                        request={async () => {
                            if (currentRow?.PICTURE_ID) {
                                return {
                                    ...currentRow
                                }
                            } else {
                                return {
                                    STAFF_NAME: currentUser.Name,
                                    OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
                                }
                            }
                        }}
                    >

                        {
                            currentRow ? '' :
                                <>
                                    <Divider orientation="left">上传图片</Divider>
                                    <ProFormUploadButton
                                        name="PICTURE_URL"
                                        label="上传图片"
                                        fileList={fileList}
                                        listType="picture-card"
                                        accept="image/*"
                                        fieldProps={{
                                            beforeUpload,
                                            maxCount: 1,
                                            onPreview: handleChangePreview,
                                            customRequest: async (info) => {
                                                const formData = new FormData();
                                                formData.append('files', info.file);
                                                formData.append('TableType', "1203");
                                                formData.append('ImageName', typeof info.file !== 'string' ? info.file?.name : '');
                                                if (info.filename) {
                                                    const success = await hanleSaveImgFile(formData)

                                                    console.log('successsuccesssuccess', success);

                                                    if (success) {
                                                        const list = [{
                                                            uid: `${success.Result_Data.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("您上传的图片不存在.")
                                                }
                                            }
                                        }}
                                    />
                                </>
                        }

                        <Divider orientation="left">基本信息</Divider>
                        <Row gutter={8}>
                            <Col span={8}>
                                <ProFormSelect
                                    label={"图片类型"}
                                    name={"PICTURE_TYPE"}
                                    options={treeView}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请选择图片类型'
                                        }
                                    ]}
                                    fieldProps={{
                                        fieldNames: {
                                            label: "FIELDENUM_NAME",
                                            value: "FIELDENUM_ID"
                                        }
                                    }}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"图片名称"}
                                    name={"PICTURE_NAME"}
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入图片名称'
                                        }
                                    ]}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"操作人"}
                                    name={"STAFF_NAME"}
                                    disabled
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    label={"操作时间"}
                                    name={"OPERATE_DATE"}
                                    disabled
                                />
                            </Col>
                        </Row>
                    </ProForm>
                </Modal>

            </div>
        </div >
    )
}

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