import React from "react"
import { Typography, Tooltip, Divider, Space, Input, Select, Modal, Row, Col } from "antd"

import { dispatch } from '../../../../model'
import Table from '../../../../util/Component/Table'
import AddRule from './add-rule'
import UpdateRule from './update-rule'
import UpdateRuleTemplate from './update-rule-template'
import PermissionButton from '../../../../util/Component/PermissionButton'
import { showMessage } from "../../../../util"
import { render } from "@testing-library/react"

const nodeItems = [
  { key: 'name', title: '名称' },
  { key: 'statusName', title: '状态' },
  { key: 'ownerName', title: '维护人' },
  { key: 'maintenanceContent', title: '维护说明' },
  { key: 'remark', title: '描述' },
  { key: 'modifiedTs', title: '维护时间', render: (text) => text?new Date(text).toLocaleString():''},
  { key: 'modifiedTs', title: '版本', render: (text) => text?`V_${new Date(text).toLocaleString()}`:''},
]        

const FC = (props) => {
  const { node, readonly } = props
  const [args, setArgs] = React.useState(() => ({
    statusId: undefined,
    alertTypeId: undefined,
    keyword: undefined,
  }))
  const [loading, setLoading] = React.useState(false)
  const [data, setData] = React.useState()
  const [selectedRows, setSelectedRows] = React.useState()
  const [loadingStatus, setLoadingStatus] = React.useState(false)
  const [status, setStatus] = React.useState()
  const [loadingAlertTypes, setLoadingAlertTypes] = React.useState(false)
  const [alertTypes, setAlertTypes] = React.useState()
  const [addRuleParams, setAddRuleParams] = React.useState({
    visible: false,
    node: undefined,
  })
  const [updateRuleParams, setUpdateRuleParams] = React.useState({
    visible: false,
    item: undefined,
  })
  const [updateRuleTemplateParams, setUpdateRuleTemplateParams] = React.useState({
    visible: false,
    type: undefined,
    item: undefined
  })
 
  const [modal, contextHolder] = Modal.useModal()

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

  React.useEffect(() => {
    if (node?.id) {
      getRules()
    }
  }, [node])

  const cols = React.useMemo(() => {
    return ([
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (_, __, index) => `${index+1}`
      },
      {
        title: '规则名称',
        dataIndex: 'ruleTemplateName',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '规则描述',
        dataIndex: 'ruleTemplateRemark',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '规则状态',
        dataIndex: 'statusName',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '规则类型',
        dataIndex: 'alertTypeName',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '规则提示',
        dataIndex: 'alertContent',
        render: (text, record) => (
          <Tooltip title={text}>
            <Typography.Text ellipsis={true}>
              { text }
            </Typography.Text>
          </Tooltip>
        )
      },
      {
        title: '操作',
        key: 'action',
        width: readonly ? 80 : 200,
        render: (text, record) => {
          return (  
            <div style={{ display: 'flex', alignItems: 'center'  }}>
              <PermissionButton 
                type='link'
                size='small'
                onClick={() => {
                  setUpdateRuleTemplateParams({
                    visible: true,
                    type: 'detail',
                    item: {
                      id: record?.ruleTemplateId
                    },
                  })
                }}
                style={{ padding: 0 }}
                defaultPermission={true}
              >
              规则详情
              </PermissionButton>
              {
                !readonly && <React.Fragment>
                  <div style={{ margin: '0 5px' }}>
                    <Divider type='vertical' />
                  </div>
                  <PermissionButton 
                    type='link'
                    size='small'
                    onClick={() => {
                      setUpdateRuleParams({
                        visible: true,
                        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>
                </React.Fragment>
              }
            </div>
          )
        }
      }
    ])
  }, [node])

  const tableData = React.useMemo(() => {
    return data?.filter(item => 
      (
        !args.keyword 
        || (item.ruleTemplateName??'').indexOf(args.keyword) !== -1 
        || (item.ruleTemplateRemark??'').indexOf(args.keyword) !== -1
      ) 
      && (
        !args.statusId 
        || (item.statusId??'').indexOf(args.statusId) !== -1
      ) && (
        !args.alertTypeId 
        || (item.alertTypeId??'').indexOf(args.alertTypeId) !== -1
      )
    )
  }, [data, args])

  const getRules = () => {
    setLoading(true)
    dispatch({
      type: 'datamodel.getRuleList',
      payload: {
        catalogId: node?.id,
      },
      callback: data => {
        setLoading(false)
        setData(data)
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const getStatus = () => {
    setLoadingStatus(true)
    dispatch({
      type: 'datamodel.getRuleStatus',
      callback: data => {
        setLoadingStatus(false)
        setStatus(data)
      },
      error: () => {
        setLoadingStatus(false)
      }
    })
  }

  const getAlertTypes = () => {
    setLoadingAlertTypes(true)
    dispatch({
      type: 'datamodel.getRuleAlertTypes',
      callback: data => {
        setLoadingAlertTypes(false)
        setAlertTypes(data)
      },
      error: () => {
        setLoadingAlertTypes(false)
      }
    })
  }

  const onAddClick = () => {
    if (!node) {
      showMessage('warn', '请先选择目录')
      return 
    }

    setAddRuleParams({
      visible: true,
      node
    })
  }

  const onExportClick = () => {
    if (!node) {
      showMessage('warn', '请先选择目录')
      return 
    }

    modal.confirm({
      title: '提示',
      content: '确定导出该规范吗?',
      onOk: () => {
        window.open(`/api/datamodeler/easyDataModelerRule/exportRules?catalogId=${node?.id}`)
      }
    })
  }

  const onBatchDeteteClick = () => {
    modal.confirm({
      title: '提示',
      content: '确定将选中的规则从规范中移除吗?',
      onOk: () => {
        dispatch({
          type: 'datamodel.deleteRules',
          payload: {
            ids: (selectedRows??[]).map(item => item.id).toString()
          },
          callback: data => {
            showMessage('success', '删除成功')
            setSelectedRows()
            getRules()
          }
        })
      }
    })
  }

  const onDeteteClick = (record) => {
    modal.confirm({
      title: '提示',
      content: '确定将选中的规则从规范中移除吗?',
      onOk: () => {
        dispatch({
          type: 'datamodel.deleteRules',
          payload: {
            ids: record?.id
          },
          callback: data => {
            showMessage('success', '删除成功')
            setSelectedRows()
            getRules()
          }
        })
      }
    })
  }

  return (
    <div className='pl-4'>
      <div className='py-3' style={{ borderBottom: '1px solid #EFEFEF' }}>
        <Row gutter={[8, 8]}>
          {
            (nodeItems??[]).map(item => {
              let val = node?.[item.key]
              if (item.render) {
                val = item.render(val)
              }

              return (
                <Col key={item.title} span={6}>
                  <Tooltip title={val}>
                    <Typography.Text ellipsis={true}>{`${item.title}: ${val??''}`}</Typography.Text>
                  </Tooltip>
                </Col>
              )
            })
          }
        </Row>
      </div>
      <div className='d-flex py-3' style={{ justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #EFEFEF' }}>
        <Space>
          {
            !readonly && <PermissionButton 
              onClick={onAddClick} 
              // permissionKey='新增'
              defaultPermission={true}
            >
            新建
            </PermissionButton>
          }
          {
            !readonly && <PermissionButton 
              onClick={onBatchDeteteClick} 
              // permissionKey='删除'
              defaultPermission={true}
              disabled={(selectedRows??[]).length===0}
              tip={(selectedRows??[]).length===0?'请先选择规则':''} 
            >
            删除
            </PermissionButton>
          }
          <PermissionButton 
            onClick={onExportClick} 
            defaultPermission={true}
          >
          导出
          </PermissionButton>
        </Space>
        <Space>
          <Select value={args.statusId} allowClear
            loading={loadingStatus}
            placeholder='请选择规则状态'
            onChange={(val) => {
              setArgs({ ...args, statusId: val })
            }}
            style={{ width: 150 }}
          >
            { (status??[]).map(item => (
              <Select.Option key={item.id} key={item.id}>{item.name}</Select.Option>
            )) }
          </Select>
          <Select value={args.alertTypeId} allowClear
            loading={loadingAlertTypes}
            placeholder='请选择规则类型'
            onChange={(val) => {
              setArgs({ ...args, alertTypeId: val })
            }}
            style={{ width: 150 }}
          >
            { (alertTypes??[]).map(item => (
              <Select.Option key={item.id} key={item.id}>{item.name}</Select.Option>
            )) }
          </Select>
          <Input size="middle"
            placeholder="规则名称/描述搜索"
            value={args.keyword}
            bordered={true} allowClear
            onChange={(e) => {
              setArgs({ ...args, keyword: e.target.value })
            }} 
            style={{ width: 270 }}
          />
        </Space>
      </div>
      <div className='pt-3'>
        <Table
          extraColWidth={32}
          loading={loading}
          columns={cols??[]}
          dataSource={tableData??[]}
          pagination={false}
          rowSelection={{
            selectedRowKeys: (selectedRows??[]).map(item => item.id),
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRows(selectedRows)
            },
          }}
        />
      </div>
      <AddRule
        {...addRuleParams}
        onCancel={(refresh) => {
          setAddRuleParams({
            visible: false,
            node: undefined,
          })

          refresh && getRules()
        }}
      />
      <UpdateRule
        {...updateRuleParams}
        onCancel={(refresh) => {
          setUpdateRuleParams({
            visible: false,
            item: undefined,
          })

          refresh && getRules()
        }}
      />
      <UpdateRuleTemplate
        {...updateRuleTemplateParams}
        onCancel={(refresh) => {
          setUpdateRuleTemplateParams({
            visible: false,
            type: undefined,
            item: undefined,
          })

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

export default FC