// 商城品牌管理
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, PlusOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, Col, Form, message, Modal, Popconfirm, Row, Space, Spin, Tree, Image, TreeSelect } 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 { handlDeleteBRAND, handleGetBRANDList, handleSynchroBRAND } from "../service";
import session from "@/utils/session";
import Draggable from "react-draggable";
import ProForm, { ProFormDatePicker, ProFormDigit, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import moment from 'moment'
import PageTitleBox from "@/components/PageTitleBox";
import { deletePicture, 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 < 5;
    if (!isLt2M) {
        message.error('图片大小不超过 5MB!');
    }
    return isJpgOrPng && isLt2M;
}

const MallBrandManage: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { confirm } = Modal;
    const { currentUser } = props
    const downloadBtnRef = useRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = 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())

    let BRANDCATEGORYObj = session.get('BRANDCATEGORYObj')
    let BRANDCATEGORYList = session.get('BRANDCATEGORYList')
    let brandObj = session.get('brandObj')
    let brandList = session.get('brandList')

    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 导出的加载效果
    const [showLoading, setShowLoading] = useState<boolean>(false)
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    const [currentRow, setCurrentRow] = useState<any>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [selectBrandList, setSelectBrandList] = useState<any>([])
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    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 columns: any = [
        {
            dataIndex: 'BRAND_INDEX',
            title: '品牌索引',
            width: 120,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'BRAND_NAME',
            title: '品牌名称',
            align: 'center',
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'BRAND_CATEGORY',
            title: '品牌分类',
            width: 120,
            valueType: 'select',
            align: 'center',
            ellipsis: true,
            valueEnum: BRANDCATEGORYObj,
            hideInSearch: true,
            // request: async () => {
            //     return await getFieldEnumTree({ FieldExplainField: 'BRAND_CATEGORY', sessionName: 'BRAND_CATEGORY' });
            // },
            // render: (_, record) => {
            //     return <a>
            //         {getFieldEnumName('BRAND_CATEGORY', record?.BRAND_CATEGORY)}
            //     </a>
            // },
        },
        // {
        //     dataIndex: 'BRAND_TYPE',
        //     title: '品牌类型',
        //     valueType: 'select',
        //     align: 'center',
        //     width: 120,
        //     ellipsis: true,
        //     valueEnum: brandObj
        // },
        {
            dataIndex: 'BRAND_STATE',
            title: '有效状态',
            align: 'center',
            width: 120,
            valueType: 'select',
            valueEnum: {
                "-1": "全部",
                "1": "有效",
                "0": "无效"
            },
            initialValue: "1"
        },
        {
            dataIndex: 'BRAND_DESC',
            title: '品牌介绍',
            align: 'center',
            width: 120,
            hideInSearch: true,
            ellipsis: true,
        },

        {
            dataIndex: 'option',
            title: '操作',
            width: 120,
            valueType: 'option',
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space>
                        <a
                            onClick={() => {
                                console.log('recordrecordrecord', record);
                                if (record?.BRAND_INTRO) {
                                    setFileList([{ url: record?.BRAND_INTRO }])
                                }
                                setCurrentRow({ ...record });
                                handleModalVisible(true);
                            }}
                        >
                            编辑
                        </a>
                        <Popconfirm
                            title="确认删除该品牌列表信息吗?"
                            onConfirm={async () => {
                                await handelDelete(record.BRAND_ID);
                            }}>
                            <a>删除</a>
                        </Popconfirm>
                    </Space >
                );
            },
        },
    ];


    const handelDelete = async (id: number) => {
        console.log('fjsdfsdflksa', id);
        const req: any = {
            BRANDId: id
        }
        const result = await handlDeleteBRAND(req)
        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 imgData: string = ''
        if (res.brandImgList && res.brandImgList.length > 0) {
            const formData = new FormData();
            res.brandImgList.forEach((file: any) => {
                formData.append('files[]', file.originFileObj);
                formData.append('ImageName', typeof file !== 'string' ? file?.name : '');
            });
            formData.append('TableId', '111');
            // formData.append('imageType', "1204");
            formData.append('TableType', "1125");

            let imgRes = await uploadPicture(formData)
            console.log('imgResimgResimgResimgRes', imgRes);
            imgData = imgRes.Result_Data.ImageUrl
        }


        let req: any = {}
        if (currentRow?.SELLER_ID) {
            req = {
                ...currentRow,
                ...res,
                BRAND_INTRO: fileList && fileList.length > 0 ? imgData || currentRow?.BRAND_INTRO || "" : "",
                BRAND_CATEGORY: 2000,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            req = {
                ...res,
                BRAND_INTRO: imgData || "",
                BRAND_CATEGORY: 2000,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }

        const data = await handleSynchroBRAND(req)
        handleConfirmLoading(false)
        if (data.Result_Code === 100) {
            message.success("新增成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleModalVisible(false)
            actionRef.current?.reload()
            setFileList([])
        } else {
            message.error(data.Result_Desc)
        }

    };

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

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

            <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
                        }}
                        search={{ span: 6 }}
                        rowKey={(record: any) => {
                            return `${record.BRAND_PID}-${record.BRAND_ID}`
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 410px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        request={async (params) => {
                            setSearchParams(params)
                            const req: any = {
                                searchParameter: {
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    PROVINCE_CODE: currentUser?.ProvinceCode,
                                    BRAND_TYPE: params?.BRAND_TYPE,
                                    BRAND_STATE: params?.BRAND_STATE === '-1' ? '' : params?.BRAND_STATE,
                                    BRAND_CATEGORY: 2000
                                },
                                keyWord: {
                                    key: "BRAND_NAME",
                                    value: params?.BRAND_NAME
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "BRAND_INDEX,OPERATE_DATE"
                            }
                            const data = await handleGetBRANDList(req)
                            console.log('datadatadatadatadata', data);
                            if (data.List && data.List.length > 0) {
                                let brandSelectList: any = []
                                data.List.forEach((item: any) => {
                                    brandSelectList.push({ label: item.BRAND_NAME, value: item.BRAND_ID })
                                })
                                setSelectBrandList(brandSelectList)
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Button
                                    key="new"
                                    icon={<PlusOutlined />}
                                    type="primary"
                                    onClick={() => {
                                        handleModalVisible(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={
                    <div
                        className="brandManager"
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {currentRow ? '更新品牌' : '新建品牌'}
                    </div>
                }
                destroyOnClose={true}
                width={500}
                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)}
                        handle=".brandManager"
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    layout={'horizontal'}
                    formRef={formRef}
                    autoFocusFirstInput
                    submitter={false}
                    preserve={false}
                    initialValues={currentRow ? currentRow : {
                        BRAND_PID: -1, // 默认上级内码为-1
                        BRAND_STATE: 1, // 默认有效状态为1
                    }}
                    onFinish={async (values) => {
                        let newValue: any = { ...values };
                        if (currentRow) {
                            // 编辑数据
                            newValue = { ...values, BRAND_ID: currentRow.BRAND_ID };
                        }


                        console.log('newValuenewValue', newValue);

                        // 如果有开关，要把开关的代码写进去
                        await handleAddUpdate(newValue);
                        handleConfirmLoading(false)
                    }}
                >
                    <Row gutter={8}>
                        <Col span={24}>
                            <ProFormSelect
                                name="BRAND_PID"
                                label="上级内码"
                                request={async () => {
                                    if (selectBrandList && selectBrandList.length > 0) {
                                        let list: any = [{ label: "默认类别", value: -1 }, ...selectBrandList]
                                        return list
                                    } else {
                                        const req: any = {
                                            searchParameter: {
                                                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                                PROVINCE_CODE: currentUser?.ProvinceCode,
                                                BRAND_CATEGORY: 2000
                                            },
                                            PageIndex: 1,
                                            PageSize: 999999,
                                        }
                                        const data = await handleGetBRANDList(req)
                                        if (data.List && data.List.length > 0) {
                                            let brandSelectList: any = []
                                            data.List.forEach((item: any) => {
                                                brandSelectList.push({ label: item.BRAND_NAME, value: item.BRAND_ID })
                                            })
                                            setSelectBrandList(brandSelectList)
                                            brandSelectList.unshirft({ label: "默认类别", value: -1 })
                                            return brandSelectList
                                        } else {
                                            return [{ label: "默认类别", value: -1 }]
                                        }
                                    }
                                }}
                                fieldProps={{
                                    showSearch: true,
                                    filterOption: (input, option) =>
                                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormDigit
                                name="BRAND_INDEX"
                                label="品牌索引"
                                fieldProps={{
                                    precision: 0, // 只允许整数
                                    min: -1,       // 可选：最小值
                                }}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormText
                                name="BRAND_NAME"
                                label="品牌名称"
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormSelect
                                name="BRAND_STATE"
                                label="有效状态"
                                options={[
                                    { label: "有效", value: 1 },
                                    { label: "无效", value: 0 },
                                ]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                label={"品牌图标"}
                                name={"brandImgList"}
                                listType="picture-card"
                                accept="image/*"
                                fieldProps={{
                                    beforeUpload,
                                    onPreview: handlePreview,
                                    fileList: fileList, // 绑定 fileList
                                    onChange: async (info: any) => {
                                        if (info.file.status === 'removed') {
                                            const index = fileList.findIndex(n => n.uid === info.file.uid);
                                            confirm({
                                                title: '确认删除该文件吗？',
                                                icon: <ExclamationCircleOutlined />,
                                                async onOk() {
                                                    if (info.file.ImageId) {
                                                        const deleteLoading = message.loading('正在删除...')
                                                        const success = await deletePicture(info.file?.ImagePath, info.file?.uid, '', '6000')
                                                        deleteLoading()
                                                        if (success) {
                                                            const files = [...fileList]
                                                            files.splice(index, 1)
                                                            setFileList(files)
                                                            message.success("删除成功")
                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }
                                                    } else {
                                                        const files = [...fileList];
                                                        files.splice(index, 1);
                                                        setFileList(files);
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            // 只保留最新上传的那一张图片
                                            let newFileList = info.fileList;
                                            if (newFileList.length > 1) {
                                                newFileList = [newFileList[newFileList.length - 1]];
                                            }
                                            setFileList(newFileList);
                                        }
                                    }
                                }}
                            />
                        </Col>


                        <Col span={24}>
                            <ProFormTextArea
                                name="BRAND_DESC"
                                label="品牌介绍"
                            />
                        </Col>
                    </Row>
                </ProForm>
            </Modal>
        </div>
    )
}

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


