import React, { useEffect, useState } from "react";
import { Modal, Button, Space, Tree, Row, Col, Table, Pagination, Select, Input, Divider, Spin } from "antd";
import { getAttributesByMetadataModel } from "../../../../service/dataassetmanager";

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

const options = [
  { name: '基础数据名称', key: 'name' },
  { name: '基础数据编码', key: 'code' },
]

const FC = (props) => {
  const { visible, onCancel, id } = props;
  const [treeData, setTreeData] = useState(undefined);
  const [tableData, setTableData] = useState(undefined);
  const [total, setTotal] = useState(0);
  const [ pagination, setPagination ] = useState( { pageNum: 1, pageSize: 20 } );
  const [loadingTree, setLoadingTree] = useState(false);
  const [loadingTable,setLoadingTable] = useState(false);
  const [currentTreeParams, setCurrentTreeParams] = useState({
    treeId: undefined,
    dataType: undefined,
  });
  const [queryProperty, setQueryProperty] = useState(options[0].key);
  const [keyword, setKeyword] = useState(undefined);
  const debouncedKeyword = useDebounce(keyword, 300);

  const { pageNum, pageSize } = pagination;

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
      ellipsis: true,
    },
    {
      title: '基础数据编码',
      dataIndex: 'code',
      ellipsis: true,
      render: (text, record) => {
        return <a onClick={() => {
          onOk(record._id);
        }}>
          {text}
        </a>
      }
    },
    {
      title: '基础数据名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (text, record) => {
        return <a onClick={() => {
          onOk(record._id);
        }}>
          {text}
        </a>
      }
    },
  ];

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

  useEffect(() => {
    if (visible && currentTreeParams.treeId) {
      getTableData();
    }
  }, [visible, pagination, currentTreeParams, queryProperty, debouncedKeyword])

  const getTreeData = () => {
    setLoadingTree(true);
    dispatch({
      type: 'assetmanage.getStandardTree',
      payload: {
        namePath: 0,
        needOrg: true,
        parentClass: 'Catalog'
      },
      callback: data => {
        setLoadingTree(false);
        const filterData = data?.filter(item => item.name!=='草稿' && item.name!=='业务术语');

        if (filterData && filterData.length > 0) {
          if (filterData[0].cnName === '指标标准') {
            setCurrentTreeParams({ treeId: filterData[0]._id, dataType: 'IndicatorStandard' });
          } else if (filterData[0].cnName === '维度标准') {
            setCurrentTreeParams({ treeId: filterData[0]._id, dataType: 'DimensionStandard' });
          } else {
            setCurrentTreeParams({ treeId: filterData[0]._id, dataType: filterData[0].type });
          }
        } 

        setTreeData(filterData);
      },
      error: () => {
        setLoadingTree(false);
      }
    });
  }

  const getTableData = () => {
    setLoadingTable(true);
    dispatch({
      type: 'assetmanage.getStandardList',
      payload: {
        params: {
          page: pageNum,
          size: pageSize,
          parentId: currentTreeParams.treeId,
          keyword: debouncedKeyword,
          queryProperty: queryProperty,
        },
        data: [`Catalog,StandardCatalog,${currentTreeParams.dataType}`]
      },
      callback: data => {
        setLoadingTable(false);
        data.content?.forEach(item => {
          item.children = null;
        });
        setTableData(data.content);
        setTotal(data.totalElements);
      },
      error: () => {
        setLoadingTable(false);
      }
    });
  }

  const onOk = (standardId) => {
    dispatch({
      type: 'assetmanage.getMetadataStandardList',
      payload: {
        data: {
          metadataId: id
        },
        params: {
          page: 1,
          size: 999999
        }
      },
      callback: data => {
        if ((data.content||[]).length === 0) {
          dispatch({
            type: 'assetmanage.standardBatchMetadata',
            payload: {
              params: {
                metadataIds: id,
                standardId
              },
            },
            callback: () => {
              showMessage('success', '关联成功');
              onCancel?.(true);
            }
          });
        } else {
          dispatch({
            type: 'assetmanage.deleteStandardBatchMetadata',
            payload: {
              params: {
                ids: data.content?.map(item => item.id).toString()
              }
            },
            callback: () => {
              dispatch({
                type: 'assetmanage.standardBatchMetadata',
                payload: {
                  params: {
                    metadataIds: id,
                    standardId
                  },
                },
                callback: () => {
                  showMessage('success', '关联成功');
                  onCancel?.(true);
                }
              });
            }
          });
        }
      },
    });
  }

  const onTreeSelect = (keys, {node}) => {
    if (keys.length > 0) {
      let paths = node.namePath.split(',');
      if(paths[1]==='指标标准'){
        setCurrentTreeParams({ treeId: keys[0], dataType: 'IndicatorStandard' });
      }else if(paths[1]==='维度标准'){
        setCurrentTreeParams({ treeId: keys[0], dataType: 'DimensionStandard' });
      }else{
        setCurrentTreeParams({ treeId: keys[0], dataType: node.type });
      }
    }
  }

  const onSelectChange = (value) => {
    setQueryProperty(value);
  }

  const onSearchChange = (e) => {
    setKeyword(e.target.value);
  }

  const changeCurrent = (page,size) => {
    setPagination({ pageNum: page, pageSize: size });
  }

  const reset = () => {
    setLoadingTree(false);
    setLoadingTable(false);
    setCurrentTreeParams({
      treeId: undefined,
      dataType: undefined,
    });
    setQueryProperty(options[0].key);
    setKeyword(undefined);
    setPagination({ pageNum: 1, pageSize: 20 });
  }

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

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

  return (
    <Modal
      title='选择标准'
      visible={ visible }
      centered
      width='90%'
      onCancel={() => { 
        reset();
        onCancel?.(); 
      }}
      footer={
        <Space>
          <Button onClick={() => {
            reset();
            onCancel?.(); 
          }}>取消</Button>
        </Space>
      }
      bodyStyle={{ padding: '24px', height: '70vh', overflow: 'auto' }}
    >
      <Row>
        <Col span={5}>
          <Spin spinning={loadingTree}>
            <Tree
              showLine={true}
              showIcon={false}
              treeData={loop(treeData)}
              onSelect={onTreeSelect} 
              selectedKeys={currentTreeParams.treeId ? [currentTreeParams.treeId]: undefined}
            />
          </Spin>
        </Col>
        <Col span={1}>
          <div style={{ width: 1, height: 'calc(70vh - 48px)', backgroundColor: '#f0f0f0' }} ></div>
        </Col>
        <Col span={18}>
          <div>
            <Space>
              <Select
                value={queryProperty}
                onChange={onSelectChange}
                style={{ width: 160 }}
              >
              {
                options.map((option, index) => {
                  return (
                    <Select.Option key={index} value={option.key} >{option.name}</Select.Option>
                  )
                })
              }
              </Select>
              <Input value={keyword} onChange={onSearchChange} placeholder='请输入关键字' />
            </Space>
          </div>
          <Divider style={{ margin: '10px 0' }} />
          <Table 
            loading={loadingTable}
            columns={columns}
            dataSource={tableData||[]}
            rowKey='_id'
            pagination={false}
          />
          <Pagination
            className="m-3"
            size='small'
            position={['bottomLeft']}
            onChange={changeCurrent}
            onShowSizeChange={changeCurrent}
            current={pageNum}
            pageSize={pageSize}
            defaultCurrent={1}
            total={total}
            showTotal={total => `共 ${total} 条`}
          />
        </Col>
      </Row>
    </Modal>
  )
}

export default FC;