// 供货商户管理
import { ConnectState } from "@/models/connect";
import { connect, CurrentUser } from "umi";
import LeftSelectMerchantType from './component/LeftSelectMerchantType'
import { useRef, useState } from "react";
import ProTable, { ActionType } from "@ant-design/pro-table";
import PageTitleBox from "@/components/PageTitleBox";
import { Button, Col, FormInstance, message, Modal, Popconfirm, Row, Space } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { handeDeleteMERCHANTS, handeGetMERCHANTSList, handeSynchroMERCHANTS } from "../service";
import Draggable from "react-draggable";
import React from "react";
import ProForm, { ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import moment from 'moment'
import ModalFooter from "../scenicSpotConfig/component/modalFooter";
import { handleSetlogSave } from "@/utils/format";

const SupplierMerchantManage: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const draggleRef = React.createRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    const [collapsible, setCollapsible] = useState<boolean>(false)
    // 拿到左侧树的数据
    const [leftTreeData, setLeftTreeData] = useState<any>()
    const [modalVisible, handleModalVisible] = useState<boolean>();
    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const [currentRow, setCurrentRow] = useState<any>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    // 当前查询的文字
    const [currentSearchText, setCurrentSearchText] = useState<string>('')

    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: "index",
            title: "序号",
            align: 'center',
            hideInSearch: true,
            valueType: "index",
            width: 70,
            ellipsis: true,
        },
        {
            dataIndex: 'MERCHANTSTYPE_NAME',
            title: '商户类型',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            // valueType: "select",
            // valueEnum: leftTreeData
        },
        {
            dataIndex: 'MERCHANTS_NAME',
            title: '商户名称',
            align: 'center',
            hideInSearch: true,
            width: 300,
            ellipsis: true,
            render: (_, record) => {
                return record?.MERCHANTS_NAME ? <a onClick={() => {
                    setCurrentRow({ ...record });
                    handleModalVisible(true);
                }}>
                    {highlightText(record?.MERCHANTS_NAME, currentSearchText)}
                </a> : "-"
            }
        },
        {
            dataIndex: 'MERCHANTS_EN',
            title: '商户简称',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return highlightText(record?.MERCHANTS_EN, currentSearchText)
            }
        },
        {
            dataIndex: 'MERCHANTS_TYPE',
            title: '商户性质',
            align: 'center',
            width: 120,
            ellipsis: true,
            valueEnum: {
                "0": "全部",
                "1000": "企业公司",
                "2000": "个体",
                "3000": "自然人"
            },
            valueType: 'select',
            initialValue: "0"
        },
        {
            dataIndex: 'TAXPAYER_IDENTIFYCODE',
            title: '统一信用代码',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'MERCHANTS_STATE',
            title: '有效状态',
            align: 'center',
            width: 120,
            ellipsis: true,
            valueType: "select",
            fieldProps: {
                options: [
                    { label: '有效', value: "1" },
                    { label: '无效', value: "0" }
                ]
            },
            initialValue: "1"
        },
        {
            dataIndex: 'searchText',
            title: '查询内容',
            align: 'center',
            hideInTable: true,
            width: 120,
            ellipsis: true,
            fieldProps: {
                placeholder: "请输入商户名称/商户ID"
            }
        },
        {
            dataIndex: 'MERCHANTS_TELEPHONE',
            title: '联系电话',
            align: 'center',
            hideInSearch: true,
            width: 120,
            ellipsis: true,
        },
        // {
        //     dataIndex: 'option',
        //     title: '操作',
        //     valueType: 'option',
        //     align: 'center',
        //     hideInSearch: true,
        //     width: 120,
        //     fixed: "right",
        //     ellipsis: true,
        //     render: (_, record) => {
        //         return (
        //             <Space>
        //                 <a
        //                     onClick={() => {
        //                         setCurrentRow({ ...record });
        //                         handleModalVisible(true);
        //                     }}
        //                 >
        //                     编辑
        //                 </a>
        //                 <Popconfirm
        //                     title="确认删除该商品管理列表信息吗?"
        //                     onConfirm={async () => {
        //                         await handelDelete(record.MERCHANTS_ID);
        //                     }}
        //                 >
        //                     <a>删除</a>
        //                 </Popconfirm>
        //             </Space>
        //         );
        //     },
        // },
    ]


    // 给颜色标红的
    const highlightText = (text: string, searchText: string) => {
        if (!text || !searchText) return text;
        const regex = new RegExp(`(${searchText})`, 'gi');
        const parts = text.split(regex);
        return (
            <span>
                {parts.map((part, i) =>
                    part.toLowerCase() === searchText.toLowerCase() ?
                        <span key={i} style={{ color: 'red' }}>{part}</span> :
                        part
                )}
            </span>
        );
    };

    const handelDelete = async (MERCHANTS_ID: number) => {
        const result = await handeDeleteMERCHANTS({ MERCHANTSId: MERCHANTS_ID });

        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            handleSetlogSave(`删除【${currentRow?.MERCHANTS_NAME}】`)
            handleConfirmLoading(false)
            handleModalVisible(false)
            actionRef.current?.reload()
        }
    };

    const handleAddUpdate = async (res: any) => {
        let req: any = {}
        if (currentRow?.MERCHANTS_ID) {
            req = {
                ...currentRow,
                ...res,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                OPERATE_PERSON: currentUser?.ID,
                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            req = {
                ...res,
                MERCHANTS_STATE: 1,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                OPERATE_PERSON: currentUser?.ID,
                OPERATE_TIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }
        const data = await handeSynchroMERCHANTS(req)
        handleConfirmLoading(false)
        if (data.Result_Code === 100) {
            handleSetlogSave(`${currentRow?.MERCHANTS_ID ? '编辑' : '新增'}【${data.Result_Data?.MERCHANTS_NAME}】`)
            message.success("新增成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleModalVisible(false)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    };

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectMerchantType setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} setData={setLeftTreeData} />
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        scroll={{ x: "100%", y: 'calc(100vh - 370px)' }}
                        rowKey={(record) => {
                            return `${record?.COMMODITY_ID}`
                        }}
                        formRef={formRef}
                        bordered
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        actionRef={actionRef}
                        search={{ span: 6, labelWidth: 'auto' }}
                        // 请求数据
                        request={async (params, sorter) => {
                            console.log('selectedId', selectedId);
                            if (!selectedId) {
                                return
                            }
                            const req = {
                                searchParameter: {
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    PROVINCE_CODE: currentUser?.ProvinceCode,
                                    MERCHANTS_TYPE: params?.MERCHANTS_TYPE === '0' ? '' : params?.MERCHANTS_TYPE,
                                    MERCHANTS_AUTOTYPE: selectedId,
                                    MERCHANTS_STATE: params?.MERCHANTS_STATE === '-1' ? '' : params?.MERCHANTS_STATE
                                },
                                keyWord: {
                                    key: "MERCHANTS_NAME,MERCHANTS_EN",
                                    value: params?.searchText || ""
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                            }
                            setCurrentSearchText(params?.searchText || "")
                            const data = await handeGetMERCHANTSList(req);
                            console.log('datadatadatadatadata', data);
                            handleSetlogSave(`点击查询按钮`)
                            if (data.List && data.List.length > 0) {
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        pagination={false}
                        columns={columns}
                        toolbar={{
                            actions: [
                                // 新增按钮
                                <Button
                                    key="new"
                                    icon={<PlusOutlined />}
                                    type="primary"
                                    onClick={() => {
                                        handleModalVisible(true);
                                    }}
                                >
                                    新增商户
                                </Button>
                            ],
                        }}
                    />
                </div>



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

                            onFocus={() => { }}
                            onBlur={() => { }}
                        >
                            {currentRow ? '更新商户信息' : '新建商户信息'}
                        </div>
                    }
                    destroyOnClose={true}
                    width={900}
                    bodyStyle={{
                        height: '700px', // 你可以根据需要调整高度
                        overflowY: 'auto',
                    }}
                    visible={modalVisible}
                    confirmLoading={confirmLoading}
                    afterClose={() => {
                        formRef.current?.resetFields();
                        setCurrentRow(undefined);
                    }}
                    onCancel={() => {
                        handleConfirmLoading(false)
                        handleModalVisible(false)
                    }}
                    footer={<ModalFooter
                        hideDelete={!currentRow?.MERCHANTS_ID}
                        handleDelete={() => {
                            handelDelete(currentRow?.MERCHANTS_ID)
                        }}
                        handleCancel={() => {
                            handleConfirmLoading(false)
                            handleModalVisible(false)
                        }}
                        handleOK={() => {
                            formRef?.current?.validateFields().then(() => {
                                handleConfirmLoading(true)
                                formRef?.current?.submit()
                            })
                        }}
                    />}

                    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=".SupplierMerchantManageModalTitle"
                        >
                            <div ref={draggleRef}>{modal}</div>
                        </Draggable>
                    }}
                >
                    <ProForm
                        layout={'horizontal'}
                        formRef={formRef}
                        autoFocusFirstInput
                        labelCol={{ style: { width: 80 } }}
                        submitter={false}
                        preserve={false}
                        initialValues={currentRow ? {
                            ...currentRow,
                            MERCHANTS_TYPE: Number(currentRow?.MERCHANTS_TYPE)
                        } : {
                            OWNERUNIT_NAME: currentUser?.OwnerUnitName
                        }}
                        onFinish={async (values) => {
                            let newValue: any = { ...values };
                            if (currentRow) {
                                // 编辑数据
                                newValue = { ...values, MERCHANTS_ID: currentRow.MERCHANTS_ID };
                            }
                            // 如果有开关，要把开关的代码写进去
                            await handleAddUpdate(newValue);

                            handleConfirmLoading(false)
                            handleModalVisible(false);
                        }}
                    >
                        <Row gutter={8}>
                            <Col span={8}>
                                <ProFormText
                                    name="OWNERUNIT_NAME"
                                    label="业主单位"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请输入业主单位！"
                                        }
                                    ]}
                                    disabled
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    name="MERCHANTS_AUTOTYPE"
                                    label="商户类型"
                                    request={() => {
                                        let list: any = []

                                        for (let key in leftTreeData) {
                                            list.push({ label: leftTreeData[key], value: key })
                                        }
                                        return list
                                    }}
                                    rules={[
                                        {
                                            required: true,
                                            message: "请选择商户类型！"
                                        }
                                    ]}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    name="MERCHANTS_TYPE"
                                    label="商户性质"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请选择商户性质！"
                                        }
                                    ]}
                                    options={[{ label: "企业公司", value: 1000 }, { label: "个体", value: 2000 }, { label: "自然人", value: 3000 }]}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    name="MERCHANTS_NAME"
                                    label="商户名称"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请输入商户名称！"
                                        }
                                    ]}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    name="MERCHANTS_EN"
                                    label="商户简称"
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    name="TAXPAYER_IDENTIFYCODE"
                                    label="信用代码"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请输入统一信用代码！"
                                        }
                                    ]}
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    name="MERCHANTS_LINKMAN"
                                    label="联系人员"
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormText
                                    name="MERCHANTS_TELEPHONE"
                                    label="手机号码"
                                />
                            </Col>
                            <Col span={8}>
                                <ProFormSelect
                                    name="MERCHANTS_STATE"
                                    label="商户状态"
                                    options={[{ label: "有效", value: 1 }, { label: "无效", value: 0 }]}
                                />
                            </Col>

                            <Col span={24}>
                                <ProFormText
                                    name="MERCHANTS_ADDRESS"
                                    label="商户地址"
                                />
                            </Col>
                            <Col span={24}>
                                <ProFormTextArea
                                    name="MERCHANTS_DESC"
                                    label="商户简介"
                                />
                            </Col>
                        </Row>
                    </ProForm>
                </Modal>


            </div>
        </div>
    )
}

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