import type { TypeResult } from '@/pages/ApplyList/hooks';
import useUrlState from '@ahooksjs/use-url-state';
import { ProForm } from '@ant-design/pro-form';
import { Alert, Button, Input, Modal, Space, Typography } from 'antd';
import { useForm } from 'antd/es/form/Form';
import { useEffect, useRef, useState } from 'react';
import { history, useIntl } from 'umi';
import { auditPreview, multipleApplyBatch, multipleAuditPreview, postApplybatch } from './api';
import PreviewTable from './components/previewTable';
import style from './index.less';
import { getPreviewParams, getSubmitParams } from './util';

const { TextArea } = Input;
const { Text } = Typography;

type TMultipleDataSource = {
  appId: number;
  name: string;
  data: any;
}[];

export type OpenType<D = any, U = any> = {
  isopen?: boolean;
  appId?: number;
  data?: D;
  otherUsers?: U;
  packageData?: TypeResult;
};

export interface AuditPreviewProps<D = any, U = any> {
  openObj: OpenType<D, U>;
  setOpenObj: (o: OpenType<D, U>) => void;
  type?: 'single' | 'multiple';
}

const AuditPreview = (props: AuditPreviewProps) => {
  const { openObj, setOpenObj, type = 'single' } = props;

  const { formatMessage } = useIntl();
  const [submit, setSubmit] = useState<boolean>(false);
  const [query] = useUrlState();
  const [tableList, setTableList] = useState([]);
  const [multipleDataSource, setMultipleDataSource] = useState<TMultipleDataSource>([]);
  const submitbtm = useRef(true);
  const [formReason] = useForm();

  const {
    isopen: open,
    data: parentData,
    otherUsers,
    appId: parentAppId,
    packageData,
  } = openObj || {};

  // 仅适用单应用申请(type === 'single')
  const { appId: urlAppId } = query || {};
  const appId = parentAppId || urlAppId;

  const onCancel = () => {
    setOpenObj({ isopen: false });
    setTableList([]);
    setMultipleDataSource([]);
  };

  const requestPreview = async (value: any) => {
    try {
      if (type === 'single') {
        const { data } = await auditPreview(value);
        setTableList(data);
      } else {
        // 多组应用权限审批预览
        const { data } = await multipleAuditPreview(value, packageData?.id);
        setMultipleDataSource(data);
      }
    } catch (e) {
      onCancel();
    }
  };

  const onSubmit = async () => {
    try {
      await formReason.validateFields();
      const reason = formReason.getFieldValue('reason');
      const proxyUserIds =
        type === 'single'
          ? parentData?.otherUsers?.map((item: any) => item.id)
          : otherUsers?.map((item: any) => item.id);
      if (type === 'single') {
        const params = {
          reason,
          proxyUserIds,
          ...getSubmitParams(parentData, appId),
        };
        const { data } = await postApplybatch(params);
        history.push(`/applyDetail?chainId=${data?.chainIds?.[0]}`);
      } else if (Array.isArray(parentData)) {
        // 权限包
        const submitData = parentData.map((item: any) => {
          return {
            proxyUserIds,
            ...getSubmitParams(item),
          };
        });
        const { data } = await multipleApplyBatch({
          data: submitData,
          reason,
          multiAuditId: packageData?.id,
        });
        history.push(`/batchApplyDetail?batchAuditId=${data?.batchAuditId}`);
      }
      setSubmit(false);
      submitbtm.current = true;
    } catch (e) {
      setSubmit(false);
      submitbtm.current = true;
    }
  };

  useEffect(() => {
    formReason.resetFields();
    if (open) {
      if (type === 'single') {
        requestPreview(getPreviewParams(parentData, appId));
        return;
      } else if (type === 'multiple' && Array.isArray(parentData)) {
        requestPreview(parentData.map((item) => getPreviewParams(item)));
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, appId]);

  return (
    <>
      <Modal
        width={1000}
        title={formatMessage({ id: 'base.appply.aduitpreview' })}
        open={open}
        onCancel={onCancel}
        destroyOnClose={true}
        keyboard={true}
        maskClosable={false}
        footer={
          <div style={{ textAlign: 'center' }}>
            <Button
              loading={submit}
              disabled={submit}
              onClick={() => {
                if (submitbtm.current) {
                  setSubmit(true);
                  onSubmit();
                  submitbtm.current = false;
                }
              }}
              className={style.btn}
              type={'primary'}
            >
              {formatMessage({ id: 'base.ok.submit' })}
            </Button>
          </div>
        }
      >
        <Space direction={'vertical'} style={{ width: '100%' }}>
          <Alert
            banner
            closable
            message={formatMessage({ id: 'base.aduitpreview.tips' })}
            type={'warning'}
          />

          {open && (
            <PreviewTable
              type={type}
              packageData={type === 'multiple' ? packageData : undefined}
              dataSource={type === 'single' ? tableList : multipleDataSource}
            />
          )}
          {/* 
          {open && type === 'single' ? (
            <PreviewTable dataSource={tableList} />
          ) : (
            <Collapse defaultActiveKey={[multipleDataSource?.[0]?.appId]}>
              {multipleDataSource.map((item) => {
                return (
                  <Collapse.Panel header={item.name} key={item.appId}>
                    <PreviewTable dataSource={item.data} />
                  </Collapse.Panel>
                );
              })}
            </Collapse>
          )} */}

          <ProForm style={{ marginTop: 10 }} form={formReason} submitter={false}>
            <ProForm.Item
              rules={[
                { required: true, message: formatMessage({ id: 'base.common.required.fields' }) },
                {
                  validator: async (val) => {
                    if (!val) return true;
                    return undefined;
                  },
                },
              ]}
              label={formatMessage({ id: 'base.apply.reason' })}
              name={'reason'}
            >
              <TextArea style={{ width: '100%', height: '100px' }} allowClear />
            </ProForm.Item>

            <ProForm.Item style={{ marginBottom: 0 }} name={'reason'}>
              <Text style={{ float: 'left' }} type={'danger'}>
                {formatMessage({ id: 'base.aduitpreview.tips1' })}
              </Text>
            </ProForm.Item>
          </ProForm>
        </Space>
      </Modal>
    </>
  );
};

export default AuditPreview;
