import React, { useRef, useState } from 'react';
import { history } from 'umi';
import type { ProFormInstance } from '@ant-design/pro-form';
import { BetaSchemaForm, ProFormRadio, ProFormUploadButton } 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, Modal, 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 { MailOutlined, AppstoreOutlined, PlusOutlined, TagsOutlined } from '@ant-design/icons';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css'
import ProFormRichEdit from '../components/ProFormRichEdit';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { TableListItem, TableListPagination } from '../../option/data';
import { queryCourseList, saveSubject } from '../../option/service';

/** 列表项定义 */
const columns: ProColumns<TableListItem>[] = [
  {
    title: '序号',
    key: 'index',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '章节名称',
    dataIndex: 'course_name',
    valueType: 'text',
    hideInTable: false,
    hideInDescriptions: false,
    hideInForm: false,
    hideInSearch: true,
  },
  {
    title: '简介',
    dataIndex: 'lecture_teacher',
    valueType: 'text',
    sorter: false,
    hideInTable: false,
    hideInForm: false,
    hideInSearch: true,
    renderText: (val: string) => `${val}`,
  },
  {
    title: '课程',
    valueType: 'textarea',
    dataIndex: 'course_describe',
    sorter: false,
    hideInTable: false,
    hideInForm: false,
    hideInSearch: true,
    renderText: (val: string) => `${val}`,
  },
  {
    title: '学时',
    dataIndex: 'course_minutes',
    valueType: 'text',
    sorter: false,
    hideInTable: false,
    hideInForm: false,
    hideInSearch: true,
    renderText: (val: string) => `${val}`,
  },
  {
    title: '操作',
    dataIndex: 'option',
    valueType: 'option',
    render: (_dom: any, record: React.SetStateAction<TableListItem | undefined>) => [
      <a
        key="detail"
        onClick={() => {
          //console.log('entity', entity);
          //setCurrentRow(record);
          //handleDetailModalVisible(true);
        }}
      >
        查看
      </a>,
      <a
        key="update"
        onClick={() => {
          //setCurrentRow(record);
          //handleUpdateModalVisible(true);
        }}
      >
        编辑
      </a>,
      <a key="remove" onClick={() => { }}>
        删除
      </a>,
    ],
  },
];

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 formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  /** 更新窗口的弹窗 */
  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  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 (value) => {
              console.log(value, "vvvvv");

              console.log(formRef.current?.getFieldsValue());
              await waitTime(2000);
              return true;
            }}
          >
            <Row gutter={24}>
              <Col lg={24} md={24} sm={24}>
                <ProFormText

                  name="subject_name"
                  label="主题名称"
                  width="md"
                  // tooltip="最长为 6 位汉字，需要与考生身份证一致"
                  placeholder="请输入名称"
                // rules={[{ required: true }]}
                // value="锦书"
                // disabled
                />
                <ProFormRichEdit
                  name="subject_describe"
                  label="主题介绍"
                  width="md"
                  // tooltip="最长为 6 位汉字，需要与考生身份证一致"
                  placeholder="请输入介绍"
                // rules={[{ required: true }]}
                // value="锦书"
                // disabled

                />
                <ProFormUploadButton
                  name="upload"
                  label="主题图片"
                  max={2}
                  fieldProps={{
                    name: 'file',
                    listType: 'picture-card',
                    data: {
                      name: '5.jpg',
                      chunk: 0,
                      chunks: 1,
                      key: 'down/Material/BC/BCFFEA09-9660-9D40-8D11-EF7D7110F7A5.jpg'
                    }
                  }}
                  action="/dsideal_yy/res/plupload/"
                  extra=""
                />
              </Col>
            </Row>

          </StepsForm.StepForm>

          <StepsForm.StepForm<{
            checkbox: string;
          }>
            name="object"
            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;

            }}
          >
            <div style={{ margin: '0' }}>
              <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>

              <ProTable<TableListItem, TableListPagination>
                headerTitle={false}
                actionRef={actionRef}
                rowKey="course_id"
                options={false}
                search={false}
                toolBarRender={() => [
                  <Button
                    type="primary"
                    key="primary"
                    onClick={() => {
                      handleCreateModalVisible(true);
                    }}
                  >
                    <PlusOutlined /> 添加章节
                  </Button>,
                ]}
                request={async (value) => {

                  const _data = await saveSubject({
                    ...value,
                    attachment_json: `{ "url": "${value.upload[0].response.url}"}`
                  });
                  return {
                    current: _data?.page_number,
                    data: _data?.data?.list,
                    pageSize: _data?.page_size,
                    total: _data?.total_row || 0,
                  };
                }}
                // dataSource={list}
                columns={columns}
                rowSelection={false}
              />
              <Modal
                title="新建章节"
                //
                width="60%"
                visible={createModalVisible}
                destroyOnClose
                onCancel={() => {
                  handleCreateModalVisible(false);
                }}
                footer={null}
              >
                <BetaSchemaForm<DataItem>
                  layout="horizontal"
                  layoutType="Form"
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 12 }}
                  onFinish={async (values: any) => {
                    // 表单处理
                    console.log('columns:', columns);
                    console.log('values:', values);

                  }}
                  submitter={{
                    render: (props, doms) => (
                      <Row>
                        <Col span={12} offset={8}>
                          <Space>{doms}</Space>
                        </Col>
                      </Row>
                    ),
                  }}
                  // action = ''
                  title="新建"
                  columns={columns}
                />
              </Modal>
            </div>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="time"
            title="完成"
            stepProps={{
              description: false,
            }}
            onFinish={async () => {
              console.log(formRef.current?.getFieldsValue());
              // 跳转到指定路由
              history.push('/course/subject');
              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>

  );
};