import React from 'react'
import { Tabs, Space, Button, Input, Pagination, Tooltip, Modal } from 'antd'

import { paginate } from '../../../../util'
import Table from '../../ResizeableTable'
import SelectResource from './select-resource'
import { dispatch } from '../../../../model';
import { AssetDraftReference } from '../../../../util/constant'
import AssetDetailDrawer from "./AssetDetailDrawer";
import { AppContext } from '../../../../App'

const FC = React.forwardRef(function ({ item, reference, action, onChange }, ref) {
  const [keyword, setKeyword] = React.useState()
  const [pagination, setPagination] = React.useState({
    pageNum: 1,
    pageSize: 20,
  })
  const [assets, setAssets] = React.useState()
  const [selectedRows, setSelectedRows] = React.useState()
  const [selectResourceParams, setSelectResourceParams] = React.useState({
    visible: false,
    item: undefined,
    type: undefined,
  })
  const [detailParams, setDetailParams] = React.useState({
    visible: false,
    id: undefined,
    dirId: undefined,
  })

  const app = React.useContext(AppContext)
  const [modal, contextHolder] = Modal.useModal()

  React.useImperativeHandle(ref, () => ({
    assets
  }), [assets])

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

  React.useEffect(() => {
    setAssets(item?.businessRelations)
  }, [item])

  const [tableData, total] = React.useMemo(() => {
    let newTableData = [...assets??[]]
    if (keyword) {
      newTableData = (newTableData??[]).filter(item => (item.name??'').indexOf(keyword) !== -1)
    }

    return [paginate(newTableData, pagination.pageNum, pagination.pageSize), (newTableData??[]).length]
  }, [assets, keyword, pagination])

  const assetCols = [
    {
      title: '序号',
      dataIndex: 'index',
      width:60,
      render:(_, __, index)=> ((pagination.pageNum-1)*pagination.pageSize+index+1)
    },
    {
      title: '路径',
      dataIndex: 'relatedDataAssetPath',
    },
    {
      title: '资产编码',
      dataIndex: 'relatedDataAssetCode',
    },
    {
      title: '名称',
      dataIndex: 'relatedDataAssetEnName',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 80,
      render: (_, record) => {
        return (
          <Space>
            <a onClick={(e) => {
              e.stopPropagation();
              setDetailParams({
                visible: true,
                id: record?.relatedDataAssetId,
              })
            }}>
              详情
            </a>
        </Space>
        )
      }
    }
  ]

  const onEditClick = () => {
    setSelectResourceParams({
      visible: true,
      item,
      type: 'asset',
    })
  }

  const onDeleteClick = () => {
    setAssets(prevAssets => {
      const filterData = (prevAssets??[]).filter(item => (selectedRows??[]).map(_item => _item.relatedDataAssetId).indexOf(item.relatedDataAssetId)===-1)

      return filterData
    })

    setSelectedRows(prevSelectedRows => {
      return []
    })
  }

  const onSelectResourceCancel = (data) => {
    setSelectResourceParams({
      visible: false,
      item: undefined,
      type: undefined
    })

    if (data) {
      setAssets(prevAssets => {
        const filterData = (data??[]).filter(item => (prevAssets??[]).map(_item => _item.relatedDataAssetId).indexOf(item.relatedDataAssetId)===-1)

        return [...prevAssets??[], ...filterData]
      })
    }
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Space>
          {
            action !== 'detail' && <React.Fragment>
              <Button onClick={onEditClick}>新增</Button>
              <Tooltip title={(selectedRows??[]).length===0?'请先选择资产':''}>
                <Button disabled={(selectedRows??[]).length===0} onClick={onDeleteClick}>删除</Button>
              </Tooltip>
            </React.Fragment>
          }
        </Space>  
      </div>
      <div className='mt-3'>
        <Table
          extraColWidth={32}
          rowKey='relatedDataAssetId'
          columns={assetCols}
          dataSource={tableData??[]}
          pagination={false}
          rowSelection={{
            selectedRowKeys: (selectedRows??[]).map(item => item.relatedDataAssetId),
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRows(selectedRows)
            },
          }}
        />
        {
          (total!==0) && <Pagination
            className="text-center my-3"
            showSizeChanger
            onChange={(page,size) => {
              setPagination({ pageNum: page, pageSize: size })
            }}
            current={pagination.pageNum}
            pageSize={pagination.pageSize}
            defaultCurrent={1}
            total={total}
            showTotal={() => `共${total??0}项`}
          />
        }
      </div>
      <SelectResource
        {...selectResourceParams}
        onCancel={onSelectResourceCancel}
      />
      <AssetDetailDrawer 
        {...detailParams}
        readonly={true}
        onCancel={() => {
          setDetailParams({
            visible: false,
            id: undefined,
            dirId: undefined,
          })
        }}
      />
      {contextHolder}
    </div>
  )
})

export default FC