import React from 'react'
import { Row, Col, Spin, Tree, Input, Tooltip, Typography, Select, Pagination, Space, Button, } from 'antd'
import produce from 'immer'
import { useDebounceEffect } from "ahooks"
import classnames from 'classnames'

import Table from '../../ResizeableTable'
import { paginate } from '../../../../util'
import { dispatch } from '../../../../model'

import './select-data-service.less'
import { AppContext } from '../../../../App'

const visibleColNames = ['数据服务资产编码', '主题域分组', '主题域', '业务对象', '数据服务名称']

const FC = (props) => {
  const { session, onChange } = props
  const [args, setArgs] = React.useState({
    keyword: undefined,
  })
  const [pagination, setPagination] = React.useState({
    page: 1,
    size: 20,
  })
  const [loadingTreeData, setLoadingTreeData] = React.useState(false)
  const [treeData, setTreeData] = React.useState()
  const [node, setNode] = React.useState()
  const [rootNode, setRootNode] = React.useState()

  const [loading, setLoading] = React.useState(false)
  const [loadingElements, setLoadingElements] = React.useState(false)
  const [elements, setElements] = React.useState()
  const [data, setData] = React.useState()
  const [currentTemplate, setCurrentTemplate] = React.useState()
  const [selectedRows, setSelectedRows] = React.useState([])
  const [expandedKeys, setExpandedKeys] = React.useState([])
  const [autoExpandParent, setAutoExpandParent] = React.useState(false)
  const [users, setUsers] = React.useState()
  const [countMap, setCount] = React.useState()

  const app = React.useContext(AppContext)

  React.useEffect(() => {
    getUsers()
    getCount()
    getTreeData()
    getElements()
  }, [])

  React.useEffect(() => {
    setSelectedRows()
    if (node) {
      setArgsByParams({ keyword: '', page: 1 })
    } else {
      setArgsByParams({ page: 1 })
    }
  }, [node])

  useDebounceEffect(() => {
    if (rootNode) {
      getDataServices()
    }
  }, [rootNode, args], { wait: 300 })

  React.useEffect(() => {
    onChange?.(selectedRows)
  }, [selectedRows])

  const treeData1 = React.useMemo(() => {
    if (treeData) {
      const newTreeData = produce(treeData, draft => {
        const setNode = (g) => {
          g.key = g.id;
          g.title = g.name;
          if (g.status === -1) {
            g.title = `${g.title}_已停用`
          }
          if (countMap?.[g.id]!==undefined && countMap?.[g.id]!==null) {
            g.title = `${g.title} (${countMap[g.id]})`
          }
          g.children = [];
          
          (g.subCatalogs??[]).forEach((child) => {
            setNode(child)
            g.children.push(child)
          });
        }

        draft.forEach((child) => {
          setNode(child)
        })
      })

      return newTreeData
    }

    return undefined
  }, [treeData, countMap])

  const actionCol = {
    title: '操作',
    dataIndex: 'action',
    width: 80,
    render: (_, record) => {
      return (
        <Space>
          <a onClick={(e) => {
            e.stopPropagation();
            onDetailClick(record);
          }}>
            详情
          </a>
        </Space>
      )
    }
  }

  const columns = React.useMemo(() => {
    let newCols = [];
    elements?.forEach(item => {
      let col = {
        title: item.name,
        dataIndex: item.key,
        ellipsis: true,
        render: (_, record) => {
          return <Tooltip title={record.basicInfo?.[item.key]??''}>
            <Typography.Text ellipsis={true}>{record.basicInfo?.[item.key]??''}</Typography.Text>
          </Tooltip>
        }
      };

      // if (item.userSelected === true) {
      //   col.render = (_, record) => {
      //     const user = users?.filter((user)=>(user.pernr===record.basicInfo?.[item.key]));
      //     if (user && user.length > 0) {
      //       return <Tooltip title={user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr}>
      //         <Typography.Text ellipsis={true}>{user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr}</Typography.Text>
      //       </Tooltip>
      //     }
      //     return record.basicInfo?.[item.key];
      //   };
      // }

      newCols.push(col);
    });
 
    return [...(newCols.filter(item => visibleColNames.indexOf(item.title) !== -1)), actionCol];
  }, [elements, users, actionCol])

  const tableData = React.useMemo(() => {
    return paginate(data??[], pagination.page, pagination.size)
  }, [data, pagination])

  const setArgsByParams = React.useCallback((params) => {
    setArgs((prev) => {
      return {...prev, ...params}
    })
  }, [])

  const getUsers = () => {
    dispatch({
      type: 'pds.getOwners',
      callback: (data) => {
        setUsers(data)
      }
    })
  }

  const getCount = async () => {
    dispatch({
      type: 'pds.loadDataServiceCatalogServiceCount',
      callback: (data) => {
        let newData = {}
        for (const key in (data||{})) {
          let total = 0

          const item = data[key]
          for (const id in item) {
            if (id === '4') {
              total = total + item[id]??0
              newData[key] = total
            }
          }
        }

        setCount(newData) 
      }
    })
  }

  const getTreeData = () => {
    setLoadingTreeData(true)
    dispatch({
      type: 'pds.refreshCatalog',
      callback: (data) => {
        setLoadingTreeData(false)
        setRootNode(data)
        setTreeData(data?.subCatalogs)
      },
      error: () => {
        setLoadingTreeData(false)
      }
    })  
  }

  const getElements = () => {
    setLoadingElements(true)
    dispatch({
      type: 'pds.getAttrs',
      payload: {
        modelName: 'DataService'
      },
      callback: (data) => {
        setLoadingElements(false)
        setElements(data)
      },
      error: () => {
        setLoadingElements(false)
      }
    })
  }

  const getDataServices = () => {
    setLoading(true)
    
    if (args.keyword) {
      dispatch({
        type: 'pds.searchService',
        payload: {
          term: args.keyword,
          namespace: app?.env?.domainId??'',
          isExcludeOtherOwner: false,
          stateId: '4_0'
        },
        callback: (data) => {
          setLoading(false)
          setData(data??[])
        },
        error: () => {
          setLoading(false)
        }
      })
    } else {
      dispatch({
        type: 'pds.getServices',
        payload: {
          pdsDataServiceCatalogId: node?node?.id:rootNode?.id,
          namespace: app?.env?.domainId??'',
          isExcludeOtherOwner: false,
          stateId: '4_0',
        },
        callback: (data) => {
          setLoading(false)
          setData(data?.pdsdataServices??[])
        },
        error: () => {
          setLoading(false)
        }
      })
    }
  }

  const onTreeExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(false)
  }

  const onTreeSelect = (selectedKeys, { selectedNodes }) => {
    if (selectedKeys.length === 0 || selectedNodes.length === 0) {
      setNode()
      return
    }

    setNode(selectedNodes[0])
  }

  const onDetailClick = (record) => {
    app?.setGlobalState && app?.setGlobalState({
      message: 'data-govern-show-service-detail',
      data: {
        id: record.id,
        isOnlyEnding: true
      }
    })
  }

  return (
    <div className='post-select-data-service'>
      <Row>
        <Col span={4}>
          <Spin spinning={loadingTreeData}>
            <Tree
              className='tree'
              showLine 
              showIcon={false} 
              autoExpandParent={autoExpandParent}
              treeData={treeData1}
              selectedKeys={node?[node.id]:[]}
              expandedKeys={expandedKeys}
              onSelect={onTreeSelect}
              onExpand={onTreeExpand}
            />
          </Spin>
        </Col>
        <Col span={20}>
          <div
            style={{
              display: 'flex',
              padding: '0px 0px 15px',
              alignItems: 'center',
              justifyContent: 'flex-end',
            }}>
            <Input size="middle"
              placeholder="通过服务名称全文检索"
              value={args.keyword}
              bordered={true} allowClear
              onChange={(e) => {
                setNode()
                setArgsByParams({ keyword: e.target.value, page: 1 })
              }} 
              style={{ width: 200 }}
            />
          </div>
          <Table
            size='small'
            extraColWidth={32}
            rowKey='id'
            loading={loading||loadingElements}
            columns={columns}
            dataSource={tableData??[]}
            pagination={false}
            rowSelection={{
              selectedRowKeys: (selectedRows??[]).map(item => item.id),
              onChange: (selectedRowKeys, selectedRows) => {
                setSelectedRows(selectedRows)
              },
            }}
            scroll={{ y: 'calc(80vh - 170px)' }}
          />
          {
            (data??[]).length!==0 && <Pagination
              style={{
                textAlign: 'center',
                marginTop: 15,
              }}
              showSizeChanger
              onChange={(page,size) => {
                setPagination({page, size})
              }}
              current={pagination.page}
              pageSize={pagination.size}
              defaultCurrent={1}
              total={(data??[]).length}
              showTotal={(total) => `共${total??0}项`}
            />
          }
        </Col>
      </Row>
    </div>
  )
}

export default FC
