// 预约点餐订单  预约订单管理
import { ConnectState } from "@/models/connect";
import { connect, CurrentUser } from "umi";
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, handeGetSALEBILLDetail, handeGetSALEBILLList, handeGetSaleBillWholeList, handeGetSALEDETAILList, 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 session from "@/utils/session";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import './style.less'
import orderIcon from '@/assets/detail/orderIcon.png'
import closeIcon from '@/assets/detail/closeIcon.png'
import OrderDetailModal from "./components/orderDetailModal";
import { handleSetlogSave } from "@/utils/format";


const BookingMealOrder: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const draggleRef = React.createRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalRef = 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) // 弹出框的内容表单是否在提交

    let SALEBILLSTATEObj = session.get('SALEBILLSTATEObj')

    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: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldProps: {
                placeholder: "请输入订单编号"
            }
        },
        {
            title: '查询时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            search: {
                transform: (value) => {
                    return {
                        ORDER_DATE_Start: value[0],
                        ORDER_DATE_End: value[1],
                    };
                },
            },
            fieldProps: {
                ranges: {
                    "本月": [moment().startOf('M'), moment()],
                    "上月": [moment().subtract(1, 'M').startOf('M'), moment().subtract(1, 'M').endOf('M')],
                    "近三月": [moment().subtract(3, 'M').startOf('M'), moment().endOf('M')],
                    "近半年": [moment().subtract(6, 'M').startOf('M'), moment().endOf('M')],
                }
            },
            // initialValue: [moment().add(-1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
            initialValue: [moment().startOf('M'), moment()],
        },
        {
            dataIndex: "index",
            title: "序号",
            align: 'center',
            hideInSearch: true,
            valueType: "index",
            width: 70,
            ellipsis: true,
        },
        {
            dataIndex: 'SALEBILL_CODE',
            title: '订单编号',
            align: 'center',
            hideInSearch: true,
            width: 250,
            ellipsis: true,
            render: (_, record) => {
                return record?.SALEBILL_CODE ? <a onClick={() => {
                    setCurrentRow(record);
                    handleModalVisible(true)
                    handleSetlogSave(`查看编号为【${record?.SALEBILL_CODE}】的订单`)
                }}>{record?.SALEBILL_CODE}</a> : "-"
            }
        },
        {
            dataIndex: 'SERVERPART_NAME',
            title: '服务区',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'SHOPNAME',
            title: '门店名称',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'ORDER_PERSON',
            title: '下单人员',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'SALEBILL_STATE',
            title: '订单状态',
            align: 'center',
            width: 120,
            ellipsis: true,
            valueType: 'select',
            valueEnum: {
                "0": "全部",
                "1005": "订单待支付",
                "1010": "订单待制作",
                "2000": "订单待取餐",
                "3000": "订单已完成",
                "8000": "退款申请中",
                "8900": "订单已退款",
                "9000": "订单已关闭",
                "9999": "订单已撤销",
            },
            initialValue: "0"
        },
        {
            dataIndex: 'ORDER_AMOUNT',
            title: '订单金额',
            align: 'center',
            hideInSearch: true,
            width: 120,
            ellipsis: true,
        },
        {
            dataIndex: 'COUPON_AMOUNT',
            title: '优惠金额',
            align: 'center',
            hideInSearch: true,
            width: 120,
            ellipsis: true,
        },
        {
            dataIndex: 'PAY_AMOUNT',
            title: '实付金额',
            align: 'center',
            hideInSearch: true,
            width: 120,
            ellipsis: true,
        },
        {
            title: "获得积分",
            dataIndex: "MEMBERSHIP_POINT",
            width: 120,
            hideInSearch: true,
            ellipsis: true,
            align: "center",
        },
        {
            title: "获得成长值",
            dataIndex: "MEMBERGROWTH_VALUE",
            width: 120,
            hideInSearch: true,
            ellipsis: true,
            align: "center",
        },
        // {
        //     dataIndex: 'COUPON_SEND_ID',
        //     title: '优惠券名',
        //     align: 'center',
        //     hideInSearch: true,
        //     width: 120,
        //     ellipsis: true,
        // },
        {
            dataIndex: 'ORDER_DATE',
            title: '订单时间',
            align: 'center',
            hideInSearch: true,
            width: 170,
            ellipsis: true,
            render: (_, record) => {
                return record?.ORDER_DATE ? moment(record?.ORDER_DATE).format('YYYY-MM-DD HH:mm:ss') : ''
            }
        },

    ]

    // 订单详情的表格
    const orderDetailColumns: any = [
        {
            dataIndex: "index",
            title: "序号",
            align: 'center',
            hideInSearch: true,
            valueType: "index",
            width: 70,
            ellipsis: true,
        },
        {
            dataIndex: 'COMMODITY_NAME',
            title: '商品名称',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'COMMODITY_BARCODE',
            title: '商品条码',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'ORDER_COUNT',
            title: '数量',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'AVERAGE_PRICE',
            title: '单价',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: 'ORDER_AMOUNT',
            title: '金额',
            align: 'center',
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
    ]

    // 关闭悬浮框
    const handleCloseModal = () => {
        handleConfirmLoading(false)
        handleModalVisible(false)
        setCurrentRow(undefined);
    }

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />
                <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) => {
                            if (!selectedId) {
                                return
                            }
                            const req = {
                                searchParameter: {
                                    SERVERPART_IDS: selectedId,
                                    SALEBILL_TYPES: 6000,
                                    ORDER_DATE_Start: params?.ORDER_DATE_Start || "",
                                    ORDER_DATE_End: params?.ORDER_DATE_End || "",
                                    SALEBILL_STATES: params?.SALEBILL_STATE === "0" ? "1010,2000,3000" : params?.SALEBILL_STATE,
                                    SearchKeyValue: params?.searchText || ""
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: "ORDER_DATE  desc",
                            }
                            const data = await handeGetSaleBillWholeList(req)
                            // const req = {
                            //     searchParameter: {
                            //         ORDER_DATE_Start: params?.ORDER_DATE_Start || "",
                            //         ORDER_DATE_End: params?.ORDER_DATE_End || "",
                            //         SALEBILL_TYPE: 6000,
                            //         OWNERUNIT_ID: currentUser?.OwnerUnitId,
                            //         PROVINCE_CODE: currentUser?.ProvinceCode,
                            //         SALEBILL_STATE: params?.SALEBILL_STATE === "0" ? "" : params?.SALEBILL_STATE
                            //     },
                            //     PageIndex: 1,
                            //     PageSize: 999999,
                            // }
                            // const data = await handeGetSALEBILLList(req);
                            handleSetlogSave(`点击查询按钮`)
                            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: [
                            ],
                        }}
                    />
                </div>

                <OrderDetailModal modalVisible={modalVisible} handleCloseModal={handleCloseModal} currentRow={currentRow} detailType={'food'} />

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

                    //         onFocus={() => { }}
                    //         onBlur={() => { }}
                    //     >
                    //         {'订单详情'}
                    //     </div>
                    // }
                    title={false}
                    closeIcon={<div></div>}
                    destroyOnClose={true}
                    width={1200}
                    visible={modalVisible}
                    confirmLoading={confirmLoading}
                    afterClose={() => {
                        formRef.current?.resetFields();
                        setCurrentRow(undefined);
                    }}
                    onCancel={() => {
                        handleConfirmLoading(false)
                        handleModalVisible(false)
                        setCurrentRow(undefined);
                    }}
                    footer={false}
                    modalRender={(modal) => {
                        return <Draggable
                            disabled={disabled}
                            bounds={bounds}
                            onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                            handle=".bookingOrderModalTop"
                        >
                            <div ref={draggleRef}>{modal}</div>
                        </Draggable>
                    }}
                >
                    <ProForm
                        layout={'horizontal'}
                        formRef={modalRef}
                        submitter={false}
                        initialValues={currentRow ? {
                            ...currentRow,
                            ORDER_DATE: currentRow?.ORDER_DATE ? moment(currentRow?.ORDER_DATE).format('YYYY-MM-DD HH:mm:ss') : ''
                        } : {}}
                    >
                        <div className="bookingOrderModalTop">
                            <div className="modalTopLeft">
                                <img className="memberIcon" src={orderIcon} />
                                <span className="modalTitle">订单详情</span>
                            </div>
                            <div className="modalTopRight">
                                <img className="memberIcon" src={closeIcon} onClick={() => {
                                    handleCloseModal()
                                }} />
                            </div>
                        </div>

                        <div className="bookingOrderModalCenter">
                            <div className="smallTitle">订单信息</div>

                            <Row gutter={8}>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"SALEBILL_CODE"}
                                        label={"订单编码"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormSelect
                                        name={"CHANNEL_TYPE"}
                                        label={"支付渠道"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"ORDER_DATE"}
                                        label={"下单时间"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"RECORD_COUNT"}
                                        label={"商品种类"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"TOTAL_COUNT"}
                                        label={"商品件数"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"ORDER_AMOUNT"}
                                        label={"订单金额"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"COUPON_AMOUNT"}
                                        label={"优惠金额"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"PACK_AMOUNT"}
                                        label={"打包金额"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"CONSUME_SCORE"}
                                        label={"使用积分"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"PAY_AMOUNT"}
                                        label={"实付金额"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormText
                                        name={"COST_AMOUNT"}
                                        label={"成本金额"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormSelect
                                        name={"SALEBILL_STATE"}
                                        label={"订单状态"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                        options={[
                                            { label: "订单待支付", value: 1005 },
                                            { label: "订单待制作", value: 1010 },
                                            { label: "订单待取餐", value: 2000 },
                                            { label: "订单已完成", value: 3000 },
                                            { label: "退款申请中", value: 8000 },
                                            { label: "订单已退款", value: 8900 },
                                            { label: "订单已关闭", value: 9000 },
                                            { label: "订单已撤销", value: 9999 },
                                        ]}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormSelect
                                        name={"COMMENT_STATE"}
                                        label={"订单评价状态"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                        options={[
                                            { label: "未评价", value: 0 },
                                            { label: "已评价", value: 1 },
                                        ]}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormSelect
                                        name={"TAKE_TYPE"}
                                        label={"取餐方式"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                        options={[
                                            { label: "堂食", value: 1000 },
                                            { label: "预约", value: 2000 },
                                        ]}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormSelect
                                        name={"PACK_TYPE"}
                                        label={"就餐方式"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                        options={[
                                            { label: "堂食", value: 1000 },
                                            { label: "打包", value: 2000 },
                                        ]}
                                    />
                                </Col>
                                <Col span={8} className="memberInfoDetailItem">
                                    <ProFormSelect
                                        name={"TAKE_NUMBER"}
                                        label={"取餐码"}
                                        readonly
                                        style={{ marginBottom: '16px' }}
                                    />
                                </Col>
                            </Row>
                        </div>
                    </ProForm>

                    <ProTable
                        columns={orderDetailColumns}
                        bordered
                        search={false}
                        options={false}
                        request={async () => {
                            const req: any = {
                                searchParameter: {
                                    SALEBILL_ID: currentRow?.SALEBILL_ID
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                            }
                            const data = await handeGetSALEDETAILList(req)
                            console.log('datadatadata', data);
                            if (data.List && data.List.length > 0) {
                                return { data: data.List, success: true, total: data.TotalCount }
                            }
                            return { data: [], success: true }
                        }}
                        summary={() => {
                            // extra 是 request 返回的 extra 字段
                            return (
                                <tr>
                                    <td colSpan={2} style={{ textAlign: 'center', fontWeight: 'bold' }}>合计</td>
                                    <td />
                                    <td style={{ textAlign: 'center', fontWeight: 'bold' }}>{currentRow?.TOTAL_COUNT || 0}</td>
                                    <td />
                                    <td style={{ textAlign: 'center', fontWeight: 'bold' }}>{currentRow?.ORDER_AMOUNT?.toFixed(2) || '0.00'}</td>
                                </tr>
                            )
                        }}
                    />

                </Modal> */}
            </div>
        </div>
    )
}

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