import React from 'react'
import { Input, Space, Modal, Divider, Tooltip, Typography } from 'antd'

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

const FC = (props) => {
  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
  })

  const [modal, contextHolder] = Modal.useModal()

  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>
        )
      },
      {
        title: '引用次数',
        dataIndex: 'referenceCount',
      },
      {
        title: '操作',
        key: 'action',
        width: 120,
        render: (text, record) => {
          return (  
            <div style={{ display: 'flex', alignItems: 'center'  }}>
              <PermissionButton 
                type='link'
                size='small'
                onClick={() => {
                  setUpdateParams({
                    visible: true,
                    type: 'edit',
                    item: record,
                  })
                }}
                style={{ padding: 0 }}
                // permissionKey='编辑'
                // permissions={permissions}
                defaultPermission={true}
              >
              编辑
              </PermissionButton>
              <div style={{ margin: '0 5px' }}>
                <Divider type='vertical' />
              </div>
              <PermissionButton
                type='link'
                size='small'
                onClick={() => { onDeteteClick(record); }}
                style={{ padding: 0 }}
                // permissionKey='删除'
                // permissions={permissions}
                defaultPermission={true}
              >
              删除
              </PermissionButton>
            </div>
          )
        }
      }
    ])
  }, [])

  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)
      }
    })
  }

  const onAddClick = () => {
    setUpdateParams({
      visible: true,
      type: 'add',
      item: undefined
    })
  }

  const onBatchDeteteClick = () => {
    modal.confirm({
      title: '提示',
      content: '删除规则，引用的规范将同步删除该规则，确定删除吗?',
      onOk: () => {
        dispatch({
          type: 'datamodel.deletesRuleTemplate',
          payload: {
            templateIds: (selectedRows??[]).map(item => item.id).toString()
          },
          callback: data => {
            showMessage('success', '删除成功')
            setSelectedRows()
            getTemplates()
          }
        })
      }
    })
  }

  const onDeteteClick = (record) => {
    modal.confirm({
      title: '提示',
      content: '删除规则，引用的规范将同步删除该规则，确定删除吗?',
      onOk: () => {
        dispatch({
          type: 'datamodel.deleteRuleTemplate',
          payload: {
            templateId: record?.id
          },
          callback: data => {
            showMessage('success', '删除成功')
            getTemplates()
          }
        })
      }
    })
  }

  return (
    <div>
      <div className='d-flex mb-3' style={{ justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <PermissionButton 
            onClick={onAddClick} 
            // permissionKey='新增'
            defaultPermission={true}
          >
          新建
          </PermissionButton>
          <PermissionButton 
            onClick={onBatchDeteteClick} 
            // permissionKey='删除'
            defaultPermission={true}
            disabled={(selectedRows??[]).length===0}
            tip={(selectedRows??[]).length===0?'请先选择规则':''} 
          >
          删除
          </PermissionButton>
        </Space>
        <Input size="middle"
          placeholder="规则名称/描述搜索"
          value={keyword}
          bordered={true} allowClear
          onChange={(e) => {
            const keyword = e.target.value
            setKeyword(keyword)
          }} 
          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()
        }}
      />
      {contextHolder}
    </div>
  )
}

export default FC