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 [activeKey, setActiveKey] = React.useState('asset')
  const [keyword, setKeyword] = React.useState()
  const [pagination, setPagination] = React.useState({
    pageNum: 1,
    pageSize: 20,
  })
  const [loadingAssets, setLoadingAssets] = React.useState(false)
  const [assets, setAssets] = React.useState()
  const [loadingServices, setLoadingServices] = React.useState(false)
  const [services, setServices] = 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, () => ({
    relations: {
      postAssets: assets??[],
      postServices: services??[]
    }
  }), [assets, services])

  React.useEffect(() => {
    onChange?.({
      postAssets: assets??[],
      postServices: services??[]
    })
  }, [assets, services])

  React.useEffect(() => {
    if (item?.id) {
      getRelatedAssets()
      getRelatedServices()
    }
  }, [item])

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

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

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

  const seriveCols = [
    {
      title: '序号',
      dataIndex: 'index',
      width:60,
      render:(_, __, index)=> ((pagination.pageNum-1)*pagination.pageSize+index+1)
    },
    {
      title: '路径',
      dataIndex: 'path',
    },
    {
      title: '数据服务资产编号',
      dataIndex: 'relatedServiceCode',
    },
    {
      title: '数据服务名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 80,
      render: (_, record) => {
        return (
          <Space>
            <a onClick={(e) => {
              e.stopPropagation();
              app?.setGlobalState && app?.setGlobalState({
                message: 'data-govern-show-service-detail',
                data: {
                  id: record.relatedServiceId,
                  isOnlyEnding: true
                }
              })
            }}>
              详情
            </a>
        </Space>
        )
      }
    }
  ]

  const getRelatedAssets = () => {
    setLoadingAssets(true)

    let url = (reference===AssetDraftReference)?'assetmanage.getDraftRelatedAssets':'assetmanage.getRelatedAssets'
    let params = (reference===AssetDraftReference)?{
      draftId: item?.id
    }:{
      dataAssetId: item?.id
    }

    dispatch({
      type: url,
      payload: {
        params
      },
      callback: (data) => {
        setLoadingAssets(false)
        setAssets(data)
      },
      error: () => {
        setLoadingAssets(false)
      }
    })
  }

  const getRelatedServices = () => {
    setLoadingServices(true)

    let url = (reference===AssetDraftReference)?'assetmanage.getDraftRelatedServices':'assetmanage.getRelatedServices'
    let params = (reference===AssetDraftReference)?{
      draftId: item?.id
    }:{
      dataAssetId: item?.id
    }

    dispatch({
      type: url,
      payload: {
        params
      },
      callback: (data) => {
        setLoadingServices(false)
        setServices(data)
      },
      error: () => {
        setLoadingServices(false)
      }
    })
  }

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

  const onDeleteClick = () => {
    if (activeKey === 'asset') {
      setAssets(prevAssets => {
        const filterData = (prevAssets??[]).filter(item => (selectedRows??[]).map(_item => _item.relatedAssetId).indexOf(item.relatedAssetId)===-1)

        return filterData
      })
    } else if (activeKey === 'service') {
      setServices(prevServices => {
        const filterData = (prevServices??[]).filter(item => (selectedRows??[]).map(_item => _item.relatedServiceId).indexOf(item.relatedServiceId)===-1)

        return filterData
      })
    }

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

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

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

          return [...prevAssets??[], ...filterData]
        })
      } else if (activeKey === 'service') {
        setServices(prevServices => {
          const filterData = (data??[]).filter(item => (prevServices??[]).map(_item => _item.relatedServiceId).indexOf(item.relatedServiceId)===-1)

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

  return (
    <div>
      <Tabs activeKey={activeKey} onChange={(val) => { 
        setActiveKey(val) 
        setPagination({ ...pagination, pageNum: 1 })
        setSelectedRows()
      }}>
        <Tabs.TabPane tab='关联资产' key='asset' />
        <Tabs.TabPane tab='关联服务' key='service' />
      </Tabs>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        {
          action !== 'detail' ? <Space>
            <Button onClick={onEditClick}>编辑</Button>
            <Tooltip title={(selectedRows??[]).length===0?(activeKey==='asset'?'请先选择资产':'请先选择服务'):''}>
              <Button disabled={(selectedRows??[]).length===0} onClick={onDeleteClick}>删除</Button>
            </Tooltip>
          </Space> : <div />
        }
        <Input size="middle"
          placeholder={activeKey==='asset'?'搜索资产名称':'搜索服务名称'}
          value={keyword}
          bordered={true} allowClear
          style={{ width: 200 }}
          onChange={(e) => {
            setPagination({...pagination, pageNum: 1})
            setKeyword(e.target.value)
          }} />
      </div>
      <div className='mt-3'>
        <Table
          extraColWidth={32}
          rowKey={activeKey==='asset'?'relatedAssetId':'relatedServiceId'}
          loading={loadingAssets||loadingServices}
          columns={activeKey==='asset'?assetCols:seriveCols}
          dataSource={tableData??[]}
          pagination={false}
          rowSelection={{
            selectedRowKeys: (selectedRows??[]).map(item => (activeKey==='asset')?item.relatedAssetId:item.relatedServiceId),
            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