import React, { Component } from'react';
import { Form, Input, Button, Table, Select, message, Modal } from 'antd';
import { delExamPaper, getList, upPaperStatus } from 'api/examPaper';
import { findIndustry } from 'api/question';

const { Option } = Select;

interface States {
    num: number;
    page: number;
    total: number;
    list: any[];
    loading: boolean;
    industryDict: any;
    selectedRowKeys: number[];
}

class ExamPaperList extends Component<any, States> {
    formRef: any;

    constructor(props: any) {
        super(props);
        this.formRef = React.createRef();
        this.state = {
            num: 10,
            page: 1,
            total: 0,
            list: [],
            loading: false,
            industryDict: [],
            selectedRowKeys: [],
        };
    }

    componentDidMount() {
        this.handleFindIndustry();
        const savedFormValues = sessionStorage.getItem('examPaperListFormValues');
        if (savedFormValues) {
            const values = JSON.parse(savedFormValues);
            this.formRef.current.setFieldsValue(values);
        }
        this.handlegetList('def');
    }

    // 字典
    handleFindIndustry() {
        findIndustry().then((res: any) => {
            if (res.data) {
                this.setState({ industryDict: res.data });
            }
        });
    }

    // 查询
    handlegetList(stat: string) {
        this.setState({ loading: true });
        const values = this.formRef.current.getFieldsValue();
        const { num, page } = this.state;
        const data = {
            ...values,
            num,
            page : stat && stat === 'init' ? 1 : page
        };
        this.setState({ page: data.page, num: data.num });
        sessionStorage.setItem('examPaperListFormValues', JSON.stringify(values));
        getList(data).then((res) => {
            this.setState({
                list: res.data.data,
                total: res.data.total,
                selectedRowKeys: [],
            });
        })
            .catch(() => {
                message.error('获取数据失败');
            })
            .finally(() => {
                this.setState({ loading: false });
            });
    }

    // 重置
    handleReset = () => {
        sessionStorage.removeItem('examPaperListFormValues');
        this.formRef.current.resetFields();
    };

    // 删除问题
    handleDeleteExamPaper = (id: number) => {
        Modal.confirm({
            title: '确认删除',
            content: '你确定要删除这个试卷吗?',
            onOk: () => {
                const idList = [id];
                delExamPaper(idList).then((res) => {
                    const success = res.data.success;
                    const info = res.data.message;
                    if (success === "true") {
                        message.success('删除成功');
                        this.handlegetList('def');
                    } else if (success === "error") {
                        Modal.confirm({
                            content: info,
                            cancelButtonProps: { style: { display: 'none' } },
                            onOk: () => {return}
                        });
                    } else {
                        message.error('删除失败,请稍后重试');
                    }
                }).catch(() => {
                    message.error('删除时发生错误,请检查');
                });
            },
            onCancel: () => {
            },
        });
    };

