import React, { Component } from'react';
import { Form, Input, Button, Table, Select, message, Modal } from 'antd';
import { delQuestion, findIndustry, getList } from 'api/question';
import { dictionary } from "api/dict/index";

const { Option } = Select;

interface States {
    num: number;
    page: number;
    total: number;
    listQuery: {
        industryId: string;
        serviceTypeId: string;
        questionContent: string;
    };
    list: any[];
    loading: boolean;
    industryDict: any;
    serviceTypeDict: any;
    selectedRowKeys: number[];
}

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

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

    componentDidMount() {
        this.findDict();
        this.getList();
    }

    // 字典
    findDict() {
        // 监管行业
        findIndustry()
            .then((res: any) => {
                if (res.data) {
                    this.setState({ industryDict: res.data });
                }
            })
            .catch(() => {
                message.error('获取监管行业字典数据失败，请稍后重试');
            });
        // AQ服务类型
        dictionary('serviceTypeDict')
            .then((res) => {
                if (res.data) {
                    this.setState({ serviceTypeDict: res.data });
                }
            })
            .catch(() => {
                message.error('获取AQ服务类型字典数据失败，请稍后重试');
            });
    }

    // 查询
    getList() {
        this.setState({ loading: true });
        const { num, page, listQuery } = this.state;
        getList(num, page, listQuery)
            .then((res) => {
                this.setState({
                    list: res.data.data,
                    total: res.data.total,
                    selectedRowKeys: [],
                });
            })
            .catch(() => {
                message.error('获取数据失败');
            })
            .finally(() => {
                this.setState({ loading: false });
            });
    }

    // 重置
    handleReset = () => {
        this.formRef.current.resetFields();
        this.setState({
            listQuery: {
                industryId: '',
                serviceTypeId: '',
                questionContent: '',
            },
        });
    };

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

    // 批量删除问题
    handleBatchDeleteQuestions = () => {
        const { selectedRowKeys } = this.state;

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

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

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

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

        const {
            industryDict,
            serviceTypeDict,
            selectedRowKeys,
            list,
            loading,
            page,
            num
        } = this.state;
        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: '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: 'AQ服务类型',
                dataIndex: 'serviceTypeId',
                key: 'serviceTypeId',
                align: 'center',
                width: 150,
                render: (serviceTypeId: any) => {
                    const serviceType = serviceTypeDict?.find((item: any) => item.dictKey === serviceTypeId);
                    return serviceType? serviceType.dictValue : serviceTypeId;
                }
            },
            {
                title: '题型',
                dataIndex: 'questionTypes',
                key: 'questionTypes',
                align: 'center',
                width: 80,
                render: (questionTypes: any) => {
                    return questionTypes === 1? '单选题' : '多选题';
                }
            },
            {
                title: '题干',
                dataIndex: 'questionContent',
                key: 'questionContent',
                align: 'center',
                width: 450
            },
            {
                title: '答案',
                dataIndex: 'answer',
                key: 'answer',
                align: 'center',
                width: 120
            },
            {
                title: '操作',
                key: 'operation',
                align: 'center',
                fixed: 'right',
                width: 120,
                render: (record: any) => [
                    <span className='mr10 link' onClick={() => {
                        this.handleDeleteQuestion(record.id);
                    }}>删除</span>,
                    <span className="mr10 link" onClick={() => {
                        sessionStorage.setItem('id', String(record.id));
                        this.props.history.push(`/questionEdit`);
                    }}>修正</span>
                ]
            },
        ];

        return (
            <div className="list-filter">
                <Form
                    ref={this.formRef}
                    className="filter"
                    layout="inline"
                    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="AQ服务类型："
                        name="serviceTypeId"
                    >
                        <Select
                            placeholder="请选择AQ服务类型"
                            style={{ width: 240 }}
                            allowClear
                        >
                            {
                                serviceTypeDict && serviceTypeDict.length > 0?
                                    (() => {
                                        let rows = [];
                                        for (let i = 0; i < serviceTypeDict.length; i++) {
                                            const item = serviceTypeDict[i];
                                            rows.push(
                                                <Option value={item.dictKey}>{item.dictValue}</Option>
                                            );
                                        }
                                        return rows;
                                    })()
                                    :
                                    <Option disabled>暂无数据</Option>
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="题干条件："
                        name="questionContent"
                    >
                        <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>
                <Form
                    className="filter"
                    layout="inline"
                    style={{ justifyContent: 'flex-end' }}
                >
                    <Form.Item>
                        <Button type="default" onClick={this.handleBatchDeleteQuestions}>删除</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={() => {
                            this.props.history.push('/questionAdd');
                        }}>新增试题</Button>
                    </Form.Item>
                </Form>
                <Table
                    dataSource={list}
                    columns={columns}
                    rowKey="id"
                    loading={loading}
                    rowSelection={{
                        selectedRowKeys: selectedRowKeys,
                        onChange: this.onChange,
                        getCheckboxProps: () => ({
                            disabled: false
                        })
                    }}
                    pagination={{
                        total: this.state.total,
                        current: this.state.page,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        showTotal: (total) => `共 ${total} 条`,
                        onChange: changePage
                    }}
                />
            </div>
        );
    }
}
export default QuestionList;