import React from 'react'
import { debounceTime, Subject } from 'rxjs'
import { Space, Input, Table, Button, Tooltip, Modal, Pagination, Typography } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'

import { defaultPage, usePage } from '../../../util/page'
import { dispatch } from '../../../model'
import AddEvaluate from './add'
 
import './index.less'
import { showMessage } from '../../../util'
import { AppContext } from '../../../App'

const FC = (props) => {
  const [args, setArgs] = React.useState(() => ({
    params: {
      page: defaultPage.pageNum, 
      size: defaultPage.pageSize, 
      keyword: undefined,
      startTime: undefined,
      endTime: undefined, 
    },
  }))

  const [loading, setLoading] = React.useState(false)
  const [data, setData] = React.useState()
  const [total, setTotal] = React.useState()
  const [elements, setElements] = React.useState()
  const $keyword = React.useMemo(() => new Subject(), [])
  const [keyword, setKeyword] = React.useState()
  const [addEvaluateParams, setAddEvaluateParams] = React.useState({
    visible: false,
    item: undefined,
    action: undefined
  })
  const [selectedRows, setSelectedRows] = React.useState([])

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

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

  const setArgsAndPage = React.useCallback((params) => {
    // 设置查询参数时将分页置为1
    setPage(prevpg => {

      setArgs((prev) => {
        const newparams = params ? { ...prev.params, ...params } : undefined
        return { params: { ...newparams, page: 1, size: prevpg.pageSize } }
      })

      return ({ ...prevpg, pageNum: 1 })
    })
    //eslint-disable-next-line react-hooks/exhaustive-deps    
  }, [])

  const setPageAndArgs = React.useCallback((page) => {
    setPage(prev => ({ ...prev, ...page }))
    setArgs((prev) => {
      return { params: { ...prev.params, page: page.pageNum, size: page.pageSize } }
    })
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  React.useEffect(() => {
    const $$keyword = $keyword.pipe(debounceTime(1000)).subscribe((keyword) => {
      setArgsAndPage({ keyword })
    })

    return () => {
      $$keyword.unsubscribe()
    }
  }, [])

  React.useEffect(() => {
    getEvaluations()
  }, [args])

  const cols = [
    {
      title: '方案名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '评估范围',
      dataIndex: 'dirs',
      render: (dirs) => {
        const dirStr = (dirs??[]).map(item => item.name).toString()
        return (
          <Tooltip title={dirStr}>
            <Typography.Text ellipsis={true}>
            {dirStr}
            </Typography.Text>
          </Tooltip>
        )
      }
    },
    {
      title: '评估要素',
      dataIndex: 'elementIds',
      render: (elementIds) => {
        const elementStr = (elements??[]).filter(item => (elementIds??[]).indexOf(item.id) !== -1).map(item => item.name).toString()
        return (
          <Tooltip title={elementStr}>
            <Typography.Text ellipsis={true}>
            {elementStr}
            </Typography.Text>
          </Tooltip>
        )
      }
    },
    {
      title: '总得分',
      dataIndex: 'score',
      ellipsis: true,
    },
    {
      title: '资产总数',
      dataIndex: 'dataAssetTotalNum',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTimestamp',
      ellipsis: true,
      render: (_, record) => record.createTimestamp ? new Date(record.createTimestamp).toLocaleString() : ''
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_,record) => (
        <a onClick={() => {
          setAddEvaluateParams({
            visible: true,
            item: record,
            action: 'edit',
          })
        }}>编辑</a>
      )
    }
  ]

  const getEvaluations = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.getEvaluations',
      payload: {
        pageNum: args.params.page,
        pageSize: args.params.size,
        keyword: args.params.keyword,
      },
      callback: data => {
        setLoading(false)
        setData(data?.data)
        setTotal(data?.total)
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const getElements = () => {
    dispatch({
      type: 'assetmanage.listElements',
      callback: data => {
        setElements(data??[])
      }
    })
  }

  return (
    <div className='asset-evalute'>
      <div className='header px-3'>
        <Space>
          <Button onClick={() => {
            setAddEvaluateParams({
              visible: true,
              item: undefined,
              action: 'add',
            })
          }}>新增</Button>
          <Button onClick={() => {
            getEvaluations()
          }}>刷新</Button>
          <Tooltip title={((selectedRows??[]).length===0)?'请先选择评估方案':''}>
            <Button 
              disabled={(selectedRows??[]).length===0}
              onClick={() => {
                modal.confirm({
                  title: '确认运行选中的评估方案吗?',
                  icon: <ExclamationCircleOutlined />,
                  okText: '确认',
                  cancelText: '取消',
                  onOk: () => {
                    dispatch({
                      type: 'assetmanage.runEvaluations',
                      payload: {
                        params: {
                          evaluationProjectIds: (selectedRows??[]).map(item => item.id).toString()
                        }
                      },
                      callback: data => {
                        showMessage('success', '运行成功')
                      },
                    })
                  }
                })
              }}>运行</Button>
          </Tooltip>
          <Tooltip title={((selectedRows??[]).length===0)?'请先选择评估方案':''}>
            <Button 
              disabled={(selectedRows??[]).length===0}
              onClick={() => {
                modal.confirm({
                  title: '确认删除选中的评估方案吗?',
                  icon: <ExclamationCircleOutlined />,
                  okText: '确认',
                  cancelText: '取消',
                  onOk: () => {
                    dispatch({
                      type: 'assetmanage.deleteEvaluations',
                      payload: {
                        params: {
                          evaluationProjectIds: (selectedRows??[]).map(item => item.id).toString()
                        }
                      },
                      callback: data => {
                        showMessage('success', '删除成功')
                        getEvaluations()
                      },
                    })
                  }
                })
              }}>删除</Button>
          </Tooltip>
        </Space>
        <Space>
          <Input size="middle"
            placeholder="方案名称"
            value={keyword}
            bordered={true} allowClear
            onChange={(e) => {
              const keyword = e.target.value
              setKeyword(keyword)
              $keyword.next((keyword??'').trim())
            }}
            style={{ 
              width: 250
            }} 
          />
        </Space>
      </div>
      <div className='px-3 pt-3'>
        <Table
          scroll={{y: 'calc(100vh - 285px)'}}
          rowKey='id'
          loading={loading}
          columns={cols}
          dataSource={data||[]}
          pagination={false}
          rowSelection={{
            selectedRowKeys: (selectedRows??[]).map(item => item?.id),
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRows(selectedRows)
            },
          }}
        />
        <Pagination
          className="text-center mt-3"
          showSizeChanger
          showQuickJumper
          onChange={(_pageNum, _pageSize) => {
            setPageAndArgs({ pageNum: _pageNum||1, pageSize: _pageSize || 20 })
          }}
          onShowSizeChange={(_pageNum, _pageSize) => {
            setPageAndArgs({ pageNum: _pageNum||1, pageSize: _pageSize || 20 })
          }}
          current={page.pageNum}
          pageSize={page.pageSize}
          defaultCurrent={1}
          total={total}
          pageSizeOptions={[10,20]}
          showTotal={total => `共 ${total} 条`}
        />
      </div>
      <AddEvaluate 
        {...addEvaluateParams}
        onCancel={(refresh) => {
          setAddEvaluateParams({
            visible: false,
            item: undefined,
            action: undefined
          })

          refresh && getEvaluations()
        }}
      />
      {contextHolder}  
    </div>
  )
}

export default FC