    // 批量删除问题
    handleBatchDeleteExamPaper = () => {
        const { selectedRowKeys } = this.state;
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的试卷');
            return;
        }
        Modal.confirm({
            title: '确认删除',
            content: '你确定要删除这些选中的试卷吗?',
            onOk: () => {
                delExamPaper(selectedRowKeys)
                    .then((res) => {
                        const success = res.data.success;
                        const info = res.data.message;
                        if (success === "true") {
                            message.success('删除成功');
                            this.handlegetList('def');
                        } else if (success === "error") {
                            Modal.confirm({
                                content: info,
                                cancelButtonProps: { style: { display: 'none' } },
                                onOk: () => {return}
                            });
                        } else {
                            message.error('删除失败,请稍后重试');
                        }
                    })
                    .catch(() => {
                        message.error('删除时发生错误,请检查');
                    });
            },
            onCancel: () => {
            },
        });
    };

    // 行选择
    handleOnChange = (selectedRowKeys: React.Key[]) => {
        this.setState({
            selectedRowKeys: selectedRowKeys as number[],
        });
    };

    // 更新试卷状态
    handleUpdatePaperStatus = (id: number, paperStatus: number) => {
        const newStatus = paperStatus === 0? 1 : 0;
        const newStatusText = paperStatus === 0? '启用' : '停用';
        const idList = [id];
        Modal.confirm({
            title: `确认${newStatusText}`,
            content: `你确定要${newStatusText}这个试卷吗?`,
            onOk: () => {
                upPaperStatus(idList, newStatus).then((res) => {
                    const success = res.data.success;
                    const info = res.data.message;
                    if (success === "true") {
                        message.success(`${newStatusText}成功`);
                        this.setState((prevState) => ({
                            list: prevState.list.map((item) =>
                                item.id === id? { ...item, paperStatus: newStatus } : item
                            )
                        }));
                    } else if (success === "error") {
                        Modal.confirm({
                            content: info,
                            cancelButtonProps: { style: { display: 'none' } },
                            onOk: () => {return}
                        });
                    } else {
                        message.error(`${newStatusText}失败,请稍后重试`);
                    }
                }).catch(() => {
                    message.error(`${newStatusText}时发生错误,请检查`);
                });
            },
            onCancel: () => {
            },
        });
    };

    // 批量更新试卷状态
    handleBatchUpdatePaperStatus = (paperStatus: number) => {
        const newStatus = paperStatus === 0? 1 : 0;
        const newStatusText = paperStatus === 0? '启用' : '停用';
        const { selectedRowKeys } = this.state;
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要操作的试卷');
            return;
        }

        Modal.confirm({
            title: `确认${newStatusText}`,
            content: `你确定要${newStatusText}这些选中的试卷吗?`,
            onOk: () => {
                upPaperStatus(selectedRowKeys, newStatus)
                    .then((res) => {
                        const success = res.data.success;
                        const info = res.data.message;
                        if (success === "true") {
                            message.success(`${newStatusText}成功`);
                            this.setState((prevState) => ({
                                list: prevState.list.map((item) =>
                                    selectedRowKeys.includes(item.id)
                                        ? { ...item, paperStatus: newStatus } : item
                                )
                            }));
                        } else if (success === "error") {
                            Modal.confirm({
                                content: info,
                                cancelButtonProps: { style: { display: 'none' } },
                                onOk: () => {return}
                            });
                        } else {
                            message.error(`${newStatusText}失败,请稍后重试`);
                        }
                    })
                    .catch(() => {
                        message.error(`${newStatusText}时发生错误,请检查`);
                    });
            },
            onCancel: () => {
            },
        });
    };

    render() {
        const {
            industryDict,
            selectedRowKeys,
            list,
            loading,
            page,
            num
        } = this.state;

        const changePage = (current: number, pageSize: number) => {
            setTimeout(() => {
                this.setState({ page: current, num: pageSize });
                this.handlegetList('def');
            }, 0);
        };

        const columns: any = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                align: 'center',
                width: 60,
                render: (_: number, __: number, index: number) => {
                    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: any) => 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,
                render: (examDuration: any, record: any) => {
                    const unit = String(record.durationType) === '1'? '分(min)' : '时(h)';
                    return `${examDuration} ${unit}`;
                }
            },
            {
                title: '状态',
                dataIndex: 'paperStatus',
                key: 'paperStatus',
                align: 'center',
                width: 60,
                render: (paperStatus: any) => {
                    return paperStatus === 0? '停用' : '启用';
                }
            },
            {
                title: '操作',
                key: 'operation',
                align: 'center',
                fixed: 'right',
                width: 200,
                render: (record: any) => [
                    <span className='mr10 link' onClick={() => {
                        sessionStorage.setItem('id', String(record.id));
                        sessionStorage.setItem('isEdit', "true");
                        this.props.history.push(`/examPaperAdd`);
                    }}>编辑</span>,
                    <span className='mr10 link' onClick={() => {
                        sessionStorage.setItem('id', String(record.id));
                        this.props.history.push(`/examPaperView`);
                    }}>预览</span>,
                    <span className='mr10 link' onClick={() => {
                        this.handleUpdatePaperStatus(record.id, record.paperStatus);
                    }}>{record.paperStatus === 0? '启用' : '停用'}</span>,
                    <span className="mr10 link" onClick={() => {
                        this.handleDeleteExamPaper(record.id);
                    }}>删除</span>
                ]
            },
        ];

        return (
            <div className="container">
                <div>
                    <div className="header-filter">
                        <div className="list-filter" style={{display: 'flex', padding: 15}}>
                            <Form
                                ref={this.formRef}
                                className="filter"
                                layout="inline"
                            >
                            <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" onClick={() => {
                                    this.handlegetList('init');
                                }}>查询</Button>
                            </Form.Item>
                        </Form>
                        </div>
                    </div>
                    <Form
                        className="filter"
                        layout="inline"
                        style={{ justifyContent: 'flex-end' }}
                    >
                        <Form.Item>
                            <Button type="default" onClick={this.handleBatchDeleteExamPaper} danger>删除</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" onClick={() => this.handleBatchUpdatePaperStatus(1)}>停用</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" onClick={() => this.handleBatchUpdatePaperStatus(0)}>启用</Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" onClick={() => { this.props.history.push(`/examPaperAdd`); }}>新增试卷</Button>
                        </Form.Item>
                    </Form>
                    <Table
                        dataSource={list}
                        columns={columns}
                        rowKey="id"
                        bordered={true}
                        size={'small'}
                        loading={loading}
                        scroll={{ y: 500 }}
                        rowSelection={{
                            selectedRowKeys: selectedRowKeys,
                            onChange: this.handleOnChange,
                            getCheckboxProps: () => ({
                                disabled: false
                            })
                        }}
                        pagination={{
                            total: this.state.total,
                            current: this.state.page,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            showTotal: (total) => `共 ${total} 条`,
                            onChange: changePage
                        }}
                    />
                </div>
            </div>
        );
    }
}
export default ExamPaperList;