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, message, Space, Descriptions, Radio, Row, Col, Modal } from 'antd';
import { GetCompanyJobList, getCompanyList, GetCompanyInfo, PostJobExport } from '@/apis/api';
import { Imageprefix } from '@/constants';
const selectfieldNames = { label: 'full_name', value: 'id' };
const PagesMainCompanyPostTable: 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 [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([])
    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',

                    }
                }}
            >

                <ProTable
                    size='small'
                    scroll={{ y: 480, x: 'auto' }}
                    bordered={true}
                    actionRef={actionRef}
                    dataSource={list}
                    search={{ span: 8, labelWidth: 'auto' }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    columns={[
                        {
                            title: '筛选日期',
                            dataIndex: 'date_range',
                            hidden: true,
                            valueType: 'dateRange',
                        },
                        {
                            title: 'ID',
                            dataIndex: 'id',
                            width: 200
                        },

                        {
                            title: '所属企业',
                            dataIndex: 'full_name',
                            width: 200,
                            valueType: 'select',
                            renderFormItem: () => {
                                return (
                                    <ProFormSelect
                                        fieldProps={{
                                            fieldNames: selectfieldNames,
                                            defaultValue: sessionStorage.getItem('post_company_info') ? JSON.parse(sessionStorage.getItem('post_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('post_company_info', JSON.stringify(res.data))
                                            })
                                        }}
                                    />
                                )
                            }
                        },
                        {
                            title: '职位名称',
                            dataIndex: 'name',
                            width: 200
                        },
                        {
                            title: '点击次数',
                            dataIndex: 'click_count',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '职位状态',
                            dataIndex: 'status',
                            width: 200,
                            colSize: 16,
                            valueType: 'radio',
                            initialValue: '0',
                            valueEnum: {
                                0: { text: '全部' },
                                1: {
                                    text: '发布中',
                                    status: 'Processing'
                                },
                                2: {
                                    text: '未发布',
                                    status: 'Error'
                                },
                                3: {
                                    text: '暂停',
                                    status: 'Error'
                                },
                                4: {
                                    text: '已锁定',
                                    status: 'Error'
                                },
                                5: {
                                    text: '回收站',
                                    status: 'Error'
                                },
                                6: {
                                    text: '已过期',
                                    status: 'Error'
                                }
                            },
                        },

                        {
                            title: '有效期（天）',
                            dataIndex: 'useful_life',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '发布时间',
                            dataIndex: 'publish_date',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '到期时间',
                            dataIndex: 'disabled_date',
                            width: 200,
                            search: false,
                        },
                        {
                            title: '操作',
                            key: 'option',
                            valueType: 'option',
                            render: (_, record, action) => [
                                <Button key='1' type='link' onClick={() => {
                                    setId(record.id)
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>编辑</Button>
                            ],
                        },
                    ]}
                    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>) =>
                        GetCompanyJobList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.name,
                            expired: params.expired,
                            status: params.status ? params.status : 0,
                            company_id: sessionStorage.getItem('post_company_info') ? JSON.parse(sessionStorage.getItem('post_company_info')).id : companyId,
                            start_date: params.date_range ? params.date_range[0] : '',
                            end_date: params.date_range ? params.date_range[1] : '',
                        }).then(res => {
                            setList(res.data.rows)
                            setTotal(res.data.total)
                        })
                    }
                    onReset={() => {
                        if (sessionStorage.getItem('post_company_info')) {
                            sessionStorage.removeItem('post_company_info')
                        }
                        setCompanyId(0)
                        actionRef.current?.reload();

                    }}
                    headerTitle="职位列表"
                    toolBarRender={() => [<Button type="primary" onClick={() => {
                        Modal.confirm({
                            title: '批量发布',
                            content: (<>
                                <div>参数： id, status,useful_life ,disabled_date </div>

                                <h4 style={{ fontWeight: 'bold' }}>有效期：</h4>
                                <Radio.Group size='small' onChange={async (e) => {
                                    actionRef.current?.reload();
                                }}>
                                    <Row gutter={[20, 20]} style={{ padding: 20 }}>
                                        <Col span={12}>
                                            <Radio value={1}>1天</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>3天</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>7天</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>15天</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>30天</Radio>
                                        </Col>
                                    </Row>

                                </Radio.Group>
                            </>),
                            onOk() {

                            },
                            onCancel() {
                                console.log('Cancel');
                            },
                            okText: '确定',
                            cancelText: '取消',
                            centered: true
                        });
                    }}>
                        批量发布
                    </Button>,
                    <Button type="primary" onClick={() => {
                        Modal.confirm({
                            title: '批量更改状态',
                            content: (<>
                                <div>参数： id, status</div>

                                <Radio.Group size='small' onChange={async (e) => {
                                    actionRef.current?.reload();
                                }}>
                                    <Row gutter={[20, 20]} style={{ padding: 20 }}>
                                        <Col span={12}>
                                            <Radio value={1}>发布中</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>未发布</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>暂停</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>已锁定</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>回收站</Radio>
                                        </Col>
                                        <Col span={12}>
                                            <Radio value={1}>已过期</Radio>
                                        </Col>
                                    </Row>
                                </Radio.Group>
                            </>),
                            onOk() {

                            },
                            onCancel() {
                                console.log('Cancel');
                            },
                            okText: '确定',
                            cancelText: '取消',
                            centered: true
                        });
                    }}>
                        批量更改状态
                    </Button>,
                    <Button type="primary" onClick={() => {
                        message.info('数据导出需要时间，请耐心等待')
                        PostJobExport().then(res => {
                            let url = Imageprefix + res.data.excel_url;
                            window.open(url);
                            message.info('数据导出完毕')
                        })
                    }}>
                        导出数据
                    </Button>,
                    <Button type="primary" onClick={() => {
                        dispatch({ type: 'openModel/getOpenModal', payload: true })
                    }}>
                        添加职位
                    </Button>
                    ]}
                />


            </ConfigProvider>

        </>



    );
};


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