import React, { Component } from'react';
import {Form, Input, Button, Table, Select, message, Modal} from 'antd';
import { TableRowSelection } from 'antd/lib/table/interface';
import {deleteSingle, deleteMultiple, findIndustry, getList} from 'api/examPaper';

const { Option } = Select;

interface States {
    num: number;
    page: number;
    listQuery: {
        industryId: string | undefined;
        paperName: string | undefined;
    };
    list: any[];
    total: number;
    loading: boolean;
    currentRow: object;
    title: string;
    modalText: string;
    modalWidth: number | string;
    industryDict: any;
    serviceTypeDict: any;
    selectedRowKeys: number[];
    isAllSelected: boolean;
}

class ExamPaperList extends Component<any, States> {
    formRef: any;
    constructor(props: any) {
        super(props);
        this.formRef = React.createRef();
        this.state = {
            num: 10,
            page: 1,
            listQuery: {
                industryId: undefined,
                paperName: undefined
            },
            list: [],
            total: 0,
            loading: false,
            currentRow: {
                id: 0,
                status: 0
            },
            title: '',
            modalText: '',
            modalWidth: 0,
            industryDict: undefined,
            serviceTypeDict: undefined,
            selectedRowKeys: [],
            isAllSelected: false,
        };
    }

    componentDidMount() {
        this.findIndustry();
    }

    // 监管行业
    findIndustry() {
        findIndustry().then((res: any) => {
            if (res.data) {
                this.setState({ industryDict: res.data });
            }
        });
    }

    // 查询
    getList() {
        this.setState({ loading: true });
        const { num, page, listQuery } = this.state;
        getList(num, page, listQuery).then((res) => {
            this.setState({
                loading: false,
                list: res.data.data,
                total: res.data.total,
                selectedRowKeys: [],
                isAllSelected: false,
            });
            this.setState({ loading: false });
        }).catch(() => {
            this.setState({ loading: false });
        });
    }

    // 重置
    handleReset = () => {
        if (this.formRef.current) {
            // 重置表单字段
            this.formRef.current.resetFields();
            // 重置 listQuery 状态
            this.setState({
                listQuery: {
                    industryId: undefined,
                    paperName: undefined
                },
                selectedRowKeys: [],
                isAllSelected: false,
            });
        }
    };

    // 删除（明细）
    deleteSingle = (id: number) => {
        Modal.confirm({
            title: '确认删除',
            content: '你确定要删除这个问题吗？',
            onOk: () => {
                deleteSingle(id).then((res) => {
                    const isSuccess = res.data;
                    if (isSuccess) {
                        message.success('删除成功');
                        this.getList();
                    } else {
                        message.error('删除失败，请稍后重试');
                    }
                }).catch(() => {
                    message.error('删除时发生错误，请检查');
                });
            },
            onCancel: () => {
            },
        });
    };

