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

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

import { set } from 'lodash';
import { getHasSetParamsList, getParamsSelectableList } from './service';
import { RecordKey } from '@ant-design/pro-utils/es/useEditableArray';

// import './style.less';

interface TableSelecterProps {
  record: any;
}

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

const EditTableModal = ({
  record,
  open,
  title,
  onVisibleChange,
  rowKey = 'id',
  onFinish,
}: {
  record: any;
  open: boolean;
  title: string;
  onVisibleChange: (bool: boolean) => void;
  rowKey?: string;
  onFinish?: (selectedRows: any[]) => void;
}) => {
  const Table = React.forwardRef(({}: TableSelecterProps, ref) => {
    const [datasource, set_datasource] = useState<any[]>([]);
    let currentSelectedRow: undefined | any = undefined;

    const columns: ProColumns[] = [
      {
        title: '分摊参数',
        dataIndex: 'shareParamCode',
        ellipsis: true,
        valueType: 'select',
        request: async () => {
          const resp = await getParamsSelectableList({
            pageSize: 500,
            current: 1,
            id: record.id,
          });
          if (resp) {
            return resp.list.map((a: any) => ({
              label: a.shareParamName,
              value: a.shareParamCode,
              id: a.id,
            }));
          }
          return [];
        },
        fieldProps: {
          showSearch: true,
          style: {
            width: '280px', // 设置你想要的宽度
          },
          onSelect: (a: any, b: any, c: any) => {
            currentSelectedRow = b;
          },
        },
      },
      {
        title: '分摊比例',
        width: 90,
        dataIndex: 'shareParamPopout',
        ellipsis: true,
        valueType: 'digit',
        fieldProps: {
          style: {
            width: '70px',
          },
        },
      },
      {
        title: '操作',
        width: 130,
        valueType: 'option',
        fieldProps: {
          style: {
            gap: '2px !important',
          },
        },
        render: (text, record, _, action) => [
          <a
            key="editable"
            onClick={() => {
              action?.startEditable?.(record.id);
            }}
          >
            编辑
          </a>,
          <a
            key="delete"
            onClick={() => {
              set_datasource(
                datasource.filter((item) => item.id !== record.id),
              );
            }}
          >
            删除
          </a>,
        ],
      },
    ];

    const saveHandle = async () => {
      onFinish && onFinish(datasource);
    };

    const getTableData = async () => {
      const resp = await getHasSetParamsList(record.id);
      if (resp) {
        set_datasource(resp);
      } else {
        return Promise.resolve([]);
      }
    };

    useEffect(() => {
      getTableData();
    }, []);

    return (
      <div>
        <EditableProTable
          columns={columns}
          className="EditableProTable"
          options={false}
          rowKey={rowKey}
          scroll={{ y: 400 }}
          tableAlertRender={false}
          recordCreatorProps={{
            record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
          }}
          editable={{
            onSave: async (rowKey, data, row) => {
              // console.log({rowKey, data, row,currentSelectedRow,datasource});

              const { index } = data;

              if (index > datasource.length - 1) {
                //新增
                const { id, label } = currentSelectedRow;
                set_datasource([
                  ...datasource,
                  {
                    shareParamName: label,
                    shareParamCode: data.shareParamCode,
                    shareParamPopout: data.shareParamPopout,
                    id: id,
                  },
                ]);
              } else {
                //编辑
                const newData = [...datasource];
                newData[index] = {
                  shareParamName: currentSelectedRow
                    ? currentSelectedRow.label
                    : data.shareParamName,
                  shareParamCode: data.shareParamCode,
                  shareParamPopout: data.shareParamPopout,
                  id: currentSelectedRow ? currentSelectedRow.id : data.id,
                };
                set_datasource([...newData]);
              }

              currentSelectedRow = undefined;
            },
          }}
          value={datasource}
        />
        <div className="footer">
          <span className="cancel" onClick={() => close()}>
            取消
          </span>
          <span className="ok" onClick={() => saveHandle()}>{`确认`}</span>
        </div>
      </div>
    );
  });

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

  return (
    <ModalForm
      className="TableSelecter"
      title={title}
      width={550}
      submitter={{
        render: false,
      }}
      open={open}
      modalProps={{
        closable: false,
      }}
    >
      <Table
        // ref={tableSelecterRef}
        record={undefined}
      ></Table>
    </ModalForm>
  );
};

export default EditTableModal;
