/*
 * @Author: cclu 1106109051@qq.com
 * @Date: 2024-09-02 11:10:07
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2024-09-29 11:04:15
 * @FilePath: \cloud-platform\src\pages\newDataAnalysis\basicServiceInformation\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 ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import ServerPart from '@/pages/newDataAnalysis/basicInfoService/components/serverpart/Index'
import LoadingBox from "@/pages/reports/Finance/businessAnalysis/components/loading";
import session from "@/utils/session";
import moment from 'moment'
import { handleSynchroSERVERPART } from "../service";


const basicServiceInformation: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const downloadBtnRef = useRef<any>()
    const serverPartRef = useRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())
    // 显示右边的表单
    const [showRightForm, setShowRightForm] = useState<boolean>(true)

    const shopregionObj = session.get('shopregionObj')

    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 加载服务区树
    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)

        let list: any = []
        data.forEach((item: any) => {
            if (item.value !== 424 ) {
                list.push(item)
            }
        })
        setTreeView(list)
        return data
    })

    // 保存方法
    const handleSubmitForm = async () => {
        let res: any = serverPartRef.current?.formRef.current?.getFieldsValue()
        console.log('res', res);
        // 表单查到的详情 更新里面的全部数据
        let detailObj: any = serverPartRef.current?.serverPartDetail


        // 把分区的数据取出来
        let objA: any = {
            SERVERPART_REGION: res?.currentArea,
            SERVERPART_REGIONNAME: res?.currentArea ? shopregionObj[res?.currentArea] : '',

        }
        let objB: any = {
            SERVERPART_REGION: res?.otherArea,
            SERVERPART_REGIONNAME: res?.otherArea ? shopregionObj[res?.otherArea] : ''
        }
        for (let key in res) {
            if (key.indexOf('_A') > 0) {
                let newKey: string = key.split('_A')[0]
                objA[newKey] = res[key]
            } else if (key.indexOf('_B') > 0) {
                let newKey: string = key.split('_B')[0]
                objB[newKey] = res[key]
            }
        }
        // 详情里面本身的服务区数组数据
        let detailServerPartList: any = detailObj?.ServerPartInfo
        if (detailServerPartList && detailServerPartList.length === 2) {
            detailServerPartList.forEach((item: any) => {
                if (Number(item.SERVERPART_REGION) === Number(objA.SERVERPART_REGION)) {
                    objA.SERVERPARTINFO_ID = item.SERVERPARTINFO_ID
                    objA.SERVERPART_ID = selectedId
                    objA.GREENSPACEAREA = item.GREENSPACEAREA
                    objA.SCENICAREA = item.SCENICAREA
                }
                if (Number(item.SERVERPART_REGION) === Number(objB.SERVERPART_REGION)) {
                    objB.SERVERPARTINFO_ID = item.SERVERPARTINFO_ID
                    objB.SERVERPART_ID = selectedId
                    objB.GREENSPACEAREA = item.GREENSPACEAREA
                    objB.SCENICAREA = item.SCENICAREA
                }
            })
        } else {
            if (objB.SERVERPART_REGION) {
                objB.SERVERPART_ID = selectedId
            }
        }


        console.log('objA', objA);
        console.log('objB', objB);
        console.log('detailObj', detailObj);
        const req: any = {
            SERVERPART_ID: detailObj?.SERVERPART_ID,
            SERVERPART_NAME: res?.SERVERPART_NAME,
            SERVERPART_ADDRESS: res?.SERVERPART_ADDRESS,
            SERVERPART_INDEX: res?.SERVERPART_INDEX,
            EXPRESSWAY_NAME: res?.EXPRESSWAY_NAME,
            SELLERCOUNT: detailObj?.SELLERCOUNT,
            SERVERPART_AREA: res?.SERVERPART_AREA,
            SERVERPART_X: res?.SERVERPART_X,
            SERVERPART_Y: res?.SERVERPART_Y,
            SERVERPART_TEL: detailObj?.SERVERPART_TEL,
            SERVERPART_INFO: res?.SERVERPART_INFO,
            PROVINCE_CODE: detailObj?.PROVINCE_CODE,
            SERVERPART_CODE: res?.SERVERPART_CODE,
            SERVERPART_TYPE: res?.SERVERPART_TYPE,
            STARTDATE: res?.STARTDATE,
            OWNEDCOMPANY: res?.OWNEDCOMPANY,
            FLOORAREA: res?.FLOORAREA,
            BUSINESSAREA: detailObj?.BUSINESSAREA,
            SHAREAREA: res?.SHAREAREA,
            MANAGERCOMPANY: res?.MANAGERCOMPANY,
            SPREGIONTYPE_ID: detailObj?.SPREGIONTYPE_ID,
            SPREGIONTYPE_NAME: detailObj?.SPREGIONTYPE_NAME,
            SPREGIONTYPE_INDEX: detailObj?.SPREGIONTYPE_INDEX,
            STATISTICS_TYPE: detailObj?.STATISTICS_TYPE,
            FIELDENUM_ID: detailObj?.FIELDENUM_ID,
            CITY_CODE: detailObj?.CITY_CODE,
            COUNTY_CODE: detailObj?.COUNTY_CODE,
            SERVERPART_IPADDRESS: detailObj?.SERVERPART_IPADDRESS,
            DAYINCAR: detailObj?.DAYINCAR,
            HKBL: detailObj?.HKBL,
            TOTALPARKING: detailObj?.TOTALPARKING,
            SHORTNAME: detailObj?.SHORTNAME,
            REGIONTYPE_ID: detailObj?.REGIONTYPE_ID,
            STATISTIC_TYPE: detailObj?.STATISTIC_TYPE,
            PROVINCE_NAME: detailObj?.PROVINCE_NAME,
            REGIONTYPE_NAME: detailObj?.REGIONTYPE_NAME,
            STAFF_ID: currentUser?.ID,
            STAFF_NAME: currentUser?.Name,
            OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            SERVERPART_DESC: detailObj?.SERVERPART_DESC,
            OWNERUNIT_ID: detailObj?.OWNERUNIT_ID,
            OWNERUNIT_NAME: detailObj?.OWNERUNIT_NAME,
            RtServerPart: {
                RTSERVERPART_ID: detailObj?.RtServerPart?.RTSERVERPART_ID,
                SERVERPART_ID: detailObj?.RtServerPart?.SERVERPART_ID,
                SERVERPART_ADDRESS: res?.SERVERPART_ADDRESS,
                EXPRESSWAY_NAME: res?.EXPRESSWAY_NAME,
                SELLERCOUNT: detailObj?.RtServerPart?.SELLERCOUNT,
                SERVERPART_X: res?.SERVERPART_X,
                SERVERPART_Y: res?.SERVERPART_Y,
                SERVERPART_TEL: detailObj?.RtServerPart?.SERVERPART_TEL,
                STARTDATE: res?.STARTDATE,
                SERVERPART_AREA: res?.SERVERPART_AREA,
                FLOORAREA: res?.FLOORAREA,
                BUSINESSAREA: detailObj?.RtServerPart?.BUSINESSAREA,
                SHAREAREA: res?.SHAREAREA,
                TOTALPARKING: detailObj?.RtServerPart?.TOTALPARKING,
                OWNEDCOMPANY: res?.OWNEDCOMPANY,
                MANAGERCOMPANY: res?.MANAGERCOMPANY,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                SERVERPART_INFO: res?.SERVERPART_INFO,
                CENTERSTAKE_NUM: res?.CENTERSTAKE_NUM,
                TAXPAYER_IDENTIFYCODE: res?.TAXPAYER_IDENTIFYCODE,
                WATERINTAKE_TYPE: res?.WATERINTAKE_TYPE,
                SEWAGEDISPOSAL_TYPE: res?.SEWAGEDISPOSAL_TYPE,
                BUSINESS_REGION: detailObj?.RtServerPart?.BUSINESS_REGION,
            },
            ServerPartInfo: objB.SERVERPART_REGION ? [objA, objB] : [objA]
        }
        console.log('req', req);
        const data = await handleSynchroSERVERPART(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            setShowRightForm(false)
            setTimeout(() => {
                setShowRightForm(true)
            }, 1000)
        } else {
            message.error(data.Result_Desc)
        }
    }


    return (
        <div ref={(el) => {
            // 打印报表
            if (!reqDetailList || reqDetailList.length === 0) return;
            setPrintOut(el);
        }} >
            <div style={{ backgroundColor: '#fff', display: 'flex', justifyContent: 'space-between' }}>
                <ProCard
                    style={{ width: !collapsible ? "300px" : "60px" }}
                    className="pageTable-leftnav"
                    bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}

                    colSpan={!collapsible ? "300px" : "60px"}
                    title={!collapsible ? "请选择服务区" : ""}
                    headerBordered
                    collapsed={collapsible}
                    extra={
                        <MenuFoldOutlined onClick={() => {
                            setCollapsible(!collapsible);
                        }} rev={undefined} />
                    }
                >
                    {treeView && treeView.length > 0 ? <Tree
                        treeData={[{
                            label: '全部',
                            value: 0,
                            key: '0-0',
                            children: treeView
                        }]}
                        fieldNames={{
                            title: "label",
                            key: "key"
                        }}
                        blockNode
                        defaultExpandedKeys={['0-0']}
                        // onCheck={(checkedKeys: React.Key[] | any, info) => {
                        //     const selectedIds = info.checkedNodes.filter((n: any) => n?.type === 1)
                        //     setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
                        // }}
                        onSelect={(selectedKeys: any, info: any) => {
                            setShowRightForm(false)
                            const selectedIds = info.selectedNodes.filter((n: any) => n?.type === 1)
                            console.log('selectedIds', selectedIds);

                            setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
                            console.log('serverPartRef', serverPartRef.current?.formRef);
                            if (selectedIds && selectedIds.length > 0) {
                                setTimeout(() => {
                                    setShowRightForm(true)
                                }, 1000)
                            } else {
                                setTimeout(() => {
                                    setShowRightForm(true)
                                }, 1)
                                serverPartRef.current?.formRef.current?.setFieldsValue({})
                            }

                        }}
                    /> : ''}
                </ProCard>
                <div style={{
                    width: !collapsible ? 'calc(100% - 320px)' : 'calc(100% - 80px)',
                    marginTop: 16,
                    paddingLeft: 16,
                    paddingBottom: 0,
                    paddingRight: 16,
                    height: 'calc(100vh - 200px)',
                    borderLeft: '1px solid #f0f0f0'
                }}>
                    <div style={{ height: 'calc(100% - 60px)', overflowY: 'auto', }}>
                        {
                            showRightForm ?
                                <ServerPart onRef={serverPartRef} currentRow={{ SERVERPART_ID: selectedId ? selectedId : '' }} onShow={showRightForm} /> :
                                <LoadingBox />
                        }
                    </div>
                    <div style={{ height: '60px', width: '100%', display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                        {
                            selectedId ?
                                <Button type="primary" onClick={() => {
                                    handleSubmitForm()
                                }}>保存</Button> : ''
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}

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