import { FileSearchOutlined, MenuFoldOutlined, PlusOutlined } from "@ant-design/icons"
import { ActionType, ProCard, ProForm, ProFormDigit, ProFormSelect, ProFormText, ProFormTreeSelect, ProTable } from "@ant-design/pro-components"
import { Button, FormInstance, message, Modal, Popconfirm, Space, Tree } from "antd"
import { useEffect, useRef, useState } from "react"
import { getFieldEnumTree, handleDeleteAPPROVALROUTE, handleGetAPPROVALROUTEList, handleGetUserList, handleSynchroAPPROVALROUTE } from "../serverpartAssets/service"
import moment from "moment"
import ChosePlayers from "./components/ChosePlayers"

const BusinessConfiguration = () => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalFormRef = useRef<FormInstance>();
    const chosePlayerRef = useRef<any>();

    // 折叠左侧业务类型属性选择框
    const [collapsible, setCollapsible] = useState<boolean>(false)
    // 左侧业务类型数据
    const [treeView, setTreeView] = useState<any>()
    // 左侧业务类型数据对象
    const [serviceTypeObj, setServiceTypeObj] = useState<any>()
    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 存储当前数据的搜索条件
    const [searchParams, setSearchParams] = useState<any>()
    // 显示新增环节的悬浮框
    const [modalVisible, setModalVisible] = useState<boolean>(false)
    // 选中的当前行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 悬浮框的确认按钮的loading
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
    // 参与人列表
    const [playerList, setPlayerList] = useState<any>()
    // 当前已经存在了的参与人
    const [defaultPerson, setDefaultPerson] = useState<any>()
    // 显示参与人的悬浮框
    const [showChosePlayer, setShowChosePlayer] = useState<boolean>(false)

    const columns: any = [
        {
            title: '环节名称',
            width: 150,
            dataIndex: 'APPROVALROUTE_NAME',
            align: 'center',
            hideInSearch: true
        },
        {
            title: '业务状态',
            width: 120,
            dataIndex: 'APPROVALROUTE_STATE',
            align: 'center',
            sorter: (a, b) => a.APPROVALROUTE_STATE - b.APPROVALROUTE_STATE,
            defaultSortOrder: 'ascend',
        },
        {
            title: '业务类型',
            width: 120,
            dataIndex: 'OPERATION_TYPE',
            valueType: 'select',
            align: 'center',
            hideInSearch: true,
            valueEnum: serviceTypeObj
        },
        {
            title: '下一业务状态',
            width: 120,
            dataIndex: 'NEXT_STATE',
            align: 'center',
            // valueType: 'select',
            hideInSearch: true,
            // valueEnum:{
            //   2000:'商户确认审核',
            //   2010:'服务区经理审核',
            //   2020:'片区中心审核',
            //   2030:'经发部审核',
            //   2040:'财务部审核',
            // }
        },
        {
            title: '参与人',
            dataIndex: 'APPROVALSTAFF_NAME',
            align: 'center',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '生成时间',
            width: 150,
            dataIndex: 'RECORD_DATE',
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return record?.RECORD_DATE ? moment(record?.RECORD_DATE).format('YYYY-MM-DD') : ''
            }
        },
        {
            title: '业主单位',
            width: 120,
            align: 'center',
            dataIndex: 'PROVINCE_CODE',
            hideInSearch: true,
        },
        {
            dataIndex: 'option',
            title: '操作',
            width: 120,
            valueType: 'option',
            align: 'center',
            fixed: 'right',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space>
                        <a onClick={() => {
                            setCurrentRow(record)
                            setModalVisible(true)
                        }}>编辑</a>
                        <Popconfirm
                            title="确认删除？"
                            onConfirm={async () => {
                                const req: any = {
                                    APPROVALROUTEId: record?.APPROVALROUTE_ID
                                }
                                const data = await handleDeleteAPPROVALROUTE(req)
                                if (data.Result_Code === 100) {
                                    message.success('删除成功')
                                    actionRef.current?.reload()
                                } else {
                                    message.error(data.Result_Desc)
                                }
                            }}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    </Space>
                )
            }
        }

    ]

    // 解构左侧类型
    const extractValueLabel = (list: any) => {
        const result: any = {};

        function traverse(nodes: any) {
            if (!Array.isArray(nodes)) return;

            nodes.forEach(item => {
                if (item.value !== undefined && item.label !== undefined) {
                    result[item.value] = item.label;
                }
                if (Array.isArray(item.children)) {
                    traverse(item.children);
                }
            });
        }

        traverse(list);
        return result;
    }

    useEffect(() => {
        getFieldEnumTree({ FieldExplainField: 'PROCESS_TYPE', sessionName: 'PROCESS_TYPE' }).then((res: any) => {
            console.log('resresresres', res);
            let obj = extractValueLabel(res)
            setServiceTypeObj(obj)
            setTreeView(res)
        })
    }, []);

    return (
        <div style={{ height: 'calc(100vh - 100px)', background: "#fff", display: 'flex' }}>
            <div>
                <ProCard
                    style={{ width: !collapsible ? "300px" : "60px" }}
                    className="pageTable-leftnav"
                    bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
                    extra={<MenuFoldOutlined onClick={() => {
                        setCollapsible(!collapsible)
                    }} />}
                    colSpan={!collapsible ? "300px" : "60px"}
                    title={!collapsible ? "请选择业务类型" : ""}
                    headerBordered
                    collapsed={collapsible}
                >
                    {treeView && treeView.length > 0 ? <Tree
                        checkable
                        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 => n?.type === 2)
                            setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
                        }}
                    // switcherIcon={<PlusOutlined />}
                    /> : ''}
                </ProCard>
            </div>

            <div style={{
                width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                paddingTop: 0,
                paddingBottom: 0,
                paddingRight: 0
            }}>
                <ProTable
                    actionRef={actionRef}
                    formRef={formRef}
                    columns={columns}
                    bordered
                    expandable={{
                        expandRowByClick: true
                    }}
                    headerTitle={'业务配置'}
                    search={{ span: 6 }}
                    request={async (params) => {
                        if (!selectedId) {
                            return
                        }
                        const req: any = {
                            SearchParameter: {
                                PROVINCE_CODE: '530000',
                                OPERATION_TYPES: selectedId || '',
                                APPROVALROUTE_VALID: 1
                            },

                            PageIndex: 1,
                            PageSize: 999999
                        }
                        setSearchParams(params)
                        const data = await handleGetAPPROVALROUTEList(req)
                        console.log('fdsjfhsdjkfhsa', data);

                        if (data && data.length > 0) {
                            return { data, success: true }
                        }
                        return { data: [], success: true }
                    }}
                    toolbar={{
                        actions: [
                            <Button
                                key="new"
                                icon={<PlusOutlined />}
                                type="primary"
                                onClick={(e) => {
                                    setModalVisible(true)
                                }}
                            >
                                新增环节
                            </Button>
                        ]
                    }}
                />
            </div>


            <Modal
                title={currentRow ? "编辑环节" : "新增环节"}
                width={600}
                destroyOnClose
                open={modalVisible}
                confirmLoading={confirmLoading}
                onOk={(e) => {
                    setModalVisible(false)
                    modalFormRef.current?.validateFields().then((res: any) => {
                        modalFormRef.current?.submit()
                    })
                }}
                onCancel={(e) => {
                    setModalVisible(false)
                    modalFormRef.current?.resetFields();
                    setDefaultPerson([])
                    setPlayerList([])
                    setCurrentRow(undefined)
                }}
            >
                <ProForm
                    formRef={modalFormRef}
                    submitter={false}
                    initialValues={currentRow}
                    request={async () => {
                        console.log('currentRowcurrentRow', currentRow);

                        if (currentRow) {
                            if (currentRow?.APPROVALSTAFF_ID) {
                                const req: any = {
                                    SearchParameter: {
                                        USER_IDS: currentRow?.APPROVALSTAFF_ID
                                    },
                                    PageIndex: 1,
                                    PageSize: 999999
                                }
                                const data = await handleGetUserList(req)
                                console.log('datadatadata', data);
                                setDefaultPerson(data)

                                if (data && data.length > 0) {
                                    const list: any = []
                                    data.forEach((item: any) => {
                                        list.push({ label: item.USER_NAME, value: item.USER_ID.toString() })
                                    })
                                    setPlayerList(list)
                                }
                            }

                            return {
                                ...currentRow,
                                APPROVALSTAFF_ID: currentRow?.APPROVALSTAFF_ID ? currentRow?.APPROVALSTAFF_ID.split(',') : null
                            }
                        } else {
                            return {}
                        }
                    }}
                    onFinish={async (res) => {
                        console.log('readas', res);
                        let req: any = {}
                        if (currentRow) {
                            req = {
                                APPROVALROUTE_ID: currentRow?.APPROVALROUTE_ID,
                                APPROVALROUTE_NAME: res?.APPROVALROUTE_NAME || '',
                                APPROVALROUTE_STATE: res?.APPROVALROUTE_STATE || '',
                                OPERATION_TYPE: res?.OPERATION_TYPE || '',
                                APPROVALSTAFF_ID: res?.APPROVALSTAFF_ID ? res?.APPROVALSTAFF_ID.toString() : null,
                                APPROVALROUTE_VALID: 1,
                                PROVINCE_CODE: '530000',
                                NEXT_STATE: res?.NEXT_STATE
                            }
                        } else {
                            req = {
                                APPROVALROUTE_NAME: res?.APPROVALROUTE_NAME || '',
                                APPROVALROUTE_STATE: res?.APPROVALROUTE_STATE || '',
                                OPERATION_TYPE: res?.OPERATION_TYPE || '',
                                APPROVALSTAFF_ID: res?.APPROVALSTAFF_ID ? res?.APPROVALSTAFF_ID.toString() : null,
                                APPROVALROUTE_VALID: 1,
                                PROVINCE_CODE: '530000',
                                NEXT_STATE: res?.NEXT_STATE
                            }
                        }
                        setConfirmLoading(true)
                        const data = await handleSynchroAPPROVALROUTE(req)
                        setConfirmLoading(false)
                        if (data.Result_Code === 100) {
                            message.success('新增成功')
                            modalFormRef.current?.resetFields();
                            setCurrentRow(undefined)
                            actionRef.current?.reload()
                            setModalVisible(false)
                            setDefaultPerson([])
                            setPlayerList([])
                            return true
                        }
                        message.error(data.Result_Desc)
                    }}
                >
                    <ProFormTreeSelect
                        label={"业务类型"}
                        name={"OPERATION_TYPE"}
                        request={async (params) => {
                            let list: any = JSON.parse(JSON.stringify(treeView))
                            if (list && list.length > 0) {
                                list.forEach((item: any) => {
                                    item.disabled = true
                                })
                            }
                            return list
                        }}
                        fieldProps={{
                            treeDefaultExpandAll: true
                        }}
                        rules={[
                            {
                                required: true,
                                message: '请选择业务类型',
                            },
                        ]}
                    />

                    <ProFormText
                        label={'环节名称'}
                        name={'APPROVALROUTE_NAME'}
                        rules={[
                            {
                                required: true,
                                message: '请输入环节名称',
                            },
                        ]}
                    />

                    <ProFormDigit
                        label={"业务状态"}
                        name={"APPROVALROUTE_STATE"}
                        rules={[
                            {
                                required: true,
                                message: '请选择业务状态',
                            },
                        ]}
                    />

                    <ProFormDigit
                        label={"下一个业务状态"}
                        name={"NEXT_STATE"}
                        rules={[
                            {
                                required: true,
                                message: '请选择下一个业务状态',
                            },
                        ]}
                        tooltip={'若下一状态为审结则是9000'}
                    />

                    <ProFormSelect
                        label={'参与人'}
                        name={'APPROVALSTAFF_ID'}
                        width={'lg'}
                        fieldProps={{
                            options: playerList || [],
                            mode: 'multiple'
                        }}
                        addonAfter={
                            <Button type="primary" icon={<FileSearchOutlined />}
                                onClick={() => {
                                    const res = modalFormRef.current?.getFieldValue('APPROVALSTAFF_ID')
                                    console.log('resres', res);

                                    // if ([res] && [res].length > 0) {
                                    //     const list: any = []
                                    //     [res].forEach((item: any) => {
                                    //         list.push(Number(item))
                                    //     })
                                    //     setDefaultPerson(list)
                                    // } else {
                                    //     setDefaultPerson([])
                                    //     setPlayerList([])
                                    // }
                                    setShowChosePlayer(true)
                                }}>
                                选择
                            </Button>}
                    />

                </ProForm>
            </Modal>

            <Modal
                title={'选择参与人'}
                width={'80%'}
                open={showChosePlayer}
                destroyOnClose
                bodyStyle={{
                    height: '700px',
                    overflowY: 'auto'
                }}
                onOk={(e) => {
                    setShowChosePlayer(false)
                    let detailList: any = chosePlayerRef?.current?.selectedRowDetail
                    console.log('detailListdetailList', detailList);

                    let list: any = []
                    if (detailList && detailList.length > 0) {
                        detailList.forEach((item: any) => {
                            list.push({ label: item?.USER_NAME, value: item.USER_ID })
                        })
                    }
                    setPlayerList(list)
                    modalFormRef.current?.setFieldsValue({ APPROVALSTAFF_ID: chosePlayerRef?.current?.selectedRowKeys })
                }}
                onCancel={(e) => {
                    setShowChosePlayer(false)
                }}
            >
                <ChosePlayers onRef={chosePlayerRef} actionRef={actionRef} defaultPerson={defaultPerson} />

            </Modal>
        </div>
    )
}



export default BusinessConfiguration;