
import { useEffect, useRef, useState } from 'react';
import { connect } from '@umijs/max';
import type { ActionType } from '@ant-design/pro-components';
import {
    ProTable, ProFormSelect
} from '@ant-design/pro-components';
import { Button, ConfigProvider, Modal, Popconfirm, message, Space } from 'antd';
import { GetCompanyDepartmentList, getCompanyList, GetCompanyInfo, PostcompanyDepartmentsDel, PostcompanyDepartmentDel } from '@/apis/api';
const selectfieldNames = { label: 'full_name', value: 'id' };
const PagesMainCompanyDepartmentTable: React.FC = ({ dispatch, getId, openModel }: any) => {
    const actionRef = useRef<ActionType>();
    const [list, setList] = useState<object[]>([])
    const [total, setTotal] = useState<number>(0)
    const [page, setPage] = useState<number>(1)
    const [pageSize, setPageSize] = useState<number>(10)
    const [companyId, setCompanyId] = useState<number>(0);
    const [ids, setIds] = useState<number[]>([])

    const setId = (id: number) => {
        getId(id)
    }

    useEffect(() => {
        if (!openModel.openModal) {
            actionRef.current?.reload();
        }

        return () => {
            sessionStorage.removeItem('company_info')
            sessionStorage.removeItem('post_company_info')
            sessionStorage.removeItem('vip_company_info')

        };
    }, [openModel.openModal])



    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                        colorLink: '#4FBE70',

                    },
                    components: {
                        Modal: {
                            colorPrimary: '#4FBE70',

                        }
                    }
                }}
            >

                <ProTable
                    size='small'
                    scroll={{ y: 480, x: 'auto' }}
                    bordered={true}
                    actionRef={actionRef}
                    dataSource={list}
                    search={{ span: 8, labelWidth: 'auto' }}
                    tableAlertRender={({
                        selectedRowKeys,
                        selectedRows,
                        onCleanSelected,
                    }) => {
                        setIds(selectedRowKeys)
                        return (
                            <Space size={24}>
                                <span>
                                    已选 {selectedRowKeys.length} 项
                                    <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                                        取消选择
                                    </a>
                                </span>
                            </Space>
                        );
                    }}
                    tableAlertOptionRender={({
                        onCleanSelected,
                    }) => {
                        return (
                            <Space size={16}>
                                <Button danger type="primary" onClick={() => {
                                    Modal.confirm({
                                        title: '批量删除',
                                        content: '确定要删除所选的数据吗',
                                        onOk() {
                                            PostcompanyDepartmentsDel({ ids: ids }).then(res => {
                                                onCleanSelected()
                                                actionRef.current?.reload();
                                            })

                                        },
                                        onCancel() {
                                            console.log('Cancel');
                                        },
                                        okText: '确定',
                                        cancelText: '取消',
                                        centered: true
                                    });
                                }}>
                                    批量删除
                                </Button>,
                            </Space>
                        );
                    }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    columns={[
                        {
                            title: '部门名称',
                            dataIndex: 'name',
                            width: 200
                        },
                        {
                            title: '所属企业',
                            dataIndex: 'company_name',
                            width: 200
                        },
                        {
                            title: '所属企业',
                            dataIndex: 'company_id',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            renderFormItem: () => {
                                return (
                                    <ProFormSelect
                                        width='lg'
                                        fieldProps={{
                                            fieldNames: selectfieldNames,
                                            defaultValue: sessionStorage.getItem('company_info') ? JSON.parse(sessionStorage.getItem('company_info')).full_name : null,
                                        }}
                                        request={async (keyword) =>
                                            getCompanyList({ page: 1, pagesize: 100, keyword: keyword.keyWords }).then(res => {
                                                return res.data.list;
                                            })
                                        }
                                        placeholder="请选择所属企业"
                                        onChange={(value) => {
                                            setCompanyId(value)
                                            GetCompanyInfo({ id: value }).then(res => {
                                                sessionStorage.setItem('company_info', JSON.stringify(res.data))
                                            })
                                        }}
                                    />
                                )
                            }
                        },
                        {
                            title: '联系人',
                            search: false,
                            width: 200,

                            dataIndex: 'contact'
                        },
                        {
                            title: '联系电话',
                            search: false,
                            width: 200,

                            dataIndex: 'phone'
                        },
                        {
                            title: '手机',
                            search: false,
                            width: 200,

                            dataIndex: 'mobile'
                        },
                        {
                            title: '邮箱',
                            search: false,
                            width: 200,

                            dataIndex: 'email'
                        },
                        {
                            title: '操作',
                            key: 'option',
                            valueType: 'option',
                            render: (_, record, action) => [
                                <Button key='1' type='link' onClick={() => {
                                    setId(record.id)
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>编辑</Button>,
                                <Popconfirm
                                    title="是否删除"
                                    onConfirm={(e) => {
                                        PostcompanyDepartmentDel({ id: record.id }).then(res => {
                                            message.success('删除成功')
                                            actionRef.current?.reload();
                                        })
                                    }}
                                    okText="删除"
                                    cancelText="取消"
                                >
                                    <Button danger type='link'>删除</Button>
                                </Popconfirm>,

                            ],
                        },
                    ]}
                    rowKey="id"
                    pagination={{
                        current: page,
                        pageSize: pageSize,
                        showSizeChanger: true,
                        total: total,
                        pageSizeOptions: [9, 18, 27, 99],
                        onChange(page, pageSize) {
                            setPage(page)
                            setPageSize(pageSize)
                        },
                        onShowSizeChange(current, size) {
                            setPage(current)
                            setPageSize(size)
                        }
                    }}
                    request={async (params = {} as Record<string, any>) =>
                        GetCompanyDepartmentList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.name,
                            company_id: sessionStorage.getItem('company_info') ? JSON.parse(sessionStorage.getItem('company_info')).id : companyId
                        }).then(res => {
                            setList(res.data.rows)
                            setTotal(res.data.total)
                        })
                    }
                    onReset={() => {
                        if (sessionStorage.getItem('company_info')) {
                            sessionStorage.removeItem('company_info')
                        }
                        setCompanyId(0)
                        actionRef.current?.reload();
                    }}
                    headerTitle="部门列表"
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                        }}>
                            添加部门
                        </Button>,
                    ]}
                />


            </ConfigProvider>

        </>



    );
};


export default connect(({ dictModel, openModel }: any) => ({
    dictModel,
    openModel
}))(PagesMainCompanyDepartmentTable);