import React, { useEffect, useState } from "react";
import { Modal, Button, Space, Tree, Row, Col, Table, Pagination } from "antd";
import LocalStorage from 'local-storage';

import { getAttributesByMetadataModel } from "../../../../service/dataassetmanager";

import { dispatch } from '../../../../model';
import { showMessage } from "../../../../util";

const FC = (props) => {
  const { visible, onCancel, id } = props;
  const [treeData, setTreeData] = useState(undefined);
  const [tableData, setTableData] = useState(undefined);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [currentTreeId, setCurrentTreeId] = useState(undefined);

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
      ellipsis: true,
    },
    {
      title: '模型名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '中文名称',
      dataIndex: 'cnName',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_,record) => (
        <a onClick={() => {
            dispatch({
              type: 'datamodel.requirementBind',
              payload: {
                data: {
                  techJobId: id,
                  assocStringIdList: [record.id]
                }
              },
              callback: data => {
                showMessage('warn', '关联成功');
                LocalStorage.set('modelChange', !(LocalStorage.get('modelChange')||false));
                let event = new Event('storage');
                event.key = 'modelChange';
                window?.dispatchEvent(event);
              }
            });
        }}>绑定</a>
      )
    }
  ];

  useEffect(() => {
    if (visible) {
      getTreeData();
    }
  }, [visible])

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

  const getTreeData = () => {
    dispatch({
      type: 'datamodel.refreshDataModelCatalog',
      callback: data => {
        if (data.subCatalogs && data.subCatalogs.length > 0) {
          setCurrentTreeId(data.subCatalogs[0].id);
        } 
        setTreeData(data.subCatalogs);
      }
    });
  }

  const getTableData = () => {
    dispatch({
      type: 'datamodel.getCurrentDataModelCatalog',
      payload: {
        easyDataModelerCatalogId: currentTreeId
      },
      callback: data => {
        setTableData(data.easyDataModelerDataModels);
      }
    });
  }

  const onTreeSelect = (keys, _) => {
    if (keys.length > 0) {
      setCurrentTreeId(keys[0]);
    }
  }

  const loop = (data) =>
    data?.map(item => { 
      if (item.subCatalogs && item.subCatalogs.length>0) {
        return {...item, title: item.name, key: item.id, children: loop(item.subCatalogs)};
      }

      return {...item, title: item.name, key: item.id, children: null};
    });

  return (
    <Modal
      title='选择模型'
      visible={ visible }
      centered
      width='90%'
      onCancel={() => { 
        setCurrentTreeId(undefined);
        onCancel?.(); 
      }}
      footer={
        <Space>
          <Button onClick={() => {
            setCurrentTreeId(undefined);
            onCancel?.(); 
          }}>取消</Button>
        </Space>
      }
      bodyStyle={{ padding: '24px', height: '70vh', overflow: 'auto' }}
    >
      <Row>
        <Col span={6}>
          <Tree
            showLine={true}
            showIcon={false}
            treeData={loop(treeData)}
            onSelect={onTreeSelect} 
            selectedKeys={currentTreeId ? [currentTreeId]: undefined}
          />
        </Col>
        <Col span={1}>
          <div style={{ width: 1, height: 'calc(70vh - 48px)', backgroundColor: '#f0f0f0' }} ></div>
        </Col>
        <Col span={17}>
          <Table 
            columns={columns}
            dataSource={tableData||[]}
            rowKey='id'
            pagination={{
              position: ['bottomCenter'],
              size: 'small',
              showTotal: (total) => `共${total}条`
            }}
          />
        </Col>
      </Row>
    </Modal>
  )
}

export default FC;