/** 考试维护 */
import React, { useState, useRef } from 'react';
import { useRequest, history } from 'umi';
import { PlusOutlined, TagsOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Col, Row, Space, Upload, Form, Popconfirm, Typography } from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ActionType } from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { ProFormColumnsType } from '@ant-design/pro-form';
import { BetaSchemaForm, ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import { querySubjectList, updateExamination, removeExamination, queryExaminationList, queryRulesList } from '../service';
import type { TableListItem, TableListPagination } from './data';
import type { DataItem } from '@antv/data-set/lib/transform/tag-cloud';
import { ConsoleMessage } from 'puppeteer-core';



/**
 * 更新考试
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在配置');
  console.log(fields, '111111111');

  try {
    await updateExamination({
      ...fields,

    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除考试
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[], currentRow) => {
  console.log('selectedRows', selectedRows)
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeExamination({
      key: selectedRows.map((row) => row.key),
    }, currentRow);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const ExaminationList: React.FC = () => {
  /** 更新窗口的弹窗 */
  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  //const [registrationModalVisible, handleRegistrationModalVisible] = useState<boolean>(false);
  const [schemaForm] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  /** 列表项定义 */
  const columns: ProFormColumnsType<DataItem>[] = [
    {
      title: '序号',
      key: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '考试名称',
      dataIndex: 'examination_name',
      valueType: 'text',
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请填写考试名称',
          },
        ]
      },
    },
    {
      title: '报名时间',
      dataIndex: 'apply_time',
      valueType: 'dateTimeRange',
      hideInTable: false,
      hideInForm: false,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择报名时间',
          },
        ]
      },
      render: (dom, entity) => {
        return entity.apply_start_time + " - " + entity.apply_end_time;
      },
    },
    {
      title: '考试时间',
      valueType: 'dateTimeRange',
      dataIndex: 'examination_time',
      hideInForm: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择考试时间',
          },
        ]
      },

      hideInSearch: true,
      render: (dom, entity) => {
        return entity.examination_start_time + " - " + entity.examination_end_time;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      valueType: 'dateTimeRange',
      hideInTable: true,
      hideInForm: true,
      hideInSearch: false,
    },
    {
      title: '关联主题',
      dataIndex: 'subject_id',
      valueType: 'text',
      hideInTable: true,
      hideInForm: false,
      hideInSearch: true,
      request: async () => {
        const { data: Items } = await querySubjectList({ page_size: 1000 });
        // 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 sinfo;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ]
      },
    },
    {
      title: '关联的规则',
      dataIndex: 'rules_id',
      valueType: 'select',
      hideInTable: true,
      hideInForm: false,
      hideInSearch: true,
      dependencies: ['subject_id'],
      request: async (params) => {
        console.log(params, 'params::::');
        const { table_List: Items } = await queryRulesList({ rules_type: 1, subject_id: params.subject_id || 0, });
        const rules = [];
        for (let i = 0; i < Items.length; i++) {
          rules.push({ label: Items[i].rules_name, value: Items[i].id })
        }
        return rules;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ]
      },
    },

    {
      title: '在线学习时长(分钟)',
      dataIndex: 'learning_time',
      valueType: 'text',
      hideInForm: false,
      hideInSearch: true,
      hideInTable: true,
      renderText: (val: string) => `${val}`,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请填写在线时长',
          },
        ]
      },

    },
    {
      title: '课程开放时间',
      dataIndex: 'course_time',

      valueType: 'dateTimeRange',
      hideInTable: true,
      hideInForm: false,
      hideInSearch: true,
      renderText: (val: string) => `${val}`,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择主题开放时间',
          },
        ]
      },
    },

    {
      title: '试卷数量',
      dataIndex: 'paper_count',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      renderText: (val: string) => `${val}`,
    },
    {
      title: '报考人数',
      dataIndex: 'apply_person_count',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true,
      render: (dom, entity) => {
        return entity.apply_person_count + "人";
      },
    },
    {
      title: '状态',
      dataIndex: 'status_type',
      hideInForm: true,
      hideInSearch: false,
      valueEnum: {
        0: { text: '待报名' },
        1: { text: '报名中' },
        2: { text: '待考试' },
        3: { text: '考试中' },
        4: { text: '考试完成' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_dom: any, record: React.SetStateAction<TableListItem | undefined>) => [

        <Popconfirm key="popconfirm" title={`确认修改发布状态吗?`} okText="是" cancelText="否"
          onConfirm={async () => {
            const success = await updateExamination({
              examination_id: record.examination_id,
              b_use: record.b_use == 1 ? 0 : 1,
              rules_id: record.rules_id
            });
            if (success) {
              // handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <a
            key="publish"
          >
            {record.b_use == 1 ? <Typography.Text type="success">已发布</Typography.Text> : <Typography.Text type="warning">未发布</Typography.Text>}
          </a>
        </Popconfirm>

        ,
        <a
          key="update"
          onClick={() => {
            console.log(record, 'record')
            handleUpdateModalVisible(true);
            record.apply_time = [record.apply_start_time, record.apply_end_time]
            record.examination_time = [record.examination_end_time, record.examination_end_time]
            record.apply_time = [record.apply_start_time, record.apply_end_time]
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <a
          key="remove"
          onClick={() => {
            handleRemove([{ key: record?.examination_id }], record); // 调用批量删除函数（如果接口不支持批量需要在service中处理）
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }}>
          删除
        </a>,
        <a
          key="registration"
          onClick={() => {
            history.push(`/examination/option/registration/${record.examination_id}`);
            //setCurrentRow(record);
          }}
        >
          名单
        </a>,
      ],
    },
  ];
  /** 获取列数据初始值 */
  const getInitialValues = (cols: any[], vals: any) => {
    console.log('getInitialValues-columns', columns);
    console.log('getInitialValues-values', vals);
    const initialValues: any[] = [];
    cols.forEach((column: { dataIndex: string }) => {
      const key: any = column?.dataIndex || '';
      initialValues.push({ ...column, initialValue: key ? vals[key] : '' });
    });
    console.log('initialValues::', initialValues);
    return initialValues || [];
  };
  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle={false}
        actionRef={actionRef}
        rowKey="examination_id"
        options={false}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建考试
          </Button>,
        ]}
        request={async (value) => {
          const { create_time } = value;
          if (create_time) {
            value.start_time = create_time[0]
            value.end_time = create_time[1]
          }
          console.log('form _data', value)
          delete value.create_time
          const _data = await queryExaminationList(
            {
              ...value,
              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}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <Modal
        title={currentRow?.examination_name || '考试详细'}
        width="60%"
        visible={detailModalVisible}
        onCancel={() => {
          setCurrentRow(undefined); // 设置当前行
          handleDetailModalVisible(false);
        }}
        footer={null}
        centered
      >{console.log('currentRow', currentRow)}
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            /* title={currentRow?.name} */
            dataSource={currentRow}
            request={async (value) => {
              console.log(value, 'form value')
              const { create_time } = value;
              if (create_time) {
                value.start_time = create_time[0]
                value.end_time = create_time[1]
              }
              const _data = await getExaminationList(
                {
                  ...value,
                  rules_type: 0,

                  page_number: value.current,
                  page_size: value.pageSize
                }
              );

              return {
                current: _data?.pageNumber,
                data: _data?.table_List,
                pageSize: _data?.pageSize,
                total: _data?.totalRow || 0,
              };
            }}
            params={{
              id: currentRow?.examination_id,
            }}
            columns={
              columns
              //columns.slice(0, columns.length - 1) as ProDescriptionsItemProps<TableListItem>[]
            }
          />
        )}
      </Modal>

      <Modal
        title="新建考试"
        //
        width="60%"
        visible={createModalVisible}
        destroyOnClose
        onCancel={() => {
          handleCreateModalVisible(false);
        }}
        footer={null}
      >
        <BetaSchemaForm<DataItem>
          form={schemaForm}
          layout="horizontal"
          layoutType="Form"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 12 }}
          onValuesChange={(values: any) => {
            console.log('values:', values);
            const { subject_id } = values
            if (subject_id) {
              schemaForm.setFieldsValue({ rule_id: "" })
            }
          }}

          onFinish={async (values: any) => {
            // 表单处理
            //console.log('columns:', columns);
            console.log('values1:', values);
            //return false;
            // values.attachment_json.response.file.response.url
            const params = {
              ...values,
              apply_start_time: values.apply_time[0],
              apply_end_time: values.apply_time[1],
              course_start_time: values.course_time[0],
              course_end_time: values.course_time[1],
              examination_start_time: values.examination_time[0],
              examination_end_time: values.examination_time[1]
            }

            delete params.apply_time
            delete params.course_time
            delete params.examination_time

            await handleUpdate(params);
            handleCreateModalVisible(false);
            actionRef.current?.reloadAndRest?.();
          }}


          /*
                    onFinish={async (values: any) => {
                      // 表单处理
                      console.log('columns:', columns);
                      console.log('values:', values);
          
                      // if (params.id) {
                      //     fileds = { ...fileds, id: params.id }
                      // }
                      // console.log(fileds, 'fileds', params);
                      // // return false
                      const res = await updateExamination({
                        ...values,
                        apply_end_time: values.apply_time[0],
                        apply_start_time: values.apply_time[1],
                        course_end_time: values.course_time[0],
                        course_start_time: values.course_time[0],
                        examination_start_time: values.examination_time[0],
                        examination_end_time: values.examination_time[0],
                      });
                      console.log(res, 'resresresres');
          
                      // // await waitTime(2000);
                      // return true;
          
          
          
                    }}
          
          */

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

      <Modal
        title="编辑"
        width="60%"
        visible={updateModalVisible}
        destroyOnClose
        onCancel={() => {
          handleUpdateModalVisible(false);
        }}
        footer={null}
      >
        {currentRow?.examination_id && (
          <BetaSchemaForm<DataItem>
            layout="horizontal"
            layoutType="Form"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 12 }}
            onFinish={async (values) => {
              console.log('values', values);
              //const url = values?.upload[0]?.url?.replace('/dsideal_yy/html/','') || values?.upload[0]?.response?.url;
              //console.log('url', url)
              const params = {
                ...values,
                apply_start_time: values?.apply_time[0],
                apply_end_time: values?.apply_time[1],
                course_start_time: values?.course_time[0],
                course_end_time: values?.course_time[1],
                examination_start_time: values?.examination_time[0],
                examination_end_time: values?.examination_time[1]
              }

              delete params.apply_time
              delete params.course_time
              delete params.examination_time
              await handleUpdate({
                ...params,
                examination_id: currentRow?.examination_id,
              });
              handleUpdateModalVisible(false); // 隐藏编辑窗口
              actionRef.current?.reloadAndRest?.();
              console.log(values);
            }}
            submitter={{
              render: (props, doms) => (
                <Row>
                  <Col span={12} offset={8}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              ),
            }}
            // action = ''
            title="编辑"
            columns={getInitialValues(columns, currentRow)}
          />
        )}
      </Modal>

    </PageContainer>
  );
};

export default ExaminationList;
