import { useRef, useState, useEffect } from 'react';
import { connect } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable, ProForm, ProFormSelect, ProFormText, ProFormDependency
} from '@ant-design/pro-components';
import { Button, ConfigProvider, Image, message, Modal, Input, Row, Flex, Space, Radio, Descriptions } from 'antd';
import { PostJobseekerList, PostJobseekerExport, PostJobapplicantUpdate } from '@/apis/api';
import { Imageprefix } from '@/constants';
import DragUpload from '@/components/Common/dragupload';

const selectfieldNames = { label: 'name', value: 'id' };


const PagesMainJobseekerListTable: React.FC = ({ dispatch, getId, dictModel, openModel }: any) => {
    const [form, setForm] = useState<{ status: number, customer_id: number, id: number, audit_memo: string }>({
        status: 1,
        customer_id: 0,
        id: 0,
        audit_memo: ''
    });
    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 [openMultieditPreview, setOpenMultieditPreview] = useState(false);
    const [ids, setIds] = useState<number[]>([])
    const [status, setStatus] = useState<number>(2)
    const [auditMemo, setAuditMemo] = useState<string>('')


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

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

    useEffect(() => {
        dispatch({ type: 'dictModel/getList', payload: { code: 2004, type: 'setPositionList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2009, type: 'setAreaList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2005, type: 'setPayList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2016, type: 'setAccommodationRequirementList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2017, type: 'setHolidayRestList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2018, type: 'setLicenseList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2021, type: 'setWorkExperienceList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2006, type: 'setEducationList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2014, type: 'setTitleList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2015, type: 'setSkillCertificationeList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2007, type: 'setOtherLanguageList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2008, type: 'setDegreeList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2027, type: 'setIndustryPostList' } })
        dispatch({ type: 'dictModel/getList', payload: { code: 2010, type: 'setPoliticalList' } })
    }, [])

    const expandedRowRender = (record) => {
        return (
            <>
                <Space direction='vertical' style={{ width: '100%' }}>
                    <Descriptions title="基本信息" bordered column={3} contentStyle={{ fontWeight: 'bold' }} labelStyle={{ width: 180 }}>
                        <Descriptions.Item label="英语">{record.english_txt}</Descriptions.Item>
                        <Descriptions.Item label="国语">{record.mandarin_txt}</Descriptions.Item>
                        <Descriptions.Item label="粤语">{record.cantonese_txt}</Descriptions.Item>
                        <Descriptions.Item label="职称">{record.title_txt}</Descriptions.Item>
                        <Descriptions.Item label="政治面貌">{record.political_status_txt}</Descriptions.Item>
                        <Descriptions.Item label="月薪要求范围">{record.salary_range_txt}</Descriptions.Item>
                        <Descriptions.Item label="审核状态">
                            <Radio.Group size='small' defaultValue={record.status} onChange={async (e) => {
                                let res = await PostJobapplicantUpdate({ customer_id: record.customer_id, id: record.id, status: e.target.value });
                                actionRef.current?.reload();
                            }}>
                                <Radio value={1}>待审</Radio>
                                <Radio value={2}>通过</Radio>
                                <Radio value={3}>不通过</Radio>
                            </Radio.Group>
                        </Descriptions.Item>
                        {
                            record.status == 3 ? <>
                                <Descriptions.Item label="不通过原因">
                                    <Input size='small' placeholder='输入原因,按回车键保存' defaultValue={record.status_txt} onPressEnter={async (e) => {
                                        let res = await PostJobapplicantUpdate({ customer_id: record.customer_id, id: record.id, status: 3, audit_memo: e.target.value });
                                        actionRef.current?.reload();
                                    }}></Input>
                                </Descriptions.Item>
                            </> : record.status_txt
                        }
                    </Descriptions>

                </Space >

            </>
        );
    };
    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' }}
                    tableAlertRender={({
                        selectedRowKeys,
                        selectedRows,
                        onCleanSelected,
                    }) => {
                        setIds(selectedRows)
                        return (
                            <Space size={24}>
                                <span>
                                    已选 {selectedRows.length} 项
                                    <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                                        取消选择
                                    </a>
                                </span>
                            </Space>
                        );
                    }}
                    tableAlertOptionRender={() => {
                        return (
                            <Space size={16}>
                                <Button  onClick={(record) => {
                                    if (ids.length === 0) {
                                        message.error('请选择要操作的数据')
                                    } else {
                                        setOpenMultieditPreview(true)
                                    }
                                }}>
                                    批量审核
                                </Button>,
                            </Space>
                        );
                    }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    expandable={{
                        expandedRowRender
                    }}
                    columns={[
                        {
                            title: '筛选日期',
                            dataIndex: 'date_range',
                            hidden: true,
                            width: 200,
                            valueType: 'dateRange',
                        },
                        {
                            title: '姓名',
                            dataIndex: 'seekername',
                            width: 200
                        }, {
                            title: '性别',
                            dataIndex: 'gender',
                            width: 200,
                            valueType: 'select',
                            valueEnum: {
                                '男': '男',
                                '女': '女'
                            }
                        }, {
                            title: '教育程度',
                            dataIndex: 'education_txt',
                            width: 200,
                            search: false
                        }, {
                            title: '教育程度',
                            dataIndex: 'education',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.educationList
                            }
                        },
                        {
                            title: '英语',
                            dataIndex: 'english',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.degreeList
                            }
                        },
                        {
                            title: '国语',
                            dataIndex: 'mandarin',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.degreeList
                            }
                        }, {
                            title: '粤语',
                            dataIndex: 'cantonese',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.degreeList
                            }
                        },
                        {
                            title: '职称',
                            dataIndex: 'title',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.titleList
                            }
                        },
                        {
                            title: '政治面貌',
                            dataIndex: 'political_status',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.politicalList
                            }
                        }, {
                            title: '月薪要求',
                            dataIndex: 'salary_range_desire',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            fieldProps: {
                                fieldNames: selectfieldNames,
                                options: dictModel.payList
                            }
                        },
                        {
                            title: '审核状态',
                            dataIndex: 'status',
                            width: 200,
                            hidden: true,
                            valueType: 'select',
                            valueEnum: {
                                0: '全部',
                                1: '待审核',
                                2: '审核通过',
                                3: '审核不通过'
                            }
                        },
                        {
                            title: '简历是否可见',
                            dataIndex: 'hide_resume',
                            width: 200,
                            search: false,
                            render: (_, record) => (<>
                                {
                                    <span>
                                        {record.hide_resume == 1 ? '可见' : '不可见'}
                                    </span>
                                }

                            </>),
                        },
                        {
                            title: '简历是否在家政模块可见',
                            dataIndex: 'house_keeping_status',
                            width: 200,
                            search: false,
                            render: (_, record) => (<>
                                {
                                    <span>
                                        {record.house_keeping_status == 1 ? '可见' : '不可见'}
                                    </span>
                                }

                            </>),
                        },
                        {
                            title: '操作',
                            key: 'option',
                            valueType: 'option',
                            render: (_, record, action) => [
                                <Button key='1' type='link' onClick={() => {
                                    setId(record)
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>编辑</Button>,
                                <Button key='2' type='link' onClick={() => {
                                    setId(record)
                                    dispatch({ type: 'openModel/getOpenResumeHelpModal', payload: true })
                                }}>工作帮扶情况</Button>,
                                <Button key='3' type='link' onClick={() => {
                                    setId(record)
                                    dispatch({ type: 'openModel/getOpenResumeDetailModal', payload: true })
                                }}>预览简历</Button>,
                                <Button key='4' type='link' onClick={() => {
                                    setId(record)
                                    dispatch({ type: 'openModel/getOpenExportModal', 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>) =>
                        PostJobseekerList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            keyword: params.seekername,
                            gender: params.gender,
                            education: params.education,
                            english: params.english,
                            mandarin: params.mandarin,
                            cantonese: params.cantonese,
                            title: params.title,
                            political_status: params.political_status,
                            salary_range_desire: params.salary_range_desire,
                            status: params.status ? Number(params.status) : 0,
                            start_date: params.date_range ? params.date_range[0] : '',
                            end_date: params.date_range ? params.date_range[1] : '',
                        }).then(res => {
                            setList(res.data.seekers)
                            setTotal(res.data.total)
                        })
                    }
                    toolBarRender={() => [
                        <Button type="primary" onClick={() => {
                            message.info('数据导出需要时间，请耐心等待')
                            PostJobseekerExport().then(res => {
                                let url = Imageprefix + res.data.excel_url;
                                window.open(url);
                                message.info('数据导出完毕')
                            })
                        }}>
                            导出数据
                        </Button>,
                        <Button type="primary" onClick={() => {
                            Modal.confirm({
                                title: '导入文件',
                                content: (<>
                                    <DragUpload form_name="doc_url" uploadTxt="导入文件"></DragUpload>
                                </>),
                                onOk() {

                                },
                                onCancel() {
                                    console.log('Cancel');
                                },
                                okText: '确定',
                                cancelText: '取消',
                                centered: true
                            });
                        }}>
                            导入数据
                        </Button >,
                    ]}
                    headerTitle="简历列表"
                />


                <Modal
                    open={openMultieditPreview}
                    title='请选择对批量数据进行何种操作'
                    centered
                    maskClosable={false}
                    destroyOnClose
                    width={400}
                    onCancel={() => {
                        setOpenMultieditPreview(false)
                    }}
                    onOk={async () => {
                        if (status) {
                            const promises = ids.map(item => {
                                return PostJobapplicantUpdate({ id: item.id, customer_id: item.customer_id, status: status, audit_memo: auditMemo });
                            });

                            // 等待所有请求完成
                            Promise.all(promises)
                                .then(() => {
                                    setOpenMultieditPreview(false);
                                    message.success('批量操作成功');
                                    actionRef.current?.clearSelected();
                                    actionRef.current?.reload();
                                })
                                .catch(error => {
                                    console.error('批量操作失败:', error);
                                    message.error('批量操作失败');
                                });

                        } else {
                            message.error('请完成表单')
                            return false
                        }
                    }
                    }
                >
                    <Flex vertical justify='center' style={{ minHeight: 100 }}>
                        <Space direction='vertical'>
                            <h4 style={{ fontWeight: 'bold' }}>状态：</h4>
                            <Radio.Group size='small' value={status} onChange={(e) => {
                                setStatus(e.target.value)
                            }}>
                                <Radio value={1}>待审核</Radio>
                                <Radio value={2}>审核通过</Radio>
                                <Radio value={3}>审核不通过</Radio>
                            </Radio.Group>
                            {
                                status === 3 && (
                                    <>
                                        <h4>如不通过请输入原因,按回车键保存，也可不填</h4>
                                        <Input style={{ width: '100%' }} placeholder='此处不通过原因' onChange={(e) => {
                                            setAuditMemo(e.target.value)
                                        }}></Input>
                                    </>
                                )
                            }

                        </Space>
                    </Flex>
                </Modal >
            </ConfigProvider>

        </>



    );
};


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