    // 删除
    deleteMultiple = () => {
        const { selectedRowKeys } = this.state;
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的问题');
            return;
        }
        Modal.confirm({
            title: '确认删除',
            content: '你确定要删除这些选中的问题吗？',
            onOk: () => {
                deleteMultiple(selectedRowKeys)
                    .then((res) => {
                        const isSuccess = res.data;
                        if (isSuccess) {
                            message.success('删除成功');
                            this.getList();
                        } else {
                            message.error('删除失败，请稍后重试');
                        }
                    })
                    .catch(() => {
                        message.error('删除时发生错误，请检查');
                    });
            },
            onCancel: () => {
            },
        });
    };

    // 多选
    onSelectChange = (selectedRowKeys: React.Key[]) => {
        this.setState({
            selectedRowKeys: selectedRowKeys as number[],
            isAllSelected: selectedRowKeys.length === this.state.list.length
        });
    };

    // 单选
    onSelect = (record: any, selected: boolean) => {
        if (selected) {
            // 单选时只保留当前选中行
            this.setState({
                selectedRowKeys: [record.id],
                isAllSelected: false
            });
        } else {
            // 取消选中时清空选中行
            this.setState({
                selectedRowKeys: [],
                isAllSelected: false
            });
        }
    };

    render() {
        const onFinish = (values: object) => {
            const _listQuery = { ...this.state.listQuery, ...values };
            this.setState({ listQuery: _listQuery });
            this.getList();
        };

        const { industryDict, selectedRowKeys } = this.state;

        // 行选择
        const rowSelection: TableRowSelection<any> = {
            selectedRowKeys,
            onChange: this.onSelectChange,
            onSelect: this.onSelect,
            getCheckboxProps: (record) => ({
                checked: selectedRowKeys.includes(record.id),
                indeterminate: selectedRowKeys.includes(record.id),
            })
        };

        // 页面跳转
        const handleAddQuestion = () => {
            this.props.history.push('/questionAdd');
        };

        const columns: any = [
            { title: '序号', dataIndex: 'index', key: 'index', align: 'center', width: 60,
                render: (_: number, __: number, index: number) => {
                    const { page, num } = this.state;
                    return (page - 1) * num + index + 1;
                }
            },
            { title: '试卷名称', dataIndex: 'paperName', key: 'paperName', align: 'center', width: 300 },
            { title: '监管行业', dataIndex: 'industryId', key: 'industryId', align: 'center', width: 150,
                render: (industryId:any) => {
                    const industry = industryDict?.find((item: { industryId: string | number; industryName: string }) => String(item.industryId) === String(industryId));
                    return industry? industry.industryName : industryId;
                }
            },
            { title: '题目数量', dataIndex: 'questionCount', key: 'questionCount', align: 'center', width: 120 },
            { title: '总分值', dataIndex: 'totalScore', key: 'totalScore', align: 'center', width: 90 },
            { title: '考试时长', dataIndex: 'examDuration', key: 'examDuration', align: 'center', width: 120 },
            { title: '状态', dataIndex: 'paperStatus', key: 'paperStatus', align: 'center', width: 60,
                render: (paperStatus:any) => {
                    if (paperStatus === 0) {
                        return '禁用';
                    } else if (paperStatus === 1) {
                        return '启用';
                    }
                    return paperStatus;}
            },
            { title: '操作', key: 'operation', align: 'center', fixed: 'right', width: 200,
                render: (record: any) => [
                    <span className='mr10 link' onClick={() => {
                        this.setState({title: '删除', modalWidth: '85%'})
                        this.props.history.push(`/questionUp/${record.id}`);
                    }}>编辑</span>,
                    <span className='mr10 link' onClick={() => {
                        this.setState({title: '预览', modalWidth: '85%'})
                        this.deleteSingle(record.id);
                    }}>预览</span>,
                    <span className='mr10 link' onClick={() => {
                        this.setState({title: '停用', modalWidth: '85%'})
                        this.deleteSingle(record.id);
                    }}>停用</span>,
                    <span className="mr10 link" onClick={() => {
                        this.setState({title: '停用', modalWidth: '85%'})
                        this.deleteSingle(record.id);
                    }}>删除</span>
                ]
            },
        ];

        // 分页切换
        const changePage = (current: number, pageSize?: number) => {
            setTimeout(() => {
                this.setState({page: current, num: pageSize || 20});
                this.getList();
            }, 0);
        };

        // 多少每页
        const selectChange = (page: number, num: number) => {
            this.setState({ page, num });
            this.getList();
        };

        const { list, loading } = this.state;

        return (
            <div className="container">
                <div className="list-filter">
                    <Form
                        ref={this.formRef}
                        className="filter"
                        layout="inline"
                        name="basic"
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="监管行业："
                            name="industryId"
                        >
                            <Select placeholder="请选择监管行业"
                                    style={{ width: 240 }}
                                    allowClear>
                                {
                                    industryDict && industryDict.length > 0?
                                        (() => {
                                            let rows = [];
                                            for (let i = 0; i < industryDict.length; i++) {
                                                const item = industryDict[i];
                                                rows.push(
                                                    <Option value={item.industryId}>{item.industryName}</Option>
                                                );
                                            }
                                            return rows;
                                        })()
                                        :
                                        <Option disabled>暂无数据</Option>
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="试卷名称："
                            name="paperName"
                        >
                            <Input placeholder="请输入试卷名称" style={{ width: 240 }}/>
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" onClick={this.handleReset}>重置</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">查询</Button>
                        </Form.Item>
                    </Form>
                </div>
                <Form
                    className="filter"
                    layout="inline"
                    name="basic"
                    onFinish={onFinish}
                    style={{ display: 'flex', justifyContent: 'flex-end' }}
                >
                    <Form.Item>
                        <Button type="default" onClick={this.deleteMultiple}>删除</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="default" onClick={this.deleteMultiple}>停用</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="default" onClick={this.deleteMultiple}>启用</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={handleAddQuestion}>新增试卷</Button>
                    </Form.Item>
                </Form>
                <Table
                    dataSource={list}
                    columns={columns}
                    rowKey="id"
                    loading={loading}
                    scroll={{ y: '400px' }}
                    pagination={{
                        total: this.state.total,
                        current: this.state.page,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        showTotal: (total) => `共 ${total} 条`,
                        onShowSizeChange: selectChange,
                        onChange: changePage
                    }}
                    rowSelection={rowSelection}
                />
            </div>
        );
    }
}

export default ExamPaperList;