import React, { Key, useEffect, useRef, useState } from 'react';
import { message } from 'antd';
import { KCIMTable } from '@/components/KCIMTable';
import { createFromIconfontCN } from '@ant-design/icons';

import { history } from 'umi';

import {
  ActionType,
  ModalForm,
  ProColumns,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';

import { set } from 'lodash';
import { getDicDataBySysId } from '@/services/getDic';
import { getCheckListReq, reCheckListReq } from './service';

// import './style.less';

interface TableSelecterProps {
  record: any;
}

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

const TableSelecter = ({
  open,
  title,
  onVisibleChange,
  rowKey = 'id',
  computeDate,
}: {
  open: boolean;
  title: string;
  onVisibleChange: (bool: boolean) => void;
  defaultSelectedKeys: Key[];
  rowKey?: string;
  computeDate: string;
}) => {
  const tableRef = useRef<ActionType>();
  const Table = React.forwardRef(({}: TableSelecterProps, ref) => {
    const [type, set_type] = useState<string>('0');
    const [tableDataFilterParams, set_tableDataFilterParams] =
      useState<any>(undefined);

    const columns: ProColumns[] = [
      {
        title: '异常信息',
        ellipsis: true,
        width: 250,
        dataIndex: 'resultMessage',
      },
      {
        title: '异常类型',
        ellipsis: true,
        width: 100,
        dataIndex: 'resultTypeName',
        renderText(text, record, index, action) {
          return (
            <span
              style={{
                display: 'inline-block',
                width: 64,
                height: 20,
                background: '#FFEBEB',
                fontSize: 12,
                borderRadius: 4,
                textAlign: 'center',
                lineHeight: '20px',
                color: '#FF4C4C',
              }}
            >
              {text}
            </span>
          );
        },
      },
      {
        title: '处理建议',
        ellipsis: true,
        dataIndex: 'resolveAdvice',
      },
      {
        title: '操作',
        key: 'option',
        width: 60,
        valueType: 'option',
        render: (_: any, record: any) => {
          return [
            record.resolvePath.length > 0 ? (
              <a onClick={() => history.push(record.resolvePath)}>处理</a>
            ) : null,
          ];
        },
      },
    ];

    const getTableData = async (params: any) => {
      const resp = await getCheckListReq({
        ...params,
        computeDate,
        resultType: type == '0' ? null : type,
      });
      if (resp) {
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
          pageSize: resp.pageSize,
          totalPage: resp.totalPage,
        };
      }
      return {
        data: [],
        success: true,
      };
    };

    const reCheckHandle = async () => {
      const resp = await reCheckListReq(computeDate);
      if (resp) {
        message.success('检查成功！');
        tableRef.current?.reload();
      }
    };

    useEffect(() => {
      tableRef.current?.reload();
    }, [type]);

    return (
      <div>
        <div
          className="filter"
          style={{
            marginBottom: 8,
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <div>
            <span>异常类型：</span>
            <ProFormSelect
              noStyle
              style={{ marginRight: 8 }}
              request={async () => {
                const { systemId } = JSON.parse(
                  localStorage.getItem('currentSelectedTab') as string,
                );
                const resp = await getDicDataBySysId(
                  systemId,
                  'DATA_EXCEPTION_TYPE',
                );
                if (resp) {
                  const { dataVoList } = resp;
                  const arr = dataVoList.map((a: any) => ({
                    label: a.name,
                    value: a.code,
                  }));
                  return [
                    {
                      label: '全部',
                      value: '0',
                    },
                    ...arr,
                  ];
                }
                return [];
              }}
              fieldProps={{
                defaultValue: '0',
                onChange(value, option) {
                  set_type(value);
                },
              }}
            />
          </div>
          <div
            onClick={() => reCheckHandle()}
            className="reCheckBtn"
            style={{
              fontWeight: 400,
              fontSize: 14,
              color: '#3376FE',
              cursor: 'pointer',
            }}
          >
            重新检查
          </div>
        </div>

        <KCIMTable
          columns={columns}
          options={{
            density: true,
            setting: {
              listsHeight: 100,
            },
          }}
          request={(params) => getTableData(params)}
          actionRef={tableRef}
          params={tableDataFilterParams}
          rowKey={rowKey}
          scroll={{ y: 400 }}
          tableAlertRender={false}
          pagination={{ showTitle: false, showSizeChanger: true, simple: true }}
        />
      </div>
    );
  });

  const close = () => {
    onVisibleChange && onVisibleChange(false);
  };

  return (
    <ModalForm
      className="TableSelecter"
      title={title}
      width={800}
      submitter={{
        render: false,
      }}
      open={open}
      onOpenChange={(bool) => !bool && close()}
      modalProps={{}}
    >
      <Table
        // ref={tableSelecterRef}
        record={undefined}
      ></Table>
    </ModalForm>
  );
};

export default TableSelecter;
