// 地址管理 会员地址管理
import React, { useRef, useState, Suspense, useEffect } from 'react';
import moment from 'moment'; // 时间相关引用，没有使用可以删除
import numeral from "numeral"; // 数字相关引用，没有使用可以删除
import { connect } from 'umi';

import useRequest from '@ahooksjs/use-request'; // 请求数据的引用
import Draggable from 'react-draggable';
import SubMenu from "antd/lib/menu/SubMenu";
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm, { ProFormDatePicker, ProFormDateTimePicker, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-form';
import { MenuFoldOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Drawer, message, Row, Popconfirm, Space, Image, Modal, Form, Switch, Upload, Tooltip, Descriptions, TreeSelect } from 'antd';

import type { CurrentUser } from "umi";
import type { ConnectState } from '@/models/connect';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { FormInstance } from 'antd';
import { handeGetMemberAddressCombineList, handleDeleteMEMBERADDRESS, handleGetMEMBERADDRESSList, handleSynchroMEMBERADDRESS } from '../service';
import PageTitleBox from '@/components/PageTitleBox';
import AddressDetail from './components/addressDetail';



const MemberAddress: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const modalActionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<any>();
    const [showDetail, setShowDetail] = useState<boolean>();
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const [searchParams, setSearchParams] = useState<any>();

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()

    const [province, setProvince] = useState<string>('');
    const [city, setCity] = useState<string>('');
    const [county, setCounty] = useState<string>('');
    const [address, setAddress] = useState<string>('');
    // 显示详情抽屉
    const [showDetailDrawer, setShowDetailDrawer] = useState<boolean>(false)
    // 显示当前选中的外层表格数据
    const [currentBigRow, setCurrentBigRow] = useState<any>(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),
        });
    };
    // 拖动结束


    useEffect(() => {
        formRef.current?.setFieldsValue({ ADDRESS: `${province || ''}${city || ''}${county || ''}` })

        // 监听省、市、区/县的变化，拼接收货地址
        // setAddress(`${province || ''}${city || ''}${county || ''}`);

    }, [province, city, county]);

    // 定义列表字段内容
    const columns: any = [
        {
            dataIndex: 'searchText',
            title: '',
            width: 150,
            align: 'center',
            hideInTable: true,
            fieldProps: {
                placeholder: "输入收货人名称/手机号"
            }
        },
        {
            dataIndex: 'USER_NAME',
            title: '收货人名称',
            width: 150,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return record?.USER_NAME ? <a onClick={() => {
                    setCurrentBigRow(record)
                    setShowDetailDrawer(true)
                }}>{record?.USER_NAME}</a> : "-"
            }
        },
        {
            dataIndex: 'USER_SEX',
            title: '收货人性别',
            width: 120,
            align: 'center',
            hideInSearch: true,
            valueType: 'select',
            valueEnum: {
                "1": "男",
                "2": "女",
                "0": "-",
            }
        },
        {
            dataIndex: 'MOBILEPHONE',
            title: '手机号码',
            width: 150,
            align: 'center',
            hideInSearch: true,
        },
        // {
        //     dataIndex: 'RECEIVE_PROVINCE',
        //     title: '省/直辖市',
        //     width: 120,
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'RECEIVE_CITY',
        //     title: '城市/直辖市',
        //     width: 120,
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'RECEIVE_COUNTY',
        //     title: '区/县',
        //     width: 150,
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'ADDRESS',
        //     title: '收货地址',
        //     width: 300,
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'DOORPLATE',
        //     title: '门牌号码',
        //     width: 300,
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'ISDEFAULT',
        //     title: '默认地址',
        //     width: 120,
        //     align: 'center',
        //     hideInSearch: true,
        //     valueType: 'select',
        //     valueEnum: {
        //         "1": "是",
        //         "0": "否",
        //     }
        // },
        // {
        //     dataIndex: 'TAGTYPE',
        //     title: '地址类型',
        //     width: 120,
        //     align: 'center',
        //     hideInSearch: true,
        //     valueType: 'select',
        //     valueEnum: {
        //         "1000": "家",
        //         "2000": "公司",
        //         "3000": "其他",
        //     }
        // },

        // {
        //     dataIndex: 'CREATE_STAFF_NAME',
        //     title: '创建人名称',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'CREATE_DATE',
        //     title: '创建时间',
        //     valueType: 'date',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'UPDATE_STAFF_NAME',
        //     title: '更新人名称',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'UPDATE_DATE',
        //     title: '更新时间',
        //     valueType: 'date',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'MEMBERADDRESS_DESC',
        //     title: '备注说明',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'option',
        //     title: '操作',
        //     width: 120,
        //     align: 'center',
        //     valueType: 'option',
        //     hideInSearch: true,
        //     render: (_, record) => {
        //         return (
        //             <Space>
        //                 <a
        //                     onClick={() => {
        //                         console.log('record', record);

        //                         setProvince(record?.RECEIVE_PROVINCE)
        //                         setCity(record?.RECEIVE_CITY)
        //                         setCounty(record?.RECEIVE_COUNTY)
        //                         setCurrentRow({ ...record });
        //                         handleModalVisible(true);
        //                     }}
        //                 >
        //                     编辑
        //                 </a>
        //                 <Popconfirm
        //                     title="确认删除该会员收货地址列表信息吗?"
        //                     onConfirm={async () => {
        //                         await handelDelete(record.MEMBERADDRESS_ID);
        //                     }}
        //                 >
        //                     <a>删除</a>
        //                 </Popconfirm>
        //             </Space>
        //         );
        //     },
        // },
    ];

    // 抽屉里面的table的columns
    const drawerColumns: any = [
        {
            dataIndex: 'searchText',
            title: '',
            width: 150,
            align: 'center',
            hideInTable: true,
            fieldProps: {
                placeholder: "输入收货人名称"
            }
        },
        {
            dataIndex: 'USER_NAME',
            title: '收货人名称',
            width: 150,
            align: 'center',
            ellipsis: true,
            hideInSearch: true
        },
        {
            dataIndex: 'USER_SEX',
            title: '收货人性别',
            width: 120,
            align: 'center',
            hideInSearch: true,
            valueType: 'select',
            valueEnum: {
                "1": "男",
                "2": "女",
                "0": "-",
            }
        },
        {
            dataIndex: 'MOBILEPHONE',
            title: '手机号码',
            width: 150,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'RECEIVE_PROVINCE',
            title: '省/直辖市',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'RECEIVE_CITY',
            title: '城市/直辖市',
            width: 150,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'RECEIVE_COUNTY',
            title: '区/县',
            width: 150,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'ADDRESS',
            title: '收货地址',
            width: 300,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'DOORPLATE',
            title: '门牌号码',
            width: 300,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'ISDEFAULT',
            title: '默认地址',
            width: 120,
            align: 'center',
            hideInSearch: true,
            ellipsis: true,
            valueType: 'select',
            valueEnum: {
                "1": "是",
                "0": "否",
            }
        },
        {
            dataIndex: 'TAGTYPE',
            title: '地址类型',
            width: 120,
            align: 'center',
            hideInSearch: true,
            ellipsis: true,
            valueType: 'select',
            valueEnum: {
                "1000": "家",
                "2000": "公司",
                "3000": "其他",
            }
        },

        // {
        //     dataIndex: 'CREATE_STAFF_NAME',
        //     title: '创建人名称',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'CREATE_DATE',
        //     title: '创建时间',
        //     valueType: 'date',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'UPDATE_STAFF_NAME',
        //     title: '更新人名称',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'UPDATE_DATE',
        //     title: '更新时间',
        //     valueType: 'date',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        // {
        //     dataIndex: 'MEMBERADDRESS_DESC',
        //     title: '备注说明',
        //     align: 'center',
        //     hideInSearch: true,
        // },
        {
            dataIndex: 'option',
            title: '操作',
            width: 120,
            align: 'center',
            valueType: 'option',
            hideInSearch: true,
            fixed: 'right',
            render: (_, record) => {
                return (
                    <Space>
                        <a
                            onClick={() => {
                                console.log('record', record);

                                setProvince(record?.RECEIVE_PROVINCE)
                                setCity(record?.RECEIVE_CITY)
                                setCounty(record?.RECEIVE_COUNTY)
                                setCurrentRow({ ...record });
                                handleModalVisible(true);
                            }}
                        >
                            编辑
                        </a>
                        <Popconfirm
                            title="确认删除该会员收货地址列表信息吗?"
                            onConfirm={async () => {
                                await handelDelete(record.MEMBERADDRESS_ID);
                            }}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                );
            },
        },
    ];


    const handelDelete = async (id: number) => {
        const result = await handleDeleteMEMBERADDRESS({
            MEMBERADDRESSId: id
        });
        console.log('resultresultresult', result);
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            modalActionRef.current?.reload()
        }
    };

    const handleAddUpdate = async (res: any) => {
        let req: any = {}

        if (currentRow?.MEMBERADDRESS_ID) {
            req = {
                ...currentRow,
                ...res
            }
        } else {
            req = {
                ...res,
                ADDTIME: moment().format('YYYY-MM-DD HH:mm:ss'),
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode
            }
        }
        const data = await handleSynchroMEMBERADDRESS(req);
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            formRef?.current?.resetFields()
            setCurrentRow(undefined)
            handleModalVisible(false)
            modalActionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    };

    return (
        <PageContainer header={{
            title: '',
            breadcrumb: {}
        }}>
            <ProTable
                style={{ height: 'calc(100vh - 135px)', background: '#fff' }}
                scroll={{ y: 'calc(100vh - 410px)' }}
                rowKey={(record) => {
                    return `${record?.MEMBERADDRESS_ID}`
                }}
                formRef={formRef}
                // headerTitle="会员收货地址列表" // 列表表头
                headerTitle={<PageTitleBox props={props} />}
                actionRef={actionRef}
                search={{ span: 6, labelWidth: 'auto' }}
                bordered
                // 请求数据
                request={async (params, sorter) => {
                    console.log('params', params);

                    // const req = {
                    //     SearchParameter: {
                    //         PROVINCE_CODE: currentUser?.ProvinceCode || "",
                    //         OWNERUNIT_ID: 911,
                    //         ISVALID: 1
                    //     },
                    //     PageIndex: params.current,
                    //     PageSize: params.pageSize,
                    //     SortStr: "CREATE_DATE desc",
                    //     keyWord: {
                    //         Key: "USER_NAME",
                    //         Value: params?.searchText
                    //     }
                    // }
                    // const data = await handleGetMEMBERADDRESSList(req);

                    const req = {
                        // PROVINCE_CODE: currentUser?.ProvinceCode || "",
                        OwnerUnitId: currentUser?.OwnerUnitId || "",
                        Isvalid: 1,
                        PageIndex: params.current,
                        PageSize: params?.pageSize,
                        SortStr: "CREATE_DATE desc",
                        SearchKeyName: "MEMBERSHIP_NAME,MEMBERSHIP_MOBILEPHONE",
                        SearchKeyValue: params?.searchText || ""
                    }

                    console.log('reqreqreqreqreqreqreq', req);
                    const data = await handeGetMemberAddressCombineList(req)
                    console.log('datadatadatadatadata', data);
                    if (data.List && data.List.length > 0) {
                        return { data: data.List, success: true, total: data.TotalCount }
                    }
                    return { data: [], success: true }
                }}
                columns={columns}
                toolbar={{
                    actions: []
                }}
                pagination={{
                    defaultPageSize: 20,
                    showTotal: (total) => `共 ${total} 条记录`
                }}
            />

            {/* 这里和 会员详情里面的同步 如果有什么修改 记得一起改 */}
            <Drawer
                width={'80%'}
                visible={showDetailDrawer}
                onClose={() => {
                    setCurrentBigRow(undefined);
                    setShowDetailDrawer(false);
                }}
                closable={false}
                destroyOnClose
            >
                <AddressDetail currentBigRow={currentBigRow} currentUser={currentUser} />
                {/* <ProTable
                    search={false}
                    pagination={false}
                    options={false}
                    scroll={{ x: "100%", y: '500px' }}
                    columns={drawerColumns}
                    headerTitle={"用户地址"}
                    actionRef={modalActionRef}
                    bordered
                    request={async (params, sorter) => {
                        const req = {
                            SearchParameter: {
                                MEMBERSHIP_ID: currentBigRow?.MEMBERSHIP_ID,
                                PROVINCE_CODE: currentUser?.ProvinceCode || "",
                                OWNERUNIT_ID: 911,
                                ISVALID: 1
                            },
                            PageIndex: params.current,
                            PageSize: params.pageSize,
                            SortStr: "CREATE_DATE desc",
                            keyWord: {
                                Key: "USER_NAME",
                                Value: params?.searchText
                            }
                        }
                        const data = await handleGetMEMBERADDRESSList(req);
                        console.log('datadatadatadatadata', data);
                        if (data.List && data.List.length > 0) {
                            return { data: data.List, success: true, total: data.TotalCount }
                        }
                        return { data: [], success: true }
                    }}
                /> */}
            </Drawer>

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

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {currentRow ? '更新会员收货地址' : '新建会员收货地址'}
                    </div>
                }
                destroyOnClose={true}
                width={900}
                visible={modalVisible}
                confirmLoading={confirmLoading}
                afterClose={() => {
                    formRef.current?.resetFields();
                    setCurrentRow(undefined);
                }}
                onCancel={() => {
                    handleConfirmLoading(false)
                    handleModalVisible(false)
                    setProvince("")
                    setCity("")
                    setCounty("")
                }}

                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=".modal-drag-title"
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    layout={'horizontal'}
                    labelCol={{ style: { width: '80px' } }}
                    formRef={formRef}
                    autoFocusFirstInput
                    submitter={false}
                    preserve={false}
                    initialValues={currentRow}
                    onFinish={async (values) => {
                        let newValue: any = { ...values };
                        if (currentRow) {
                            // 编辑数据
                            newValue = { ...values, MEMBERADDRESS_ID: currentRow.MEMBERADDRESS_ID };
                        }
                        await handleAddUpdate(newValue);

                        handleConfirmLoading(false)
                    }}
                >
                    <Row gutter={8}>
                        <Col span={12}>
                            <ProFormText
                                name="USER_NAME"
                                label="收货人名称"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="USER_SEX"
                                label="收货人性别"
                                options={[
                                    { label: "男", value: 1 },
                                    { label: "女", value: 2 },
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="MOBILEPHONE"
                                label="手机号码"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="RECEIVE_PROVINCE"
                                label="省"
                                fieldProps={{
                                    onChange: (e: any) => {
                                        console.log('eee', e);

                                        setProvince(e.target.value)
                                    }
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="RECEIVE_CITY"
                                label="市"
                                fieldProps={{
                                    onChange: (e: any) => {
                                        setCity(e.target.value)
                                    }
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="RECEIVE_COUNTY"
                                label="区/县"
                                fieldProps={{
                                    onChange: (e: any) => {
                                        setCounty(e.target.value)
                                    }
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="ADDRESS"
                                label="收货地址"
                                disabled
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="DOORPLATE"
                                label="门牌号码"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="ISDEFAULT"
                                label="默认地址"
                                options={[
                                    { label: "是", value: 1 },
                                    { label: "否", value: 0 },
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="TAGTYPE"
                                label="地址类型"
                                options={[
                                    { label: "家", value: 1000 },
                                    { label: "公司", value: 2000 },
                                    { label: "其他", value: 3000 },
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="ISVALID"
                                label="是否有效"
                                options={[
                                    { label: "是", value: 1 },
                                    { label: "否", value: 0 },
                                ]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name="MEMBERADDRESS_DESC"
                                label="备注说明"
                            />
                        </Col>
                    </Row>
                </ProForm>
            </Modal>
        </PageContainer>
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(MemberAddress);
