/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2024-09-03 11:09:26
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 服务区门店管理模块
 * @FilePath: \cloud-platform\src\pages\basicManage\ServerpartShop\index.tsx
 */
import ProCard from "@ant-design/pro-card";
import ProDescriptions from "@ant-design/pro-descriptions";
import SubMenu from "antd/lib/menu/SubMenu";
import ProTable from "@ant-design/pro-table";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnum, getFieldEnumTree, getServerpartOption, getServerpartTree } from "@/services/options";
import { MenuFoldOutlined, PlusOutlined } from "@ant-design/icons";
import ProForm, { ModalForm, ProFormDatePicker, ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import { Button, Tree, Col, Row, Drawer, message, Popconfirm, Space, Menu, Avatar, Form, TreeSelect, Modal } from "antd";
import type { ProDescriptionsItemProps } from "@ant-design/pro-descriptions";
import type { ActionType, ProColumns } from "@ant-design/pro-table";
import type { FormInstance } from "antd";
import type { ServerpartShopModel } from './data'

import { useRef, useState } from "react";
import { getList, delServerpartShop, updateServerpartShop, handleSynchroServerpartShop, handleDeleteServerpartShop, handleSynchroRTSERVERPARTSHOP } from "./service";
import './style.less'

import type { ConnectState } from "@/models/connect";
import type { CurrentUser } from "umi";
import { connect } from "umi";
import FormDetail from "./component/formDetail";
import moment from 'moment'
import session from "@/utils/session";
import ShopOperate from "./component/shopOperate";
import LogTable from "./component/logTable";
import Draggable from "react-draggable";
import React from "react";
import BusinessInforForm from "./component/businessInforForm";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";


// 服务区门店组件主体
const ServerpartShopTable: React.FC<{ currentUser: CurrentUser }> = ({ currentUser }) => {
    const actionRef = useRef<ActionType>()
    const formRef = useRef<FormInstance>()
    const updateShopStateModalFormRef = useRef<FormInstance>()
    const BusinessInforFormRef = useRef<any>()
    const ShopOperateRef = useRef<any>()
    const formDetailRef = useRef<any>()
    const [currentRow, setCurrentRow] = useState<ServerpartShopModel | any>()
    const [showDetail, setShowDetail] = useState<boolean>()
    const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中的左侧菜单
    const [modalVisible, handleModalVisible] = useState<boolean>()
    const [serverpartId, setServerpartId] = useState<any>()
    const [collapsible, setCollapsible] = useState<boolean>(false)
    // 同步门店状态的悬浮框
    const [updateShopStateModal, setUpdateShopStateModal] = useState<boolean>(false)
    // 添加经营信息的悬浮框
    const [showAddBusinessModal, setShowAddBusinessModal] = useState<boolean>(false)
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    // 选择的服务区
    const [selectServerPartList, setSelectServerPartList] = useState<any>()
    // 门店更新状态的loading
    const [updateShopStateLoading, setUpdateShopStateLoading] = useState<boolean>()

    const businessStateList = session.get('businessStateList')
    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 { loading: severpartLoading, data: severpartTree = [] } = useRequest(() => { return getServerpartTree(currentUser?.ProvinceCode) })
    const { data: shoptradeTree = [] } = useRequest(async () => {
        return await getFieldEnumTree({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'BUSINESSTYPE' })
    })
    const { data: businessTypeTree = [] } = useRequest(async () => {
        return await getFieldEnumTree({ FieldExplainField: 'BUSINESS_TYPE', sessionName: 'BUSINESS_TYPE' })
    })
    const { data: businessStateTree = [] } = useRequest(async () => {
        return await getFieldEnumTree({ FieldExplainField: 'BUSINESSSTATE', sessionName: 'BUSINESSSTATE' })
    })
    const ServerpartIdsList = session.get('ServerpartIdsList')


    const columns: ProColumns<ServerpartShopModel>[] = [
        {
            dataIndex: 'SHOPNAME',
            title: <div style={{ textAlign: 'center' }}>门店名称</div>,
            width: 200,
            ellipsis: true,
            hideInDescriptions: true,
        },
        {
            dataIndex: 'SERVERPART_NAME',
            title: "服务区",
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true
        },
        {
            dataIndex: 'SHOPREGION',
            title: '所属方位',
            valueType: 'select',
            width: 120,
            align: 'center',
            ellipsis: true,
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'SHOPREGION' })
            },
            hideInSearch: true
        },

        {
            dataIndex: 'SHOPTRADE',
            title: '商品业态',
            hideInSearch: true,
            align: 'center',
            valueType: 'select',
            width: 120,
            ellipsis: true,
            request: async () => {
                return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE', sessionName: 'SHOPTRADE', notformate: true })
            }
        },
        {
            dataIndex: 'BUSINESS_TYPE',
            title: '经营模式',
            width: 120,
            align: 'center',
            ellipsis: true,
            valueType: 'select',
            request: async () => {
                return await getFieldEnumTree({ FieldExplainField: 'BUSINESS_TYPE', sessionName: 'BUSINESS_TYPE' })
            }
        },
        {
            dataIndex: 'BUSINESS_STATE',
            title: '经营状态',
            valueType: 'select',
            width: 120,
            ellipsis: true,
            align: 'center',
            initialValue: "1000",
            valueEnum: {
                "3000": { text: '关闭', status: 'error' },
                "2000": { text: '暂停', status: 'warning' },
                "1000": { text: '运营中', status: 'processing' },
                "1010": { text: '待运营', status: 'default' }
            }
        },
        {
            dataIndex: 'ISVALID',
            title: '有效状态',
            hideInTable: true,
            valueType: 'select',
            valueEnum: {
                "1": '有效',
                "0": "无效"
            },
            initialValue: "1"
        },
        {
            dataIndex: 'STAFF_NAME',
            title: '操作员',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true
        },
        {
            dataIndex: 'option',
            title: '操作',
            width: 120,
            align: 'center',
            valueType: 'option',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space>
                        <a onClick={() => {
                            console.log('record', record);

                            setCurrentRow({ ...record })
                            handleModalVisible(true)

                        }}>编辑</a>

                    </Space>
                )
            }
        }
    ]

    // 保存门店
    const handleGetSaveShop = async () => {
        let req: any = {}

        let formRes: any = formDetailRef.current?.formRef.current?.getFieldsValue()
        // 老的查出的详情
        let oldDetail: any = formDetailRef.current?.formDetailObj
        console.log('formRes', formRes);
        if (currentRow?.SERVERPARTSHOP_ID) {
            // 编辑
            req = {
                ...oldDetail,
                ...formRes,
                BUSINESS_DATE: formRes?.BUSINESS_DATE ? moment(formRes?.BUSINESS_DATE).format('YYYY-MM-DD') : '',
                BUSINESS_ENDDATE: formRes?.BUSINESS_ENDDATE ? moment(formRes?.BUSINESS_ENDDATE).format('YYYY-MM-DD') : '',
                SERVERPART_NAME: formRes?.SERVERPART_ID ? ServerpartIdsList[formRes?.SERVERPART_ID] : '',
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            // 新增
            req = {
                ...formRes,
                BUSINESS_DATE: formRes?.BUSINESS_DATE ? moment(formRes?.BUSINESS_DATE).format('YYYY-MM-DD') : '',
                BUSINESS_ENDDATE: formRes?.BUSINESS_ENDDATE ? moment(formRes?.BUSINESS_ENDDATE).format('YYYY-MM-DD') : '',
                SERVERPART_NAME: formRes?.SERVERPART_ID ? ServerpartIdsList[formRes?.SERVERPART_ID] : '',
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                OWNERUNIT_ID: currentUser?.OwnerUnitId,
                OWNERUNIT_NAME: currentUser?.OwnerUnitName,
                PROVINCE_CODE: currentUser?.ProvinceCode,
            }
        }
        console.log('req', req);
        const data = await handleSynchroServerpartShop(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            handleModalVisible(false);
            setCurrentRow(undefined)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 添加经营信息
    const handleAddBusinessInfo = () => {
        BusinessInforFormRef.current?.formRef.current?.validateFields().then(async () => {
            let res: any = BusinessInforFormRef.current?.formRef.current?.getFieldsValue()
            console.log('res', res);
            const req: any = {
                ...res,
                SERVERPARTSHOP_ID: currentRow?.SERVERPARTSHOP_ID,
                SHOPNAME: currentRow?.SHOPSHORTNAME,
                BUSINESS_DATE: res?.BUSINESS_DATE ? moment(res?.BUSINESS_DATE).format('YYYY-MM-DD') : '',
                BUSINESS_ENDDATE: res?.BUSINESS_ENDDATE ? moment(res?.BUSINESS_ENDDATE).format('YYYY-MM-DD') : '',
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            }
            console.log('req', req);

            const data = await handleSynchroRTSERVERPARTSHOP(req)
            if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                ShopOperateRef.current?.actionRef.current?.reload()
            } else {
                message.error(data.Result_Desc)
            }
            setShowAddBusinessModal(false)
        })
    }

    // 同步门店经营状态
    const handleUpdateShopState = async (value: any) => {
        setUpdateShopStateLoading(true)
        setUpdateShopStateLoading(false)

    }

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectTree setSelectedId={setServerpartId} setCollapsible={setCollapsible} collapsible={collapsible} />
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        rowKey="SERVERPARTSHOP_ID"
                        headerTitle="门店列表"
                        request={async (params) => {
                            if (serverpartId && serverpartId.length > 0) {
                                const data = await getList({
                                    ...params,
                                    SERVERPART_IDS: serverpartId,
                                    current: 1,
                                    pageSize: 999999
                                })
                                return data
                            }
                            return { data: [], success: true }
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 450px)" }}
                        actionRef={actionRef}
                        search={{ span: 6 }}
                        columns={columns}
                        bordered
                        toolbar={{
                            actions: [
                                <Button type="primary" onClick={() => {
                                    if (selectServerPartList && selectServerPartList.length > 0) {
                                        setUpdateShopStateModal(true)
                                    } else {
                                        message.error('请先选择门店！')
                                    }
                                }}>批量更新</Button>,
                                <Button
                                    key="new"
                                    icon={<PlusOutlined />}
                                    type="primary"
                                    onClick={() => {
                                        handleModalVisible(true)
                                    }}
                                >门店</Button>
                            ]
                        }}
                        options={false}
                        rowSelection={{
                            type: 'checkbox',
                            selectedRowKeys: selectServerPartList,
                            preserveSelectedRowKeys: true,
                            onChange: (selectedRowKeys: any, selectedRows: any) => {
                                console.log('selectedRowKeys', selectedRowKeys);
                                setSelectServerPartList(selectedRowKeys)
                            }
                        }}
                    />
                </div>
            </div>

            {/* 同步门店状态的悬浮框 */}
            <Modal
                title="批量同步门店状态"
                width={800}
                bodyStyle={{ padding: 16 }}
                open={updateShopStateModal}
                destroyOnClose={true}
                onCancel={() => {
                    setUpdateShopStateModal(false)
                }}
                confirmLoading={updateShopStateLoading}
                onOk={() => {
                    updateShopStateModalFormRef.current?.validateFields().then((res: any) => {
                        handleUpdateShopState(res)
                    })
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    formRef={updateShopStateModalFormRef}
                    submitter={false}
                >
                    <Row gutter={8}>
                        <Col span={8}>
                            <ProFormSelect
                                label={"经营状态"}
                                name={"BUSINESS_STATE"}
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择经营状态'
                                    }
                                ]}
                                fieldProps={{
                                    options: businessStateList
                                }}
                            />
                        </Col>
                    </Row>
                </ProForm>
            </Modal>

            <Drawer
                width={'80%'}
                visible={modalVisible}
                onClose={() => {
                    handleModalVisible(false);
                    setCurrentRow(undefined)
                }}
                bodyStyle={{ backgroundColor: "#fff", padding: 16 }}
                closable={false}
                destroyOnClose
                footer={<div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div>
                        <Button type="primary" onClick={() => {
                            setShowAddBusinessModal(true)
                        }}>添加经营信息</Button>
                    </div>
                    <div>
                        {
                            currentRow?.SERVERPARTSHOP_ID ?
                                <Popconfirm title="确认删除该门店吗?" onConfirm={async () => {
                                    const data = await handleDeleteServerpartShop({ ServerpartShopId: currentRow?.SERVERPARTSHOP_ID })
                                    if (data.Result_Code === 100) {
                                        message.success(data.Result_Desc)
                                        handleModalVisible(false);
                                        setCurrentRow(undefined)
                                        actionRef.current?.reload()
                                    } else {
                                        message.error(data.Result_Desc)
                                    }
                                }}>
                                    <Button type={"primary"} danger style={{ marginRight: '8px' }}>删除</Button>
                                </Popconfirm> : ''
                        }

                        <Button type={'primary'} onClick={() => {
                            formDetailRef.current?.formRef.current?.validateFields().then((res: any) => {
                                handleGetSaveShop()
                            })
                        }}>保存</Button>
                    </div>
                </div>}
            >
                {/* 表单 */}
                <FormDetail onRef={formDetailRef} currentRow={currentRow} />
                {/* 经营表格 */}
                <ShopOperate currentRow={currentRow} onRef={ShopOperateRef} />
                {/* 日志表 */}
                <LogTable currentRow={currentRow} />
            </Drawer>

            {/* 经营信息 */}
            <Modal
                title="经营信息"
                width={800}
                bodyStyle={{ padding: 16 }}
                open={showAddBusinessModal}
                destroyOnClose={true}
                onCancel={() => {
                    setShowAddBusinessModal(false)
                }}
                onOk={() => {
                    handleAddBusinessInfo()
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <BusinessInforForm onRef={BusinessInforFormRef} currentRow={currentRow} />
            </Modal>
        </div >
    );
}
export default connect(({ user }: ConnectState) => ({
    currentUser: user?.currentUser
}))(ServerpartShopTable);
