/** 考试维护 */
import React, { useState, useRef,useEffect } from 'react';
import { useRequest, history } from 'umi';
import { ConsoleSqlOutlined, PlusOutlined, TagsOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Col, Row, Space, Upload, Form, Popconfirm, Typography,Select } 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';
import ExaminationRules from '../../examinationrules/normal/index';

const { Option } = Select;

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

const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在更新');
  // fields.rules_id=fields.rules_name;
  // delete fields.rules_name;
  try {
    await updateExamination({
      ...fields,

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

/**
 * 删除考试
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[], currentRow) => {
  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 [ruleList,setRuleList] = useState([]);
  const [subjectList,setSubjectList] = useState([]);
  const [subjectId,setSubjectId] = useState(null);
  const [ruleId,setRuleId ] = useState(null);
  // useEffect(() => {
  // }, [rules]);

  useEffect(() => {

  }, [updateModalVisible]);

  const { data:Items } = useRequest(() => {
    return querySubjectList({ page_size: 1000 });
  }, {
    formatResult: (result) => {
      console.log('result',result.data.list);
      setSubjectList(result.data.list)
    }
  });

  /** 列表项定义 */
  const columns: ProFormColumnsType<DataItem>[] = [
    {
      title: '序号',
      key: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '考试名称',
      dataIndex: 'examination_name',
      valueType: 'text',
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      fieldProps: {
        maxLength: 64
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请填写考试名称',
          },
          {
            pattern: /^[^\s]*$/,
            message: '禁止输入空格'
          }
        ]
      },
    },
    {
      title: '报名时间',
      dataIndex: 'apply_time',
      valueType: 'dateTimeRange',
      hideInTable: false,
      hideInForm: false,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择报名时间',
          },
          {
            validator: (rule, value) => {
              // console.log(value[0] > value[1]);
              const examinationTime = schemaForm.getFieldValue('examination_time')
                  if (examinationTime&&value) {
                    if (value[0] > new Date(examinationTime[0])) {
                      return Promise.reject('报名开始时间不能晚于考试开始时间')
                    }
                    if (value[1] > new Date(examinationTime[0])) {
                      return Promise.reject('报名结束时间不能晚于考试开始时间')
                    }
                  }

              return Promise.resolve()
            }
          }
        ]
      },
      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: '请选择考试时间',
          },
          {
            validator: (rule, value) => {
              // console.log(value[0] > value[1]);
              const applyTime = schemaForm.getFieldValue('apply_time')
              const courseTime = schemaForm.getFieldValue('course_time')
              console.log('applyTime',applyTime)
              console.log('courseTime',courseTime)
              console.log('value考试时间',value)

              if (applyTime&&value) {
                if (value[0] < new Date(applyTime[0])) {
                  return Promise.reject('考试开始时间不能晚于报名开始时间')
                }
                if (value[0] < new Date(applyTime[1])) {
                  return Promise.reject('考试开始时间不能早于报名结束时间')
                }
              }

              if (courseTime&&value) {
                if (value[0] < new Date(courseTime[0])) {
                  return Promise.reject('考试开始时间不能晚于课程主题开放开始时间')
                }
              }


              return Promise.resolve()
              // callback("时间不对");
            }
          }
        ]
      },

      hideInSearch: true,
      render: (dom, entity) => {
        return entity.examination_start_time + " - " + entity.examination_end_time;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      valueType: 'dateRange',
      hideInTable: false,
      hideInForm: true,
      hideInSearch: false,
      // colSize: 2,
      render:(text,record)=>{
        return record.create_time
      }
    },
    {
      title: '关联主题',
      dataIndex: 'subject_id',
      // valueType: 'select',
      hideInTable: true,
      hideInForm: false,
      hideInSearch: true,
      request: async () => {
        const { data: Items } = await querySubjectList({ page_size: 1000 });

        // schemaForm.setFieldsValue({ rules_id: '' });

        const sinfo = []
        for (let i = 0; i < Items.list.length; i++) {
          sinfo.push({ label: Items.list[i].subject_name, value: Items.list[i].subject_id })
        }
        console.log(sinfo, '关联主题');
        setSubjectList(sinfo)
        return sinfo;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择关联主题',
          },
      ]
      },

    },
    {
      title: '关联考试规则',
      dataIndex: 'rules_id',
      valueType: 'text',
      hideInTable: true,
      hideInForm: false,
      hideInSearch: true,
      dependencies: ['subject_id'],
      request: async (params) => {
        const rules = [];
        if(params.subject_id!==undefined){
          const { table_List: Items } = await queryRulesList({ rules_type: 1, subject_id: params.subject_id, });

          for (let i = 0; i < Items.length; i++) {
            rules.push({ label: Items[i].rules_name, value: Items[i].id })
          }
          // setRules(rules)

        }
        return rules;
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择关联考试规则',
          },
        ]
      },
    },

    {
      title: '在线学习时长(分钟)',
      dataIndex: 'learning_time',
      valueType: 'digit',
      hideInForm: false,
      hideInSearch: true,
      hideInTable: true,
      renderText: (val: string) => `${val}`,
      fieldProps: {
        maxLength: 3,
        min: 1
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请填写在线时长',
          },
          {
            pattern: /^[^\s]*$/,
            message: '禁止输入空格'
          }
        ]
      },

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

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

              // console.log(value[0] > value[1]);
              const examinationTime = schemaForm.getFieldValue('examination_time')
              // console.log("处理时间", examinationTime[0], new Date(examinationTime[0]));

              if (examinationTime&&value) {
                if (value[0] > new Date(examinationTime[0])) {
                  return Promise.reject('课程主题开放开始时间不能晚于考试开始时间')
                }

              }

              return Promise.resolve()
            }
          }
        ]
      },
    },

    {
      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 () => {
            try {
              await updateExamination({
                examination_id: record.examination_id,
                b_use: record.b_use == 1 ? 0 : 1,
                rules_id: record.rules_id
              });
              if (actionRef.current) {
                actionRef.current.reload();
              }
              // return true;
            } catch (error) {
              message.error(error.response.data.info);
            }



          }}
        >
          <a
            key="publish"
            style={{ display: 'inline-block', width: 50 }}
          >
            {record.b_use == 1 ? <Typography.Text type="success">已发布</Typography.Text> : <Typography.Text type="warning">发布</Typography.Text>}
          </a>
        </Popconfirm>

        ,
        <Button
          type="link"
          key="update"
          disabled={record.b_use ? true : false}
          onClick={() => {
            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.course_time = [record.course_start_time, record.course_end_time]
            setCurrentRow(record);
          }}
          style={{ padding: '0 2px 0 0' }}
        >
          编辑
        </Button>,
        <Popconfirm key="popconfirm" title={`确认删除当前考试吗?`} okText="是" cancelText="否"
                    disabled={record.b_use ? true : false}
          onConfirm={async () => {
            handleRemove([{ key: record?.examination_id }], record); // 调用批量删除函数（如果接口不支持批量需要在service中处理）
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }}
        >
          <Button  type="link" key="remove"  disabled={record.b_use ? true : false}>删除</Button>
        </Popconfirm>
        ,
        <Button
          type="link"
          disabled={record.b_use ? false : true}
          key="registration"
          onClick={() => {
            history.push(`/examination/option/registration/${record.examination_id}/${'kkwh'}`);
            //setCurrentRow(record);
          }}
        >
          查看名单
        </Button>,
      ],
    },
  ];
  /** 获取列数据初始值 */
  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,
          defaultCollapsed: false
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              schemaForm.resetFields()
              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]
          }
          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
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            /* title={currentRow?.name} */
            dataSource={currentRow}
            request={async (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="新建考试"
        destroyOnClose={true}
        width="60%"
        visible={createModalVisible}
        onCancel={() => {
          schemaForm.resetFields()
          handleCreateModalVisible(false);
        }}
        footer={null}
      >
        <BetaSchemaForm<DataItem>
          form={schemaForm}
          layout="horizontal"
          layoutType="Form"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 12 }}
          onValuesChange={(values: any) => {
            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



            const success = await handleUpdate(params);

            if (success) {

              if (actionRef.current) {
                actionRef.current.reload();
                handleCreateModalVisible(false);
                schemaForm.resetFields()
              }
            }

          }}


          submitter={{
            render: (props, doms) => (
              <Row>
                <Col span={12} offset={8}>
                  <Space>{doms}</Space>
                </Col>
              </Row>
            ),
          }}
          columns={columns}
        />
      </Modal>

      <Modal
        title="编辑"
        width="60%"

        visible={updateModalVisible}
        destroyOnClose={true}
        onCancel={() => {
          schemaForm.resetFields()
          handleUpdateModalVisible(false);
        }}
        footer={null}
      >
        {currentRow?.examination_id && (
          <BetaSchemaForm<DataItem>
            preserve={false}
            layout="horizontal"
            layoutType="Form"
            form={schemaForm}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 12 }}
            onFinish={async (values) => {
              schemaForm.validateFields()
              //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?.();
              schemaForm.resetFields()
            }}
            submitter={{
              render: (props, doms) => (
                <Row>
                  <Col span={12} offset={8}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              ),
            }}
            // action = ''
            columns={getInitialValues(columns, currentRow)}
          />
        )}
      </Modal>

    </PageContainer>
  );
};

export default ExaminationList;
