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 { dispatch } from '../../../../model'
import { AssetItem } from './AssetTable'
import AssetDetailDrawer from "./AssetDetailDrawer";

import './select-asset.less'

// const specialCol = ['数据关键用户', '业务数据owner', 'it责任人', '创建人', '更新人']

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

  const [loadingTemplates, setLoadingTemplates] = React.useState(false)
  const [loading, setLoading] = React.useState(false)
  const [loadingElements, setLoadingElements] = React.useState(false)
  const [templates, setTemplates] = React.useState()
  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 [detailParams, setDetailParams] = React.useState({
    visible: false,
    id: undefined,
    dirId: undefined,
  })

  React.useEffect(() => {
    getUsers()
    getTemplates()
  }, [])

  React.useEffect(() => {
    if (currentTemplate) {
      getTreeData()
      getElements()
    }
  }, [currentTemplate])

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

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

  useDebounceEffect(() => {
    if (currentTemplate) {
      getAssets()
    }
  }, [args], { wait: 300 })

  const treeData1 = React.useMemo(() => {
    if (treeData) {
      const newTreeData = produce(treeData, draft => {
        const setNode = (g) => {
          g.key = g.nodeId
          g.title = `${g.text} (${g.dataAssetAndSubDirCount})`
          g.children?.forEach((child) => {
            setNode(child)
          })
        }

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

      return newTreeData
    }

    return undefined
  }, [treeData])

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

  const [columns, tableData, total] = React.useMemo(() => {
    let [newColumns, newTableData] = [[], []]

    for (const element of elements??[]) {
      for (const name of element.names??[]) {
        const column = {
          title: name,
          dataIndex: name,
          ellipsis: true,
          render: (text, record) => {
            return (
              <Tooltip title={text}>
                <Typography.Text ellipsis={true}>
                {text}
                </Typography.Text>
              </Tooltip>
            );
          }
        }

        if (name === '资产项') {
          column.width = 250
          column.render = (text) => {
            let metadata = null
            try {
              metadata = JSON.parse(text)
            } catch(error) {
              metadata = text;
            }
            return (
              <AssetItem metadata={metadata} />
            );
          }
        }

        newColumns.push(column)
      }
    }

    if (!loadingElements) {
      for (const item of (data?.data??[])) {
        let index = 0
        let newItem = {}
        for (const elementValue of (item.elementValues??[])) {
          for (const value of elementValue.values) {
            if ((newColumns??[]).length > index) {
              const name = newColumns[index].dataIndex
              newItem[name] = value

              // if (specialCol.indexOf((name??'').toLowerCase()) !== -1) {
              //   const user = users?.filter((user)=>(user.pernr===value))
              //   if ((user??[]).length > 0) {
              //     newItem[name] = user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr;
              //   }
              // }
            }
  
            index++
          }
        }
  
        newTableData.push({...item, ...newItem})
      }
    }

    return [[...newColumns, actionCol], newTableData, data?.total??0]
  }, [elements, data, loadingElements, users])

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

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

  const getTemplates = () => {
    setLoadingTemplates(true)

    dispatch({
      type: 'assetmanage.getTemplates',
      callback: data => {
        setLoadingTemplates(false)
        const newTemplates = (data??[]).filter(item => item.structedStateEnum==='structured')

        setTemplates(newTemplates)
  
        if ((newTemplates??[]).length > 0) {
          setCurrentTemplate(newTemplates[0])
        }
      },
      error: () => {
        setLoadingTemplates(false)
      }
    })
  }

  const getTreeData = () => {
    setLoadingTreeData(true)
    dispatch({
      type: 'assetmanage.queryAllDirectoryAsTree',
      payload: {
        templateType: currentTemplate?.type
      },
      callback: data => {
        setLoadingTreeData(false)
        setTreeData(data)
      },
      error: () => {
        setLoadingTreeData(false)
      }
    }) 
  }

  const getElements = () => {
    setLoadingElements(true)
    dispatch({
      type: 'assetmanage.listFilterElementsGroupByType',
      payload: {
        templateType: currentTemplate?.type,
        isAdmin: true
      },
      callback: data => {
        setLoadingElements(false)
        setElements(data)
      },
      error: () => {
        setLoadingElements(false)
      }
    }) 
  }

  const getAssets = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.listDataAssetsByPage',
      payload: {
        dirId: node?.nodeId??'',
        pageNum: args.page,
        pageSize: args.size,
        keyword: args.keyword??'',
        recursive: true,
        templateType: currentTemplate?.type,
      },
      callback: data => {
        setLoading(false)
        setData(data)
      },
      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) => {
    setDetailParams({
      visible: true,
      id: record?.id,
      dirId: record?.dirId,
    })
  }

  return (
    <div className='post-select-asset'>
      <Row>
        <Col span={4}>
          <Select
            size='small'
            loading={loadingTemplates}
            value={currentTemplate?.type}
            onChange={(val) => {
              if (val) {
                const index = (templates??[]).findIndex(item => item.type === val)
                if (index !== -1) {
                  setCurrentTemplate(templates[index])
                  setNode()
                } else {
                  setCurrentTemplate()
                  setNode()
                }
              } else {
                setCurrentTemplate()
                setNode()
              }
            }}
            style={{ width: 100, marginBottom: 10 }}
          >
            {(templates??[]).map(item => (
              <Select.Option key={item.id} value={item.type}>{item.name}</Select.Option>
            ))}
          </Select>
          <Spin spinning={loadingTreeData}>
            <Tree
              className='tree'
              showLine 
              showIcon={false} 
              autoExpandParent={autoExpandParent}
              treeData={treeData1}
              selectedKeys={node?[node.nodeId]:[]}
              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) => {
                setArgsByParams({ keyword: e.target.value, page: 1 })
              }} 
              style={{ width: 200 }}
            />
          </div>
          <Table
            size='small'
            rowKey='id'
            extraColWidth={32}
            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)' }}
          />
          {
            (total!==0) && <Pagination
              style={{
                textAlign: 'center',
                marginTop: 15,
              }}
              showSizeChanger
              onChange={(page,size) => {
                setArgsByParams({ page, size })
              }}
              current={args.page}
              pageSize={args.size}
              defaultCurrent={1}
              total={total}
              showTotal={() => `共${total??0}项`}
            />
          }
        </Col>
      </Row>
      <AssetDetailDrawer 
        {...detailParams}
        readonly={true}
        onCancel={() => {
          setDetailParams({
            visible: false,
            id: undefined,
            dirId: undefined,
          })
        }}
      />
    </div>
  )
}

export default FC