import React from 'react'
import { Button, Modal, Spin, Typography, Tooltip, Input } from 'antd'

import { dispatch } from '../../../../model'
import Table from '../../../../util/Component/Table'
import { showMessage } from '../../../../util'
import Update from './update-rule-template'

const FC = (props) => {
  const { visible, node, onCancel } = props
  const [waiting, setWaiting] = React.useState(false)
  const basicRef = React.useRef()

  const close = (refresh = false) => {
    setWaiting(false)
    onCancel?.(refresh)
  }

  const save = () => {
    const selectedRows = basicRef.current?.selectedRows
    if ((selectedRows??[]).length === 0) {
      showMessage('warn', '请先选择规则模板')
      return
    }

    setWaiting(true)
    dispatch({
      type: 'datamodel.addRule',
      payload: {
        params: {
          catalogId: node?.id,
          templateIds: (selectedRows??[]).map(item => item.id).toString()
        }
      },
      callback: data => {
        close(true)
      },
      error: () => {
        setWaiting(false)
      }
    })
  }

  const footer = React.useMemo(() => {
    return [
      <Button key='cancel'
        onClick={() => close()}
      >取消</Button>,
      <Button key='save' type='primary'
        onClick={() => save()}
      >确定</Button>
    ]
  }, [close, save])

  return (
    <Modal
      visible={visible}
      footer={footer}
      width='80%'
      bodyStyle={{ padding: '15px', overflowX: 'auto', maxHeight: '80vh' }}
      title='新增检查规则'
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      <Spin spinning={waiting}>
        <Basic ref={basicRef} />
      </Spin>
    </Modal>
  )
}

export default FC

export const Basic = React.forwardRef(function ({}, ref) {
  const [keyword, setKeyword] = React.useState()
  const [loading, setLoading] = React.useState(false)
  const [data, setData] = React.useState()
  const [selectedRows, setSelectedRows] = React.useState()
  const [updateParams, setUpdateParams] = React.useState({
    visible: false,
    type: undefined, 
    item: undefined
  })

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

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

  const cols = React.useMemo(() => {
    return ([
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (_, __, index) => `${index+1}`
      },
      {
        title: '规则编号',
        dataIndex: 'number',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '规则中文名称',
        dataIndex: 'name',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              <a onClick={() => {
                setUpdateParams({
                  visible: true,
                  type: 'detail',
                  item: record
                })
              }}>
              { text }
              </a>
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '规则描述',
        dataIndex: 'remark',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '检查类型',
        dataIndex: 'checkTypeName',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
    ])
  }, [])

  const _data = React.useMemo(() => {
    const _keyword = (keyword??'').trim()
    return (data??[]).filter(item => !_keyword 
      || (item.name??'').indexOf(_keyword) !== -1
      || (item.remark??'').indexOf(_keyword) !== -1
    )
  }, [data, keyword])

  const getTemplates = () => {
    setLoading(true)
    dispatch({
      type: 'datamodel.getRuleTemplateList',
      callback: data => {
        setLoading(false)
        setData(data)
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  return (
    <div>
      <div className='d-flex mb-3' style={{ justifyContent: 'end', alignItems: 'center' }}>
        <Input size="middle"
          placeholder="规则名称/描述搜索"
          value={keyword}
          bordered={true} allowClear
          onChange={(e) => {
            setKeyword(e.target.value)
          }} 
          style={{ width: 270 }}
        />
      </div>
      <Table
        extraColWidth={32}
        loading={loading}
        columns={cols??[]}
        dataSource={_data}
        pagination={false}
        rowSelection={{
          selectedRowKeys: (selectedRows??[]).map(item => item.id),
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRows(selectedRows)
          },
        }}
      />
      <Update 
        {...updateParams}
        onCancel={(refresh) => {
          setUpdateParams({
            visible: false,
            type: undefined,
            item: undefined
          })

          refresh && getTemplates()
        }}
      />
    </div>
  )
})