import React, { Key, useEffect, useState } from 'react';
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 { getProjectShareParamsSetTableData } from '../projectShareParamsSet/service';

// 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[]>([]);
    const [currentSelectedRow, set_currentSelectedRow] =
      useState<any>(undefined);

    const columns: ProColumns[] = [
      {
        title: '项目名称',
        dataIndex: 'shareParamName',
        ellipsis: true,
        valueType: 'select',
        request: async () => {
          const resp = await getProjectShareParamsSetTableData();
          if (resp) {
            return resp.map((a: any) => ({
              label: a.shareParamName,
              value: a.shareParamCode,
            }));
          }
          return [];
        },
        fieldProps: {
          onSelect: (a: any, b: any, c: any) => {
            set_currentSelectedRow(b);
          },
        },
      },
      {
        title: '占比',
        dataIndex: 'percent',
        ellipsis: true,
        valueType: 'digit',
      },
      {
        title: '操作',
        valueType: 'option',
        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);
    };

    useEffect(() => {
      const { shareParamCostDetails = [] } = record;
      set_datasource([...(shareParamCostDetails ? shareParamCostDetails : [])]);
    }, []);

    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});
              const { index } = data;

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

              set_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;
