




import { useRef, useState, useEffect } from 'react';
import { connect, history, Link } from '@umijs/max';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import {
    ProTable, ProFormRadio, ProForm
} from '@ant-design/pro-components';

import { Button, Image, ConfigProvider, Select, message, Descriptions, Space, Radio, Modal, Flex, Row, Col, Badge } from 'antd';
import { getCompanyList, GetCompanyInfo, updateCompany, PostCompanyExport, PostCompanyEdit, PostCompanyMultieditstatus } from '@/apis/api';
import { Imageprefix } from '@/constants';

import DragUpload from '@/components/Common/dragupload';

import UploadModel from '@/components/Common/upload';


const PagesMainCompanyListTable: React.FC = ({ dispatch, openModel, getId }: 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 [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([])
    const [openMultieditPreview, setOpenMultieditPreview] = useState(false);
    const [ids, setIds] = useState<number[]>([])
    const [status, setStatus] = useState<number>(1)



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

    const [addButton, setAddButton] = useState<boolean>(true)
    const [editButton, setEditButton] = useState<boolean>(true)

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


    const [uploadedFilephotoName, setUploadedFilephotoName] = useState<string>('');
    const uploadedFilephotoNameRef = useRef<string>('');
    const handleFileUploadedphoto = (filename: string) => {
        setUploadedFilephotoName(filename);
    };

    useEffect(() => {
        uploadedFilephotoNameRef.current = uploadedFilephotoName;
    }, [uploadedFilephotoName])


    const [uploadedFilelicenseName, setUploadedFilelicenseName] = useState<string>('');
    const uploadedFilelicenseNameRef = useRef<string>('');
    const handleFileUploadedlicense = (filename: string) => {
        setUploadedFilelicenseName(filename);
    };

    useEffect(() => {
        uploadedFilelicenseNameRef.current = uploadedFilelicenseName;
    }, [uploadedFilelicenseName])
    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.establishment_date}</Descriptions.Item>
                        <Descriptions.Item label="来源">{record.origin_text}</Descriptions.Item>
                        <Descriptions.Item label="登录次数">{record.login_count}</Descriptions.Item>
                        <Descriptions.Item label="点击次数">{record.click_count}</Descriptions.Item>
                        <Descriptions.Item label="企业照片">
                            <Space align='center'>
                                <Image src={`${Imageprefix}${record.photo}`} width={60} height={60} />
                                <Button size='small' type='primary' onClick={() => {
                                    Modal.confirm({
                                        title: '更换企业照片',
                                        content: (<>
                                            <ProForm submitter={{ render: false }}>
                                                <UploadModel multiple={false} form_name="photo" image_length={1} uploadTxt="更换企业照片" image_type={3} imageUrl={record.photo} onUploadComplete={handleFileUploadedphoto}></UploadModel>
                                            </ProForm>
                                        </>),
                                        async onOk() {
                                            let info = await GetCompanyInfo({ id: record.id });
                                            let res = await updateCompany({ ...info.data, photo: uploadedFilephotoNameRef.current });
                                            setUploadedFilephotoName('');
                                            actionRef.current?.reload();
                                        },
                                        onCancel() {
                                            console.log('Cancel');
                                        },
                                        okText: '保存',
                                        cancelText: '取消',
                                        centered: true,
                                    });
                                }}>更换企业照片</Button>
                            </Space>
                        </Descriptions.Item>
                        <Descriptions.Item label="照片审核">
                            <Radio.Group value={record.photo_status} size='small' onChange={async (e) => {
                                let info = await GetCompanyInfo({ id: record.id });
                                let res = await updateCompany({ ...info.data, photo_status: e.target.value });
                                actionRef.current?.reload();
                            }}>
                                <Radio value={1}>待审</Radio>
                                <Radio value={2}>通过</Radio>
                                <Radio value={3}>不通过</Radio>
                            </Radio.Group>
                        </Descriptions.Item>
                        <Descriptions.Item label="登录账号">{record.login_name}</Descriptions.Item>

                        <Descriptions.Item label="营业执照">
                            <Space align='center'>
                                <Image src={`${Imageprefix}${record.license_path}`} width={60} height={60} />
                                <Button size='small' type='primary' onClick={() => {
                                    Modal.confirm({
                                        title: '更换营业执照',
                                        content: (<>
                                            <ProForm submitter={{ render: false }}>
                                                <UploadModel multiple={false} form_name="license_path" image_length={1} uploadTxt="更换营业执照" image_type={3} imageUrl={record.license_path} onUploadComplete={handleFileUploadedlicense}></UploadModel>
                                            </ProForm>
                                        </>),
                                        async onOk() {
                                            let info = await GetCompanyInfo({ id: record.id });
                                            let res = await updateCompany({ ...info.data, license_path: uploadedFilelicenseNameRef.current });
                                            setUploadedFilelicenseName('');
                                            actionRef.current?.reload();
                                        },
                                        onCancel() {
                                            console.log('Cancel');
                                        },
                                        okText: '保存',
                                        cancelText: '取消',
                                        centered: true,
                                    });
                                }}>更换营业执照</Button>
                            </Space>
                        </Descriptions.Item>
                        <Descriptions.Item label="营业执照审核">
                            <Radio.Group value={record.photo_status} size='small' onChange={async (e) => {
                                let info = await GetCompanyInfo({ id: record.id });
                                let res = await updateCompany({ ...info.data, license_status: e.target.value });
                                actionRef.current?.reload();
                            }}>
                                <Radio value={1}>待审</Radio>
                                <Radio value={2}>通过</Radio>
                                <Radio value={3}>不通过</Radio>
                            </Radio.Group>
                        </Descriptions.Item>
                    </Descriptions>
                    <Descriptions title="会员信息" bordered column={3} contentStyle={{ fontWeight: 'bold' }} labelStyle={{ width: 180 }}>
                        <Descriptions.Item label="会员类型">
                            {
                                record.member_type_text && <Button type="primary" size='small' onClick={() => {
                                    sessionStorage.setItem('vip_company_info', JSON.stringify(record))
                                    history.push({
                                        pathname: '/company/vip'
                                    })
                                }}>
                                    {record.member_type_text}
                                </Button>
                            }
                        </Descriptions.Item>
                        <Descriptions.Item label="开始时间">
                            {record.start_date}
                        </Descriptions.Item>
                        <Descriptions.Item label="到期时间">
                            {record.end_date}
                        </Descriptions.Item>
                        <Descriptions.Item label="剩余点数">
                            {record.code}
                        </Descriptions.Item>
                        <Descriptions.Item label="会员状态">
                            {
                                record.member_status === 2 ? <Badge status="processing" text={record.member_status_text} /> : <Badge status="error" text={record.member_status_text} />
                            }

                        </Descriptions.Item>

                    </Descriptions>
                </Space >

            </>
        );
    };

    return (
        <>
            <ConfigProvider
                theme={{
                    token: {
                        colorPrimary: '#4FBE70',
                        colorLink: '#4FBE70',
                    },
                    components: {
                        Descriptions: {
                            labelBg: '#ffffff',
                            contentColor: '#000'
                        },

                    }
                }}
            >
                <ProTable
                    size='small'
                    scroll={{ y: 480, x: 'auto' }}
                    bordered={true}
                    actionRef={actionRef}
                    dataSource={list}
                    search={{ span: 6, 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={() => {
                        return (
                            <Space size={16}>
                                <Button onClick={() => {
                                    if (ids.length === 0) {
                                        message.error('请选择要操作的数据')
                                    } else {
                                        setOpenMultieditPreview(true)
                                    }
                                }}>
                                    批量管理账号
                                </Button>,
                            </Space>
                        );
                    }}
                    rowSelection={{
                        type: 'checkbox'
                    }}
                    expandable={{
                        expandedRowRender
                    }}

                    columns={[
                        {
                            title: '筛选日期',
                            dataIndex: 'date_range',
                            hidden: true,
                            valueType: 'dateRange',
                            search: {
                                transform: (value) => {
                                    return {
                                        start_date: value[0],
                                        end_date: value[1],
                                    };
                                },
                            },
                            width: 200
                        },
                        {
                            title: 'ID',
                            dataIndex: 'id',
                            width: 200
                        },
                        {
                            title: '企业名称',
                            dataIndex: 'full_name',
                            width: 200
                        },
                        {
                            title: '社会统一信用代码',
                            dataIndex: 'registration_number',
                            width: 200,
                            search: false
                        },
                        {
                            title: '性质',
                            dataIndex: 'nature_text',
                            width: 200,
                            search: false
                        },
                        {
                            title: '规模',
                            dataIndex: 'scale_text',
                            width: 200,
                            search: false
                        },
                        {
                            title: '账号状态',
                            dataIndex: 'status',
                            width: 200,
                            render: (_, record) => (<>
                                <Radio.Group size='small' value={record.status} onChange={async (e) => {

                                    actionRef.current?.reload();
                                }}>
                                    <Radio value={1}>开通</Radio>
                                    <Radio value={2}>关闭</Radio>
                                </Radio.Group>
                            </>),
                            valueType: 'select',
                            valueEnum: {
                                0: { text: '全部' },
                                1: {
                                    text: '开通',
                                    status: 'Processing'
                                },
                                2: {
                                    text: '关闭',
                                    status: 'Error'
                                },
                            },
                        },
                        {
                            title: '会员类型',
                            dataIndex: 'member_type',
                            width: 100,
                            hidden: true,
                            valueType: 'select',
                            valueEnum: {
                                0: { text: '全部' },
                                1: {
                                    text: '试用申请中',
                                },
                                2: {
                                    text: '试用正式',
                                },
                                3: {
                                    text: '普通申请中',
                                },
                                4: {
                                    text: '普通正式',
                                },
                                5: {
                                    text: 'VIP申请中',
                                },
                                6: {
                                    text: 'VIP正式',
                                },
                            },
                        },
                        {
                            title: '操作',
                            key: 'option',
                            valueType: 'option',
                            render: (_, record, action) => [
                                <>
                                    {
                                        editButton && <Button key='1' type='link' onClick={() => {
                                            setId(record.id)
                                            dispatch({ type: 'openModel/getOpenModal', payload: true })
                                        }}>编辑</Button>
                                    }
                                </>,
                                <Button key='2' type='link' onClick={() => {
                                    GetCompanyInfo({ id: record.id }).then(res => {
                                        sessionStorage.setItem('company_info', JSON.stringify(res.data))
                                        history.push({
                                            pathname: '/company/department'
                                        })
                                    })
                                }}>企业部门</Button>,
                                <Button key='3' type='link' onClick={() => {
                                    GetCompanyInfo({ id: record.id }).then(res => {
                                        sessionStorage.setItem('post_company_info', JSON.stringify(res.data))
                                        history.push({
                                            pathname: '/company/post'
                                        })
                                    })
                                }}>企业职位</Button>,
                                <Button key='4' type='link' onClick={() => {
                                    sessionStorage.setItem('vip_company_info', JSON.stringify(record))
                                    history.push({
                                        pathname: '/company/vip'
                                    })
                                }}>会员信息</Button>,
                                <Button key='5' type='link' onClick={() => {
                                    setId(record.id)
                                    dispatch({ type: 'openModel/getOpenBindModal', 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>) =>
                        getCompanyList({
                            page: page,
                            pagesize: pageSize,
                            sort: 'id',
                            sortby: 'desc',
                            id: params.id,
                            keyword: params.full_name,
                            login_name: params.login_name,
                            member_type: params.member_type,
                            member_status: params.member_status,
                            status: params.status,
                            start_date: params.start_date,
                            end_date: params.end_date,
                        }).then(res => {
                            setList(res.data.list)
                            setTotal(res.data.total)
                        })
                    }
                    headerTitle="企业列表"
                    toolBarRender={() => [

                        <Button type="primary" onClick={() => {
                            message.info('数据导出需要时间，请耐心等待')
                            PostCompanyExport().then(res => {
                                let url = Imageprefix + res.data.excel_url;
                                window.open(url);
                                message.info('数据导出完毕')
                            })
                        }}>
                            导出数据
                        </Button>,
                        <>
                            {
                                addButton && <Button type="primary" onClick={() => {
                                    dispatch({ type: 'openModel/getOpenModal', payload: true })
                                }}>
                                    添加企业
                                </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 >,
                    ]}
                />

                <Modal
                    open={openMultieditPreview}
                    title='请选择对批量数据进行何种操作'
                    centered
                    maskClosable={false}
                    destroyOnClose
                    width={400}
                    onCancel={() => {
                        setOpenMultieditPreview(false)
                    }}
                    onOk={() => {
                        if (status) {
                            PostCompanyMultieditstatus({ ids: ids, status: status }).then(res => {
                                setOpenMultieditPreview(false)
                                actionRef.current?.clearSelected();
                                actionRef.current?.reload();
                            })
                        } else {
                            message.error('请选择状态')
                            return false
                        }
                    }
                    }
                >
                    <Flex justify='center' align='center' style={{ minHeight: 100 }}>
                        <Radio.Group size='small' value={status} onChange={(e) => {
                            setStatus(e.target.value)
                        }} options={[
                            { value: 1, label: '开通账号' },
                            { value: 2, label: '关闭账号' }
                        ]} >
                            {/* <Row gutter={[20, 20]} style={{ padding: 20 }}>
                                                <Col span={12}>
                                                    <Radio value={1}>开通账号</Radio>
                                                </Col>
                                                <Col span={12}>
                                                    <Radio value={2}>关闭账号</Radio>
                                                </Col>
                                                {/* <Col span={12}>
                                                    <Radio value={3}>禁用1天</Radio>
                                                </Col>
                                                <Col span={12}>
                                                    <Radio value={4}>禁用3天</Radio>
                                                </Col>
                                                <Col span={12}>
                                                    <Radio value={5}>禁用7天</Radio>
                                                </Col>
                                                <Col span={12}>
                                                    <Radio value={6}>禁用15天</Radio>
                                                </Col>
                                                <Col span={12}>
                                                    <Radio value={7}>禁用30天</Radio>
                                                </Col>
                                                <Col span={12}>
                                                    <Radio value={8}>永久禁用</Radio>
                                                </Col> 
                                            </Row> */}
                        </Radio.Group>
                    </Flex>

                </Modal >
            </ConfigProvider >
        </>
    );
};


export default connect(({ openModel }: any) => ({
    openModel
}))(PagesMainCompanyListTable);