/*
 * @Author: cclu 1106109051@qq.com
 * @Date: 2024-09-02 14:20:59
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2024-12-16 10:56:36
 * @FilePath: \cloud-platform\src\pages\newDataAnalysis\panoramaConfig\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import { Button, FormInstance, message, Modal, Popconfirm, Row, Spin } from "antd";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import { handleDeleteSERVERPARTTYPE, handleGetNestingSERVERPARTTYPEList, handleGetServerpartTree, handleGetSERVERPARTTYPEDetail, handleModifyRTServerpartType, handleSynchroSERVERPARTTYPE } from "./service";
import { getFieldEnum } from "@/services/options";
import moment from 'moment'
import Draggable from "react-draggable";
import ProForm, { ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect } from "@ant-design/pro-form";
import RelationService from "./components/relationService";
import data from "../areaVehicle/data";
import './style.less'
import PageTitleBox from "@/components/PageTitleBox";


const panoramaConfig: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const RelationServiceRef = useRef<any>()
    const modalFormRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [searchParams, setSearchParams] = useState<any>()
    // 添加和编辑的modal
    const [showModal, setShowModal] = 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 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 [currentRow, setCurrentRow] = useState<any>()
    // 默认展开的行
    const [defaultExpandRow, setDefaultExpandRow] = useState<string[]>([])
    // 悬浮框的保存loading
    const [modalLoading, setModalLoading] = useState<boolean>(false)
    // 详情的具体数据
    const [formDetail, setFormDetail] = useState<any>()
    // 显示关联服务区
    const [relationService, setRelationService] = useState<boolean>(false)
    // 展开的行
    const [expandedRowKeys, setExpandedRowKeys] = useState<any>([])
    // 表格单行columns的展开行
    const [columnsLoading, setColumnsLoading] = useState<boolean>(false)
    // 表格数据
    const [tableData, setTableData] = useState<any>()

    const columns: any = [
        {
            title: <div style={{ textAlign: 'center' }}>类别名称</div>,
            dataIndex: 'TYPE_NAME',
            ellipsis: true,
            width: 250,
            hideInSearch: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>数据类型</div>,
            dataIndex: 'SERVERPARTSTATICTYPE_ID',
            hideInSearch: true,
            width: 150,
            align: 'center',
            valueType: 'select',
            request: async () => {
                const list = await getFieldEnum({ FieldExplainField: 'SERVERPART_STATISTICSYPE', notformate: true })
                return list
            }
        },
        {
            title: '有效状态',
            dataIndex: 'TYPE_STATE',
            hideInSearch: true,
            width: 120,
            align: 'center',
            valueType: 'select',
            valueEnum: {
                "1": '有效',
                "0": "无效"
            }
        },
        {
            title: '类别顺序',
            width: 120,
            dataIndex: 'TYPE_INDEX',
            align: 'center',
            hideInSearch: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>操作人员</div>,
            dataIndex: 'STAFF_NAME',
            width: 150,
            ellipsis: true,
            hideInSearch: true
        },
        {
            title: '操作时间',
            dataIndex: 'OPERATE_DATE',
            hideInSearch: true,
            align: 'center',
            width: 150,
            render: (_, record) => {
                return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : ''
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>类别说明</div>,
            dataIndex: 'TYPE_DESC',
            hideInSearch: true,
            width: 120,
            ellipsis: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            hideInSearch: true,
            align: 'center',
            width: 120,
            render: (_, record) => {
                return record?.noOption ? '' : <>
                    <a style={{ marginRight: '8px' }} onClick={() => {
                        console.log('record', record);
                        setCurrentRow(record)
                        setShowModal(true)
                    }}>
                        编辑
                    </a>
                    <Popconfirm title={'确认删除？'} onConfirm={async () => {
                        console.log('record', record);
                        const data = await handleDeleteSERVERPARTTYPE({ SERVERPARTTYPEId: record?.SERVERPARTTYPE_ID })
                        if (data.Result_Code === 100) {
                            message.success(data.Result_Desc)
                            handleCancelModal()
                            actionRef.current?.reload()
                        } else {
                            message.error(data.Result_Desc)
                        }
                    }}>
                        <a>
                            删除
                        </a>
                    </Popconfirm>
                </>
            }
        }
    ]

    // 新增和编辑
    const handleAddEdit = async () => {

        let formRes: any = modalFormRef.current?.getFieldsValue()
        console.log('formRes', formRes);



        setModalLoading(true)
        let req: any = {}
        if (currentRow?.SERVERPARTTYPE_ID) {
            // 编辑
            req = {
                ...formDetail,
                ...formRes,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            }
        } else {
            // 新增
            req = {
                SERVERPARTSTATICTYPE_ID: formRes?.SERVERPARTSTATICTYPE_ID,
                TYPE_NAME: formRes?.TYPE_NAME,
                TYPE_STATE: formRes?.TYPE_STATE,
                TYPE_DESC: formRes?.TYPE_DESC,
                ADDTIME: moment().format('YYYY-MM-DD HH:mm:ss'),
                TYPE_PID: formRes?.TYPE_PID,
                TYPE_INDEX: formRes?.TYPE_INDEX,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            }
        }
        const data = await handleSynchroSERVERPARTTYPE(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            handleCancelModal()
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
        setModalLoading(false)
    }

    // 悬浮框的取消事件
    const handleCancelModal = () => {
        setFormDetail(undefined)
        setShowModal(false)
        setModalLoading(false)
        setCurrentRow(undefined)
    }

    // 寻找展开的行 加上加载效果
    const addLoadingRow = (name: string) => {
        const main = document.getElementsByClassName(`panoramaConfigTable`)[0]
        const pageLoading = document.getElementsByClassName(`pageLoading`)[0]

        const row = main.getElementsByClassName(`${name}`)[0]
        const loadingBox = document.createElement('tr');
        const span = document.createElement('span');
        const Spin = pageLoading.cloneNode(true);  // 深克隆DOM节点
        span.innerText = '加载中...';
        Spin.setAttribute('class', 'rowLoadingSpin');
        span.setAttribute('class', 'span');

        loadingBox.appendChild(Spin);
        loadingBox.appendChild(span);
        loadingBox.setAttribute('class', 'loadingBox');
        row.parentNode.insertBefore(loadingBox, row.nextSibling)
    }
    // 寻找展开的行 去除加载效果
    const removeLoadingRow = (name: string) => {
        const main = document.getElementsByClassName(`panoramaConfigTable`)[0]
        const pageLoading = document.getElementsByClassName(`loadingBox`)[0]
        pageLoading.remove() // 防止重复打印一个内容
    }

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

            <Spin style={{ display: 'none' }} className={'pageLoading'} />

            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <div style={{
                    width: '100%',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        rowKey={(record) => {
                            return `${record?.SERVERPARTTYPE_ID}-${record?.ServerpartId}`
                        }}
                        rowClassName={(record) => {
                            return `${record?.SERVERPARTTYPE_ID}-${record?.ServerpartId}`
                        }}
                        className={"panoramaConfigTable"}
                        expandable={{
                            // expandRowByClick: true,
                            defaultExpandAllRows: true,
                            defaultExpandedRowKeys: defaultExpandRow
                        }}
                        headerTitle={<PageTitleBox props={props} />}
                        search={{ span: 6 }}
                        request={async (params) => {
                            const req: any = {
                                PROVINCE_CODE: currentUser?.ProvinceCode,
                                TYPE_STATE: 1
                            }
                            setSearchParams(params)

                            const data = await handleGetNestingSERVERPARTTYPEList(req)
                            console.log('data', data);
                            if (data && data.length > 0) {
                                let list: string[] = []
                                let rowKey: any = []
                                data.forEach((item: any) => {
                                    list.push(item.SERVERPARTTYPE_ID.toString())
                                    rowKey.push(`${item?.SERVERPARTTYPE_ID}-${item?.ServerpartId}`)
                                    if (item.children && item.children.length > 0) {
                                        item.children.forEach((subItem: any) => {
                                            subItem.children = []
                                        })
                                    }

                                })
                                setExpandedRowKeys(rowKey)
                                setDefaultExpandRow(list)
                                setTableData(data)
                                // return { data, success: true }
                            } else {
                                setTableData([])
                                setExpandedRowKeys([])
                                setDefaultExpandRow([])
                            }
                            // return { data: [], success: true }
                        }}
                        dataSource={tableData}
                        toolbar={{
                            actions: [
                                <Button type={"primary"} onClick={() => {
                                    setShowModal(true)
                                }}>添加类型</Button>
                            ]
                        }}
                        expandable={{
                            expandedRowKeys,
                            onExpand: async (record, event) => {
                                console.log('record', record);
                                console.log('event', event);
                                if (record) {
                                    if (expandedRowKeys && expandedRowKeys.length > 0) {
                                        const list: any = JSON.parse(JSON.stringify(expandedRowKeys))
                                        list.push(`${event?.SERVERPARTTYPE_ID}-${event?.ServerpartId}`)
                                        setExpandedRowKeys(list)
                                    } else {
                                        const list: any = []
                                        list.push(`${event?.SERVERPARTTYPE_ID}-${event?.ServerpartId}`)
                                        setExpandedRowKeys(list)
                                    }
                                } else {
                                    const list: any = JSON.parse(JSON.stringify(expandedRowKeys))
                                    const newList: any = list.filter((item) => item !== `${event?.SERVERPARTTYPE_ID}-${event?.ServerpartId}`)
                                    setExpandedRowKeys(newList)

                                }
                                if (columnsLoading) {
                                    return
                                }
                                let isHave: boolean = true
                                if (event.children && event.children.length > 0) {
                                    isHave = false
                                }
                                if (record && event.SERVERPARTTYPE_ID && isHave) {
                                    setColumnsLoading(true)
                                    addLoadingRow(`${event?.SERVERPARTTYPE_ID}-${event?.ServerpartId}`)
                                    const req: any = {
                                        ProvinceCode: currentUser?.ProvinceCode,
                                        SPRegionType_ID: event?.SERVERPARTTYPE_ID
                                    }
                                    const data = await handleGetServerpartTree(req)
                                    let res: any = []
                                    if (data && data.length > 0) {
                                        res = data[0].children
                                        if (res && res.length > 0) {
                                            res.forEach((item: any) => {
                                                item.TYPE_NAME = item.label
                                                item.ServerpartId = item.value
                                                item.noOption = true
                                            })
                                        }
                                    }
                                    if (tableData && tableData.length > 0) {
                                        let oldTable: any = JSON.parse(JSON.stringify(tableData))
                                        oldTable.forEach((item: any) => {
                                            if (item.children && item.children.length > 0) {
                                                item.children.forEach((subItem: any) => {
                                                    if (subItem.SERVERPARTTYPE_ID === event?.SERVERPARTTYPE_ID) {
                                                        subItem.children = res
                                                    }
                                                })
                                            }
                                        })
                                        setTableData(oldTable)
                                    }
                                    removeLoadingRow(`${event?.SERVERPARTTYPE_ID}-${event?.ServerpartId}`)
                                    setColumnsLoading(false)
                                }
                            }
                        }}
                    />
                </div>
            </div>


            <Modal
                title="拆分明细"
                width={500}
                bodyStyle={{ padding: 16 }}
                open={showModal}
                footer={<div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div>
                        {
                            currentRow?.SERVERPARTTYPE_ID ?
                                <Button style={{ marginRight: '8px' }} onClick={() => {
                                    setRelationService(true)
                                }}>关联服务区</Button> : ''
                        }
                    </div>
                    <div>
                        <Button style={{ marginRight: '8px' }} onClick={() => {
                            handleCancelModal()
                        }}>取消</Button>
                        <Button type="primary" onClick={() => {
                            handleAddEdit()
                        }}>保存</Button>
                    </div>
                </div>}
                destroyOnClose={true}
                onOk={() => {
                    handleAddEdit()
                }}
                confirmLoading={modalLoading}
                onCancel={() => {
                    handleCancelModal()
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >

                <ProForm
                    formRef={modalFormRef}
                    submitter={false}
                    request={async () => {
                        if (currentRow?.SERVERPARTTYPE_ID) {
                            const data = await handleGetSERVERPARTTYPEDetail({ SERVERPARTTYPEId: currentRow?.SERVERPARTTYPE_ID })
                            console.log('data', data);
                            setFormDetail(data)
                            let obj: any = {
                                ...data,
                                SERVERPARTSTATICTYPE_ID: data.SERVERPARTSTATICTYPE_ID.toString()
                            }
                            return obj
                        }
                        return {}
                    }}
                >
                    <ProFormTreeSelect
                        label={"上级类别"}
                        name={"TYPE_PID"}
                        request={async () => {
                            const req: any = {
                                PROVINCE_CODE: currentUser?.ProvinceCode,
                                TYPE_STATE: 1
                            }
                            const data = await handleGetNestingSERVERPARTTYPEList(req)
                            data.unshift({ TYPE_NAME: '默认类别', SERVERPARTTYPE_ID: -1 })
                            return data
                        }}
                        fieldProps={{
                            fieldNames: {
                                label: "TYPE_NAME",
                                value: "SERVERPARTTYPE_ID"
                            },
                            treeDefaultExpandAll: true
                        }}
                        rules={[{
                            required: true,
                            message: '请选择上级类别',
                        }]}
                    />

                    <ProFormSelect
                        label={"数据类型"}
                        name={"SERVERPARTSTATICTYPE_ID"}
                        request={async () => {
                            const list = await getFieldEnum({ FieldExplainField: 'SERVERPART_STATISTICSYPE', notformate: true })
                            return list
                        }}
                    />

                    <ProFormText
                        label={"类别名称"}
                        name={"TYPE_NAME"}
                        rules={[{
                            required: true,
                            message: '请输入类别名称',
                        }]}
                    />

                    <ProFormSelect
                        label={"有效状态"}
                        name={"TYPE_STATE"}
                        options={[{ label: '有效', value: 1 }, { label: '无效', value: 0 }]}
                        initialValue={1}
                        rules={[{
                            required: true,
                            message: '请选择有效状态',
                        }]}
                    />

                    <ProFormDigit
                        label={"类别顺序"}
                        name={"TYPE_INDEX"}
                        fieldProps={{
                            addonAfter: false
                        }}
                        rules={[{
                            required: true,
                            message: '请输入类别顺序',
                        }]}
                    />

                    <ProFormTextArea
                        label={"类别说明"}
                        name={"TYPE_DESC"}
                    />
                </ProForm>
            </Modal>

            <Modal
                title="关联服务区"
                width={700}
                bodyStyle={{ padding: 16 }}
                open={relationService}
                destroyOnClose={true}
                onOk={async () => {
                    let res: any = RelationServiceRef.current?.alreadyList
                    console.log('res', res);

                    let list: any = []
                    if (res && res.length > 0) {
                        res.forEach((item: any) => {
                            list.push(item.value)
                        })
                    }

                    const req: any = {
                        ServerpartTypeId: currentRow?.SERVERPARTTYPE_ID,
                        ServerpartId: list.toString()
                    }
                    const data = await handleModifyRTServerpartType(req)
                    if (data.Result_Code === 100) {
                        message.success(data.Result_Desc)
                        setRelationService(false)
                    } else {
                        message.error(data.Result_Desc)
                    }
                }}
                onCancel={() => {
                    setRelationService(false)
                }}
            >
                <RelationService onShow={relationService} currentRow={currentRow} onRef={RelationServiceRef} />
            </Modal>
        </div>
    )
}

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