import React, { useEffect, useRef, useState } from 'react';
import { history, useParams, useRequest } from 'umi';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ProFormRadio } from '@ant-design/pro-form';
import ProForm, {
    StepsForm,
    ProFormText,
    ProFormDatePicker,
    ProFormSelect,
    ProFormTextArea,
    ProFormCheckbox,
    ProFormDateRangePicker,
} from '@ant-design/pro-form';
import ProCard from '@ant-design/pro-card';
import { Button, Checkbox, Col, Divider, List, Menu, message, Radio, Row, Space, Typography } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProDescriptions from '@ant-design/pro-descriptions';
import styles from './index.less'
import { saveRules, querySubjectList, queryRulesView, queryRulesList, queryRulesPaper } from '../../service';
import { queryQuestionType } from '@/pages/questionbank/service';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { TableListPagination } from '@/pages/ListTableList2/data';
import { PlusOutlined } from '@ant-design/icons';
import { TableListItem } from '../../components/QuestionSelector';

/** 题型序号 */
const numberType = ['一','二','三','四','五','六','七','八','九','十'];

const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};
const numbers = [];
for (let i = 0; i < 50; i++) {
    numbers.push({ id: `${i}` })
}

export default () => {
    /** 列表项定义 */
    const columns: ProColumns<TableListItem>[] = [
        {
        title: '序号',
        key: 'index',
        valueType: 'indexBorder',
        width: 48,
        },
        {
        title: '考试名称',
        dataIndex: 'rules_name',
        valueType: 'text',
        hideInTable: false,
        hideInForm: false,
        hideInSearch: true,
        },
        {
        title: '试卷',
        dataIndex: 'examination_time',
        valueType: 'text',
        sorter: false,
        hideInTable: false,
        hideInForm: false,
        hideInSearch: true,
        renderText: (val: string) => `${val}`,
        },
        {
        title: '关联主题',
        dataIndex: 'subject_name',
        valueType: 'text',
        hideInTable: false,
        hideInForm: false,
        hideInSearch: true,
        },
        {
        title: '题型设置',
        dataIndex: 'subject_id',
        valueType: 'text',
        hideInTable: true,
        hideInForm: false,
        hideInSearch: false,
        request: async () => {
            /*
            const { data: Items } = await querySubjectList({});
            // console.log(Items, ')))');

            const sinfo = []
            for (let i = 0; i < Items.list.length; i++) {
            // console.log(Items.list[i], ">>>")
            sinfo.push({ label: Items.list[i].subject_name, value: Items.list[i].subject_id })
            }
            console.log(sinfo, 'sinfo');
    */
            return [];
        },
        },
        {
        title: '总分',
        dataIndex: 'sum_score',
        sorter: false,
        valueType: 'text',
        hideInSearch: true,
        hideInForm: false,
        renderText: (val: string) => `${val}分`,
        },
        {
        title: '通过线',
        dataIndex: 'pass_score',
        sorter: false,
        valueType: 'text',
        hideInSearch: true,
        hideInForm: false,
        renderText: (val: string) => `${val}`,
        },
        {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_dom: any, record: React.SetStateAction<TableListItem | undefined>) => {
            console.log(record, 'record')
            return [
                <a
                    key="detail"
                    onClick={() => {
                        //console.log('entity', entity);
                        //setCurrentRow(record);
                        //handleDetailModalVisible(true);
                    }}
                >
                查看
                </a>,
                <a
                    key="create"
                    onClick={() => {
                    //history.push(`/examination/option/registration/${record.examination_id}`);
                    //setCurrentRow(record);
                    }}
                >
                重新生成
                </a>,
            ]
        },
        },
    ];
    const formRef = useRef<ProFormInstance>();
    const params = useParams();
    const actionRef = useRef<ActionType>();
    
    console.log(params, 'params');
    let ruleData = {}
    if (params?.id) {
        console.log(JSON.stringify(params), "878");

        const { data } = useRequest(async () => {
            const { bean } = await queryRulesView(params);
            return { data: bean }
        });
        ruleData = data
    }
    console.log(ruleData, 'ruleData');

    const [questionType, setQuestionType] = useState([]); // 题型
    /** 获取题型 */
    const { data: questionTypeData } = useRequest(() => {
        return queryQuestionType();
    },{
        formatResult: (result) => {
        return result.list;
        }
    });

    useEffect(() => {
        setQuestionType(questionTypeData || []);
        return ()=>{
          /** 退出当前页面清空Map */
          //parsingMap.clear();
        }
    }, [questionTypeData]);
      
    return (
        <PageContainer content={''} extraContent={''}>
            <ProCard className={styles.examinationrules}>
                <StepsForm<{
                    name: string;
                }>
                    formRef={formRef}
                    onFinish={async () => {
                        await waitTime(1000);
                        message.success('提交成功');
                    }}
                    formProps={{
                        layout: "horizontal",
                        labelCol: { span: 8 },
                        wrapperCol: { span: 12 },
                        validateMessages: {
                            required: '此项为必填项',
                        },
                    }}
                >
                    <StepsForm.StepForm<{
                        name: string;
                    }>
                        name="base"
                        title="模拟考试基本信息"
                        stepProps={{
                            description: false,
                        }}
                        onFinish={async (fileds) => {
                            if (params.id) {
                                fileds = { ...fileds, id: params.id }
                            }
                            console.log(fileds, 'fileds', params);
                            // return false
                            await saveRules({
                                ...fileds,
                                b_use: 0,
                                rules_type: 1,
                                start_time: fileds.dateRange[0],
                                end_time: fileds.dateRange[1]
                            });

                            // await waitTime(2000);
                            return true;

                        }}
                    >
                        <Row gutter={24}>
                            <Col lg={24} md={24} sm={24}>
                                {ruleData && (
                                    <>
                                        <ProFormText
                                            name="rules_name"
                                            label="考试名称"
                                            width="md"
                                            initialValue={ruleData.rules_name}
                                            // tooltip="最长为 6 位汉字，需要与考生身份证一致"
                                            placeholder="请输入名称"
                                            rules={[{ required: true, message: '请输入考试名称' }]}
                                        // value="锦书"
                                        // disabled
                                        />

                                        <ProFormSelect
                                            width="md"
                                            initialValue={ruleData.subject_id}
                                            request={async () => {
                                                return querySubjectList().then(({ data }) => {
                                                    console.log(data, 'querySubjectList')
                                                    return data.list.map((item) => {
                                                        return {
                                                            label: item.subject_name,
                                                            value: item.subject_id,
                                                        };
                                                    });
                                                });
                                            }}
                                            rules={[{ required: true, message: '请选择主题' }]}
                                            name="subject_id"
                                            label="关联主题"
                                        />
                                        <ProFormText name="examination_time" label="考试时长"
                                            initialValue={ruleData.examination_time}
                                            rules={[{ required: true, message: '请输入考试时长' }]}
                                        // tooltip="限制考试时长的情况下，用户考试中离开，倒计时不会停止。"
                                        />

                                        <ProFormText name="paper_count" label="试卷数量"
                                            initialValue={ruleData.paper_count}
                                            rules={[{ required: true, message: '请输入数量' }]}
                                        // tooltip="限制考试时长的情况下，用户考试中离开，倒计时不会停止。"
                                        />

                                        <ProFormDateRangePicker name="dateRange" label="试卷有效期" initialValue={[ruleData.start_time, ruleData.end_time]} />
                                    </>
                                )}
                            </Col>
                        </Row>

                    </StepsForm.StepForm>

                    <StepsForm.StepForm<{
                        checkbox: string;
                    }>
                        name="object"
                        title="组卷"
                        stepProps={{
                            description: false,
                        }}
                        onFinish={async () => {
                            console.log(formRef.current?.getFieldsValue());
                            return true;
                        }}
                    >
                        <div style={{ margin: '0' }}>
                            <ProTable<TableListItem, TableListPagination>
                                headerTitle={false}
                                actionRef={actionRef}
                                rowKey="examination_id"
                                options={false}
                                search={false}
                                toolBarRender={() => [
                                <Button
                                    type="primary"
                                    key="primary"
                                    onClick={() => {
                                    //history.push('/examinationrules/attestation/step')
                                    }}
                                >
                                    <PlusOutlined /> 系统组卷
                                </Button>,
                                <Button
                                    type="primary"
                                    key="primary"
                                    onClick={() => {
                                    //history.push('/examinationrules/attestation/step')
                                    }}
                                >
                                    <PlusOutlined /> 批量设置分值
                                </Button>
                                ]}
                                request={async (value) => {
                                    const _data = await queryRulesPaper(
                                        {
                                        rules_id: params?.id,
                                        page_number: value.current,
                                        page_size: value.pageSize
                                        }
                                    );
                                    return {
                                        current: _data?.pageNumber,
                                        data: _data?.table_List,
                                        pageSize: _data?.pageSize,
                                        total: _data?.totalRow || 0,
                                    };
                                }}
                                // dataSource={list}
                                columns={columns}
                                rowSelection={false}
                            />
                        </div>
                    </StepsForm.StepForm>

                    <StepsForm.StepForm
                        name="time"
                        title="完成"
                        stepProps={{
                            description: false,
                        }}
                        onFinish={async () => {
                            console.log(formRef.current?.getFieldsValue());
                            // 跳转到指定路由
                            history.push('/examinationrules/normal');
                            return true;
                        }}
                    >

                        <Row gutter={24}>
                            <Col lg={12} md={12} sm={12} offset={8}>
                                <ProDescriptions
                                    layout='horizontal'
                                    column={1}
                                    //actionRef={actionRef}
                                    title="模拟考试"
                                    request={async () => {
                                        return Promise.resolve({
                                            success: true,
                                            data: { id: '这是一段文本', object: '', date: '2020-07-30 08:00', duration: '', grade: 100, through: '>60', learn: '>20 min', times: 2 },
                                        });
                                    }}
                                    extra={false}
                                >
                                    <ProDescriptions.Item dataIndex="id" hideInDescriptions />
                                    <ProDescriptions.Item dataIndex="object" label="考试名称" valueType="text" />
                                    <ProDescriptions.Item dataIndex="date" label="关联培训主题" valueType="text" />
                                    <ProDescriptions.Item dataIndex="duration" label="考试时长" valueType="text" />

                                    <ProDescriptions.Item dataIndex="grade" label="考试信息" valueType="text" />

                                    <ProDescriptions.Item dataIndex="through" label="通过标准" valueType="text" />
                                    <ProDescriptions.Item dataIndex="times" label="考试次数" valueType="text" />
                                </ProDescriptions>
                            </Col>
                        </Row>
                    </StepsForm.StepForm>
                </StepsForm>
            </ProCard>
        </PageContainer>

    );
};