import React, { useRef, useState } from 'react';
import { connect } from 'umi';
import type { ConnectState } from "@/models/connect";
import type { CurrentUser } from "umi";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import { Tag, message, Modal, Space } from "antd";
import { handleGetMEMBERSHIPList, handeGetSynchroMEMBERSHIP, handleGetServerpartTree } from "../service";
import session from "@/utils/session";
import PageTitleBox from "@/components/PageTitleBox";
import type { FormInstance } from "antd";
import ProForm, { ProFormSelect, ProFormTreeSelect } from '@ant-design/pro-form';

const OwnWaterManager: React.FC<{ currentUser: CurrentUser, isComponent?: boolean, searchReq?: any }> = (props) => {
    const { currentUser } = props;
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalFormRef = useRef<FormInstance>();
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [selectedRows, setSelectedRows] = useState<any[]>([]);
    const [stationModalVisible, setStationModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<any>(null);
    const MEMBERSHIPLEVELYNObj = session.get('MEMBERSHIPLEVELYNObj') || {};
    const [treeData, setTreeData] = useState<any[]>([]);
    // 表单加载效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
    // 辅助函数：处理标签字符串 (Logic B)
    const updateTargetTags = (currentTags: string | undefined, targetTag: string, action: 'add' | 'remove') => {
        let tagList = (currentTags || '').split(',').filter(Boolean);
        if (action === 'add') {
            if (!tagList.includes(targetTag)) {
                tagList.push(targetTag);
            }
        } else {
            tagList = tagList.filter(t => t !== targetTag);
        }
        return tagList.join(',');
    };

    // 批量操作通用逻辑 (Logic B)
    const handleBatchAction = (action: 'add' | 'remove') => {
        if (selectedRowKeys.length === 0) {
            message.warning('请先选择会员');
            return;
        }

        const title = action === 'add' ? '确认批量开通权限' : '确认批量取消权限';
        const content = action === 'add'
            ? `确定为选中的 ${selectedRowKeys.length} 名会员开通自有水权限吗？`
            : `确定为选中的 ${selectedRowKeys.length} 名会员取消自有水权限吗？`;

        Modal.confirm({
            title,
            content,
            onOk: async () => {
                const hide = message.loading('正在处理中...');
                try {
                    const promises = selectedRows.map((row) => {
                        const newTags = updateTargetTags(row.MEMBERSHIP_TARGET, '2803', action);
                        return handeGetSynchroMEMBERSHIP({
                            ...row,
                            MEMBERSHIP_TARGET: newTags || "#", // 若标签为空，传 # 占位
                        });
                    });
                    const results = await Promise.all(promises);
                    const allSuccess = results.every((res: any) => res.Result_Code === 100);

                    if (allSuccess) {
                        message.success('操作成功！');
                        setSelectedRowKeys([]);
                        setSelectedRows([]);
                        actionRef.current?.reload();
                    } else {
                        const failedCount = results.filter((res: any) => res.Result_Code !== 100).length;
                        message.error(`部分操作失败，失败条目数：${failedCount}`);
                        actionRef.current?.reload();
                    }
                } catch (error) {
                    console.error('Batch action error:', error);
                    message.error('操作异常');
                } finally {
                    hide();
                }
            },
        });
    };

    const handleBatchOpen = () => handleBatchAction('add');
    const handleBatchCancel = () => handleBatchAction('remove');

    const columns: ProColumns<any>[] = [
        {
            title: '用户昵称',
            dataIndex: 'MEMBERSHIP_NAME',
            width: 150,
            ellipsis: true,
            align: 'center',
            fieldProps: {
                placeholder: '搜索用户昵称/电话',
            },
        },
        {
            title: '联系电话',
            dataIndex: 'MEMBERSHIP_MOBILEPHONE',
            width: 150,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '会员等级',
            dataIndex: 'MEMBERSHIP_LEVEL',
            width: 120,
            align: 'center',
            valueType: 'select',
            valueEnum: MEMBERSHIPLEVELYNObj,
            hideInSearch: true,
        },
        {
            title: '自有水权限',
            dataIndex: 'MEMBERSHIP_TARGET',
            width: 120,
            align: 'center',
            valueType: 'select',
            valueEnum: {
                '': { text: '全部' },
                '2803': { text: '已开通' },
                '-2803': { text: '未开通' },
            },
            hideInTable: true,
            initialValue: '',
        },
        {
            title: '权限状态',
            dataIndex: 'MEMBERSHIP_TARGET_STATUS',
            width: 120,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                const isAuth = record.MEMBERSHIP_TARGET === '2803' || record.MEMBERSHIP_TARGET?.toString().includes('2803');
                return (
                    <Tag color={isAuth ? 'green' : 'red'}>
                        {isAuth ? '已开通' : '未开通'}
                    </Tag>
                );
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width: 120,
            align: 'center',
            render: (_, record) => {
                const isAuth = record.MEMBERSHIP_TARGET === '2803' || record.MEMBERSHIP_TARGET?.toString().includes('2803');
                if (!isAuth) return null;
                return (
                    <Space>
                        <a
                            onClick={() => {
                                console.log('recordrecord', record);

                                setCurrentRow(record);
                                setStationModalVisible(true);
                            }}
                        >
                            站点权限
                        </a>
                    </Space>
                );
            },
        },
    ];

    // 拿到站点信息
    const handleGetStationList = async (stationType: any) => {
        const params = {
            ProvinceCode: '530000',
            ShowWholePower: true,
            ShowRoyalty: false,
            ShowCompactCount: false,
            StatisticsType: '1000',
            ServerpartType: stationType || '1010',
        };
        const res = await handleGetServerpartTree(params);
        console.log('dasdasdas', res);

        setTreeData(res);
        return res;
    }

    // 更新用户权限
    const handleUpdateStationList = async (res: any) => {
        let req: any = {
            ...currentRow,
            SERVERPART_AUTHORITY: res.stationIds && res.stationIds.length > 0 ? res.stationIds.toString() : "#"
        }
        setConfirmLoading(true);
        const data = await handeGetSynchroMEMBERSHIP(req);
        console.log('dashdlasjdaslk', data);
        setConfirmLoading(false);
        if (data.Result_Code = 100) {
            message.success(data.Result_Desc)
            setStationModalVisible(false);
            actionRef.current?.reload();
        } else {
            message.error(data.Result_Desc)
        }
    }

    return (
        <div style={{ background: '#fff', padding: '16px' }}>
            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                rowKey="MEMBERSHIP_ID"
                headerTitle={<PageTitleBox props={props} />}
                bordered
                scroll={{ y: 'calc(100vh - 500px)' }}
                search={{
                    labelWidth: 'auto',
                    defaultCollapsed: false,
                    span: 6,
                }}
                request={async (params, sorter) => {
                    const sortstr = Object.keys(sorter).map(n => {
                        const value = sorter[n]
                        return value ? `${n} ${value.replace('end', '')}` : ''
                    }).filter(Boolean).toString();

                    const req = {
                        SearchParameter: {
                            OWNERUNIT_ID: currentUser?.OwnerUnitId || 911,
                            MEMBERSHIP_TARGET: params?.MEMBERSHIP_TARGET || "",
                            MEMBERSHIP_STATES: 1000,
                        },
                        keyWord: {
                            Key: "MEMBERSHIP_NAME,MEMBERSHIP_MOBILEPHONE",
                            value: params?.MEMBERSHIP_NAME || ""
                        },
                        PageIndex: params.current || 1,
                        PageSize: params?.pageSize || 20,
                        sortstr: sortstr,
                    };

                    const data = await handleGetMEMBERSHIPList(req);
                    return {
                        data: data?.List || [],
                        success: true,
                        total: data?.TotalCount || 0,
                    };
                }}
                rowSelection={{
                    selectedRowKeys,
                    onChange: (keys, rows) => {
                        setSelectedRowKeys(keys);
                        setSelectedRows(rows);
                    },
                }}
                tableAlertOptionRender={() => (
                    <Space size={16}>
                        <a onClick={handleBatchOpen}>批量开通权限</a>
                        <a onClick={handleBatchCancel} style={{ color: '#ff4d4f' }}>批量取消权限</a>
                    </Space>
                )}
            />

            <Modal
                title={`${currentRow?.MEMBERSHIP_NAME}站点权限`}
                width={"800px"}
                open={stationModalVisible}
                destroyOnClose
                confirmLoading={confirmLoading}
                onOk={async () => {
                    modalFormRef.current?.validateFields().then((res) => {
                        console.log('dsakdasldjaslkdjaslkdj', res);

                        modalFormRef.current?.submit()
                    })
                }}
                onCancel={() => {
                    setCurrentRow(undefined);
                    setStationModalVisible(false);
                }}
            >
                <ProForm
                    formRef={modalFormRef}
                    submitter={false}
                    request={async () => {
                        await handleGetStationList(1010)
                        if (currentRow) {
                            let res: any = {}
                            if (currentRow?.SERVERPART_AUTHORITY) {
                                res = {
                                    ...res,
                                    stationIds: currentRow?.SERVERPART_AUTHORITY.split(',').map((item: any) => Number(item))
                                }
                            }
                            return res;
                        }
                        return {};
                    }}
                    onFinish={async (value) => {
                        await handleUpdateStationList(value)
                    }}
                >
                    <ProFormSelect
                        name="stationType"
                        label="选择范围"
                        options={[
                            { label: '全部', value: '1010,1000' },
                            { label: '片区', value: '1010' },
                            { label: '服务区', value: '1000' },
                        ]}
                        fieldProps={{
                            onChange: async (e: any) => {
                                setTreeData([]);
                                await handleGetStationList(e)
                                modalFormRef.current?.setFieldsValue({
                                    stationIds: []
                                })
                            }
                        }}
                        initialValue={'1010'}
                    />
                    {
                        treeData && treeData.length > 0 ?
                            <ProFormTreeSelect
                                name="stationIds"
                                label="站名列表"
                                rules={[{
                                    required: true, message: "请选择站点！"
                                }]}
                                placeholder="请选择站点"
                                fieldProps={{
                                    options: treeData,
                                    allowClear: true,
                                    multiple: true,
                                    treeDefaultExpandAll: true,
                                    showSearch: true,
                                    fieldNames: {
                                        key: "value",
                                        title: 'label',
                                    }
                                }}
                            /> : ""
                    }

                </ProForm>
            </Modal>

        </div>
    )
}

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