// 不动产管理
import { useEffect, useImperativeHandle, useRef, useState } from "react";
import LeftSelectTree from "@/components/leftSelectTree/leftSelectTree";
import { ActionType, FormInstance, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigitRange, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { handleDeleteREALESTATE, handleGetREALESTATEList, handleSynchroREALESTATE } from "./service";
import moment from "moment";
import { encryptAES } from "@/utils/handleAes";
import { Button, Col, message, Modal, Row } from "antd";
import ModalFooter from "./components/modalFooter";
import { handleGetPassportInfoById } from "../DigitalElectronics/service";
// 引入地址解析工具
import { handleAddressChange, parseAddress } from "@/utils/addressParser";
import { handleGetServerpartDDL } from "../serverpartAssets/service";
import { handleGetSERVERPARTDetail } from "../operationReport/service";




const RealEstate = ({ serverPartId, isComponent, onRef, selectRealEstateId }: { serverPartId: string, isComponent: boolean, onRef?: any, selectRealEstateId?: any }) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalFormRef = useRef<FormInstance>();
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    const [collapsible, setCollapsible] = useState<boolean>(false)
    // 添加不动产内容的悬浮框
    const [showDetail, setShowDetail] = useState<boolean>(false)
    // 当前行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 判断是不是第一次进入到页面
    const [isFirst, setIsFirst] = useState<boolean>(true)
    // 获取用户信息
    const [userInfo, setUserInfo] = useState<any>()
    // 拿到服务区列表
    const [serverPartList, setServerPartList] = useState<any>()
    // 悬浮框点击确认的按钮加载效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
    // 选中的行数据详情
    const [selectRowDetail, setSelectRowDetail] = useState<any>()



    // 列表配置
    const columns: any = [
        {
            title: "统计日期",
            dataIndex: "staticDate",
            hideInTable: true,
            valueType: "dateRange",
            initialValue: [moment().startOf('M'), moment()],
            search: {
                transform: (value: any) => {
                    return {
                        START_LEASEDATE_End: moment().startOf('y').format('YYYY-MM-DD'),
                        END_LEASEDATE_Start: moment().format('YYYY-MM-DD')
                    };
                },
            },
            fieldProps: {
                picker: "day",
                format: 'YYYY-MM-DD',
            }
        },
        {
            title: "服务区名称",
            dataIndex: "SERVERPART_NAME",
            hideInSearch: true,
            ellipsis: true,
            width: 180,
            align: 'center'
        },
        {
            title: "不动产类型",
            dataIndex: "REALESTATE_TYPE",
            width: 150,
            valueType: "select",
            align: 'center',
            valueEnum: {
                1000: "房屋租赁",
                2000: "车辆资产",
            }
        },
        {
            title: "产权证号",
            dataIndex: "ESTATE_IDENTITY",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center',
            render: (_, record) => {
                return record?.ESTATE_IDENTITY ? isComponent ? record?.ESTATE_IDENTITY : <a onClick={() => {
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>
                    {record?.ESTATE_IDENTITY}
                </a> : ""
            }
        },
        {
            title: "资料编码",
            dataIndex: "SPECIALINDUSTRY_NUMBER",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center',
            render: (_, record) => {
                return record?.SPECIALINDUSTRY_NUMBER ? isComponent ? record?.ESTATE_IDENTITY : <a onClick={() => {
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>
                    {record?.SPECIALINDUSTRY_NUMBER}
                </a> : ""
            }
        },
        {
            title: "查询内容",
            dataIndex: "searchText",
            hideInTable: true,
            fieldProps: {
                placeholder: "请输入省份名称/城市名称",
            }
        },
        {
            title: "省份名称",
            dataIndex: "PROVINCE_NAME",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center'
        },
        {
            title: "城市名称",
            dataIndex: "CITY_NAME",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center'
        },
        {
            title: "详细地址",
            dataIndex: "REALESTATE_ADDRESS",
            hideInSearch: true,
            ellipsis: true,
            width: 180,
            align: 'center'
        },
        {
            title: "是否跨地",
            dataIndex: "CROSS_CITYSIGN",
            hideInSearch: true,
            ellipsis: true,
            width: 120,
            align: 'center',
            render: (_: any, record: any) => {
                return record?.CROSS_CITYSIGN ? "是" : "否"
            }
        },
        {
            title: "面积单位",
            dataIndex: "AREA_UNIT",
            hideInSearch: true,
            ellipsis: true,
            width: 120,
            align: 'center'
        },
        {
            title: "租赁期限",
            dataIndex: "LEASEDATE",
            hideInSearch: true,
            ellipsis: true,
            width: 250,
            align: 'center',
            render: (_: any, record: any) => {
                return `${record?.START_LEASEDATE || ""}${record?.END_LEASEDATE ? `-${record?.END_LEASEDATE}` : ''}`
            }
        }
    ]

    // 获取当前用户信息的方法 
    const handleGetUserInfo = async () => {
        const search = window.location.search;
        const addressParams: any = Object.fromEntries(new URLSearchParams(search).entries());
        const req: any = {
            UserIdEncrypted: addressParams.UserIdEncrypted
        }
        const data = await handleGetPassportInfoById(req)
        console.log('dsajikajds', data);

        setUserInfo(data)
    }

    // 新增和同步不动产的方法
    const handleAddOrUpdate = async (values: any) => {
        // 准备入参
        let req: any = {}
        console.log('valuesvalues', values);

        let [start, end] = [moment(values?.LEASEDATE[0].$d).format('YYYY-MM-DD HH:mm:ss'), moment(values?.LEASEDATE[1].$d).format('YYYY-MM-DD HH:mm:ss')]

        if (currentRow?.REALESTATE_ID) {
            req = {
                ...currentRow,
                ...values,
                LEASEDATE: "",
                START_LEASEDATE: start || "",
                END_LEASEDATE: end || "",
                REALESTATE_STATE: 1,
                STAFF_ID: userInfo?.ID,
                STAFF_NAME: userInfo?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            }
        } else {
            req = {
                ...values,
                LEASEDATE: "",
                REALESTATE_STATE: 1,
                START_LEASEDATE: start || "",
                END_LEASEDATE: end || "",
                STAFF_ID: userInfo?.ID,
                STAFF_NAME: userInfo?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            }
        }
        console.log('reqreqreqreq', req);

        let reqData: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }
        const data: any = await handleSynchroREALESTATE(reqData)
        setConfirmLoading(false)
        if (data?.Result_Code === 100) {
            message.success('添加成功！');
            setCurrentRow(undefined)
            setShowDetail(false)
            actionRef.current?.reload()
        } else {
            message.error(data?.Result_Desc || '添加失败')
        }
    }

    // 删除不动产
    const handleDeleteOrUpdate = async (id: string) => {
        const req: any = {
            REALESTATEId: id
        }
        let reqData: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }
        const data: any = await handleDeleteREALESTATE(reqData)
        setConfirmLoading(false)
        if (data?.Result_Code === 100) {
            message.success('删除成功！');
            setCurrentRow(undefined)
            setShowDetail(false)
            actionRef.current?.reload()
        } else {
            message.error(data?.Result_Desc || '删除失败')
        }
    }

    useEffect(() => {
        if (isFirst) {
            handleGetUserInfo()
            setIsFirst(false)
        }
    }, [])

    useImperativeHandle(onRef, () => ({
        selectRowDetail
    }));

    return <div style={{ height: isComponent ? '600px' : 'calc(100vh - 100px)', backgroundColor: '#fff', display: 'flex' }}>
        {
            isComponent ? '' :
                <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />
        }

        <div style={{
            width: isComponent ? 'calc(100%)' : !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
            paddingTop: 0,
            paddingBottom: 0,
            paddingRight: 0
        }}>

            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                rowKey={'REALESTATE_ID'}
                scroll={{ x: '100%', y: 'calc(100vh - 450px)' }}
                headerTitle={'不动产列表'}
                search={isComponent ? false : { span: 6, }}
                request={async (params) => {
                    if (!selectedId && !isComponent) {
                        return []
                    }

                    const req: any = {
                        searchParameter: {
                            REALESTATE_TYPE: isComponent ? '' : params?.REALESTATE_TYPE || "",// 不动产类型
                            SERVERPART_IDS: isComponent ? serverPartId : selectedId,
                            START_LEASEDATE_End: isComponent ? '' : params?.END_LEASEDATE_Start || "",
                            END_LEASEDATE_Start: isComponent ? '' : params?.START_LEASEDATE_End || "",
                            REALESTATE_STATE: 1
                        },
                        PageIndex: 1,
                        PageSize: 999999,
                        keyWord: {
                            Key: "PROVINCE_NAME,CITY_NAME",
                            Value: params?.searchText || ""
                        }
                    }
                    let newReq: any = {
                        name: "",
                        value: encryptAES(JSON.stringify(req))
                    }
                    const data: any = await handleGetREALESTATEList(newReq)
                    console.log('datadatadata', data);
                    if (data && data.length > 0) {
                        return { data, success: true }
                    }
                    return { data: [], success: true }
                }}
                rowSelection={isComponent ? {
                    type: 'checkbox',
                    defaultSelectedRowKeys: selectRealEstateId || [],
                    onChange: (_, row) => {
                        console.log('__', _);
                        console.log('row', row);

                        setSelectRowDetail(row)
                    }
                } : false}
                toolbar={{
                    actions: [
                        <Button type="primary" onClick={() => {
                            setShowDetail(true)
                        }}>添加不动产</Button>
                    ]
                }}
            />
        </div>

        <Modal
            title={currentRow?.REALESTATE_ID ? '编辑不动产' : '添加不动产'}
            destroyOnClose
            width={1200}
            open={showDetail}
            className="realEstateModalBox"
            onCancel={() => {
                setCurrentRow(undefined)
                setShowDetail(false)
            }}
            confirmLoading={confirmLoading}
            footer={
                <ModalFooter
                    confirmLoading={confirmLoading}
                    hideDelete={!currentRow?.REALESTATE_ID}
                    handleDelete={async () => {
                        setConfirmLoading(true)
                        await handleDeleteOrUpdate(currentRow?.REALESTATE_ID)
                    }}
                    handleCancel={() => {
                        setCurrentRow(undefined)
                        setShowDetail(false)
                    }}
                    handleOK={() => {
                        modalFormRef.current?.validateFields().then(async (res) => {
                            setConfirmLoading(true)
                            await handleAddOrUpdate(res)
                        })
                    }}
                />
            }
        >
            <ProForm
                formRef={modalFormRef}
                submitter={false}
                request={async () => {
                    if (currentRow?.REALESTATE_ID) {
                        return {
                            ...currentRow,
                            SERVERPART_ID: currentRow?.SERVERPART_ID.toString(),
                            LEASEDATE: [moment(currentRow?.START_LEASEDATE), moment(currentRow?.END_LEASEDATE)]
                        }
                    } else {
                        return {}
                    }
                }}
                onFinish={() => {
                }}
            >
                <Row gutter={16}>
                    <Col span={8}>
                        <ProFormSelect
                            label={'不动产类型'}
                            name={'REALESTATE_TYPE'}
                            options={[
                                { label: "房屋租赁", value: 1000 },
                                { label: "车辆资产", value: 2000 },
                            ]}
                            rules={[{
                                required: true,
                                message: '请选择不动产类型!'
                            }]}
                        />
                    </Col>

                    <Col span={8}>
                        <ProFormSelect
                            label={'服务区'}
                            name={'SERVERPART_ID'}
                            options={[
                                { label: "房屋租赁", value: 1000 },
                                { label: "车辆资产", value: 2000 },
                            ]}
                            request={async () => {
                                if (serverPartList && serverPartList.length > 0) {
                                    return serverPartList
                                } else {
                                    const req: any = {
                                        ProvinceCode: "530000",
                                    }
                                    let list: any = []
                                    const data = await handleGetServerpartDDL(req)
                                    if (data && data.length > 0) {
                                        list = data
                                        setServerPartList(list)
                                    } else {
                                        setServerPartList([])
                                    }
                                    return list
                                }
                            }}
                            fieldProps={{
                                showSearch: true,
                                filterOption: (input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
                                optionFilterProp: 'label',
                                onChange: async (value, option: any) => {
                                    modalFormRef.current?.setFieldsValue({ SERVERPART_NAME: option.title })
                                    // 顺便拿个 服务区详情 
                                    let detail: any = await handleGetSERVERPARTDetail({ SERVERPARTId: value })
                                    // 从地址里面 解出 城市(市区)
                                    let address: any = parseAddress(detail?.SERVERPART_ADDRESS);

                                    modalFormRef.current?.setFieldsValue({ PROVINCE_NAME: detail?.PROVINCE_NAME, CITY_NAME: address?.city, REALESTATE_ADDRESS: detail?.SERVERPART_ADDRESS })
                                }
                            }}
                            rules={[{
                                required: true,
                                message: '请选择服务区!'
                            }]}
                        />
                    </Col>
                    <Col span={8} style={{ display: 'none' }}>
                        <ProFormText
                            label={'服务区'}
                            name={'SERVERPART_NAME'}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormDateRangePicker
                            label={'租赁日期'}
                            name={"LEASEDATE"}
                            style={{ width: '100%' }}
                        />
                    </Col>

                    <Col span={8} >
                        <ProFormText
                            label={'省份名称'}
                            name={'PROVINCE_NAME'}
                        />
                    </Col>
                    <Col span={8} >
                        <ProFormText
                            label={'城市名称'}
                            name={'CITY_NAME'}
                        />
                    </Col>
                    <Col span={8} >
                        <ProFormSelect
                            label={'跨地标志'}
                            name={'CROSS_CITYSIGN'}
                            options={[
                                { label: "是", value: 1 },
                                { label: "否", value: 0 },
                            ]}
                        />
                    </Col>
                    <Col span={24} >
                        <ProFormTextArea
                            label={'详细地址'}
                            name={'REALESTATE_ADDRESS'}
                        />
                    </Col>
                    <Col span={8} >
                        <ProFormSelect
                            label={'面积单位'}
                            name={'AREA_UNIT'}
                            options={[
                                { label: "平方千米", value: 1 },
                                { label: "平方米", value: 2 },
                                { label: "公顷", value: 3 },
                                { label: "亩", value: 4 },
                                { label: "h㎡", value: 5 },
                                { label: "k㎡", value: 6 },
                                { label: "㎡", value: 7 }
                            ]}
                        />
                    </Col>
                    <Col span={8} >
                        <ProFormText
                            label={'产权证号'}
                            name={'ESTATE_IDENTITY'}
                            rules={[
                                ({ getFieldValue }) => ({
                                    validator(_: any, value: any) {
                                        if (value || getFieldValue('SPECIALINDUSTRY_NUMBER')) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('产权证号和资料编码至少填写一个'));
                                    },
                                }),
                            ]}
                        />
                    </Col>
                    <Col span={8} >
                        <ProFormText
                            label={'资料编码'}
                            name={'SPECIALINDUSTRY_NUMBER'}
                            rules={[
                                ({ getFieldValue }) => ({
                                    validator(_: any, value: any) {
                                        if (value || getFieldValue('ESTATE_IDENTITY')) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('产权证号和资料编码至少填写一个'));
                                    },
                                }),
                            ]}
                        />
                    </Col>


                </Row>
            </ProForm>


        </Modal>

    </div >
}


export default RealEstate         