
import React, { useState, useEffect } from 'react';
import { Modal,Button } from 'antd';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';

import ProFormDigit from '@ant-design/pro-form/lib/components/Digit';
import { getClolumnTableData } from '@/pages/setting/reportSet/reportSetting/service';
import { arrayMoveImmutable } from 'array-move';
import { ProColumns } from '@ant-design/pro-components';
import { BMSTable } from '@/components/BMSTable';


const SetColWidComponent = ({reportCode,onOkHandle}:{reportCode:string,onOkHandle?:(data:any[])=>void}) => {
    const [dataSource, setDataSource] = useState<any[]>([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const urlReportCode = reportCode; // Replace with actual report code
  
    useEffect(() => {
      const fetchData = async () => {
        const resp = await getClolumnTableData({ reportCode: urlReportCode });
        if (resp) {
          const dataSorted = resp.sort((prev: any, cur: any) => prev.sort - cur.sort);
          setDataSource(dataSorted);
        }
      };
      fetchData();
    }, [urlReportCode]);
  
    const SortableItem = SortableElement((props: any) => <tr className="sortable-item" {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);
    const DragHandle = SortableHandle(() => <img width={16} style={{ cursor: 'pointer' }} src={require('../../../../static/tuozhuai_icon.png')} alt="" />);
  
    const onSortEnd = ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
      if (oldIndex !== newIndex) {
        const newData = arrayMoveImmutable([...dataSource], oldIndex, newIndex).filter((el) => !!el);
        const updatedSortArr = newData.map((item: any, index: number) => ({ ...item, sort: index }));
        setDataSource(updatedSortArr);
      }
    };
  
    const DraggableContainer = (props: any) => (
      <SortContainer
        useDragHandle
        disableAutoscroll
        helperClass="row-dragging"
        onSortEnd={onSortEnd}
        {...props}
      />
    );
  
    const DraggableBodyRow = (props: any) => {
      const { className, style, ...restProps } = props;
      const index = dataSource.findIndex((x) => x.id === restProps['data-row-key']);
      return <SortableItem index={index} {...restProps} />;
    };
  
    const onChangeHandle = (value:any, record: any) => {
      const newDataSource = [...dataSource].map((a) => {
        if (a.id === record.id) {
          return {
            ...a,
            width: value
          };
        } else {
          return a;
        }
      });
      setDataSource(newDataSource);
    };
  
    const modalTableColumns: ProColumns[] = [
      {
        title: '排序',
        dataIndex: 'sort',
        width: 60,
        className: 'drag-visible',
        render: () => <DragHandle />
      },
      {
        title: '列标题',
        ellipsis: true,
        dataIndex: 'columnHeaderText',
      },
      {
        title: '列名称',
        ellipsis: true,
        dataIndex: 'columnName',
      },
      {
        title: '列宽',
        dataIndex: 'width',
        render: (num: any, record: any) => {
          return (
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center' }}>
              <ProFormDigit 
                noStyle 
                width={70} 
                fieldProps={{
                  defaultValue: num,
                  onBlur: (value) => onChangeHandle(value, record)
                }} 
              />
            </div>
          );
        }
      }
    ];
  
    const showModal = () => {
      setIsModalVisible(true);
    };
  
    const handleOk = () => {
      setIsModalVisible(false);
      onOkHandle&&onOkHandle(dataSource)
    };
  
    const handleCancel = () => {
      setIsModalVisible(false);
    };
  
    return (
      <div>
        <div onClick={showModal}>设置列宽</div>
        <Modal
          title="设置列宽"
          open={isModalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
          width={500}
        >
          <BMSTable
            rowKey='id'
            scroll={{ y: 450 }}
            pagination={false}
            columns={modalTableColumns}
            dataSource={dataSource}
            components={{
              body: {
                wrapper: DraggableContainer,
                row: DraggableBodyRow,
              },
            }}
          />
        </Modal>
      </div>
    );
  };
  
  export default SetColWidComponent;