/** 考试规则维护 */
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, Typography } from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
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, queryRulesList, removeRules } from '../service';
import type { TableListItem, TableListPagination } from './data';
import type { DataItem } from '@antv/data-set/lib/transform/tag-cloud';
import { updateRules } from './service';

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

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

/**
 * 更新考试规则
 *
 * @param fields
 */
 const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
  const hide = message.loading('正在配置');
  console.log('fields',fields)
  try {
    await updateRules({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

const ExaminationRules: React.FC = () => {
  //const [registrationModalVisible, handleRegistrationModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  /** 列表项定义 */
  const columns: ProColumns<TableListItem>[] | ProColumns<TableListItem>[] = [
    {
      title: '序号',
      key: 'index',
      valueType: 'indexBorder',
      render: (text: React.ReactNode, _: any, index: number) => {
        if (actionRef && actionRef?.current && actionRef?.current?.pageInfo) {
          return `${(actionRef?.current?.pageInfo?.current - 1) * actionRef.current.pageInfo?.pageSize + (index + 1)
            }`;
        } else {
          return '';
        }
      },
      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({ 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;
      },
    },
    {
      title: '创建日期',
      dataIndex: 'create_time',
      valueType: 'dateRange',
      sorter: false,
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      render: (dom, entity) => {
        return entity.create_time
      },
    },

    {
      title: '总分',
      dataIndex: 'sum_score',
      sorter: false,
      valueType: 'text',
      hideInForm: false,
      hideInSearch: true,
      renderText: (val: string) => `${val || '-'}`,
    },
    {
      title: '通过线',
      dataIndex: 'pass_score',
      sorter: false,
      valueType: 'text',
      hideInForm: false,
      hideInSearch: true,
      renderText: (val: string) => `${val || '-'}`,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_dom: any, record: React.SetStateAction<TableListItem | undefined>) => {
        return [
          // <a
          //   key="detail"
          //   onClick={() => {
          //     //console.log('entity', entity);
          //     setCurrentRow(record);
          //     handleDetailModalVisible(true);
          //   }}
          // >
          //   查看
          // </a>,
          <Button type="link"
            key="update"
            disabled={record.b_use ? true : false}
            onClick={() => {
              history.push('/examinationrules/normal/step/' + record.id)
            }}
            style={{padding: '0 2px 0 0'}}
          >
            编辑
            </Button>,
          <Button type="link"
            key="remove"
            disabled={record.b_use ? true : false}
            onClick={ () => {
              handleRemove([{ key: record?.id }], record); // 调用批量删除函数（如果接口不支持批量需要在service中处理）
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            style={{padding: '0 2px 0 0'}}
            >
            <Typography.Text disabled={record.b_use ? true : false} type={"danger"}>删除</Typography.Text>
          </Button>,
          <a
            key="b_use"
            onClick={async () => {
              //history.push(`/examination/option/registration/${record.examination_id}`);
              //setCurrentRow(record);
              console.log('record', {...record, b_use: !record.b_use})
              await handleUpdate({b_use: record?.b_use === 0 ? 1 : 0}, record);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            {record.b_use == 1 ? <Typography.Text type="success">已发布</Typography.Text> : <Typography.Text type="secondary">发布</Typography.Text>}
          </a>,
        ]
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle={false}
        actionRef={actionRef}
        rowKey="id"
        options={false}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              history.push('/examinationrules/normal/step')
            }}
          >
            <PlusOutlined /> 新建考试规则
          </Button>,
        ]}
        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 queryRulesList(
            {
              ...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,
          };
        }}
        // 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>
      )}
    </PageContainer>
  );
};

export default ExaminationRules;
