import React, { useEffect, useState } from 'react'
import Helmet from 'react-helmet'
import Container, { ContainerBody } from 'components/Container'
import Box from 'components/Box'
import {
  Button,
  Col,
  Divider,
  Icon,
  message,
  Popconfirm,
  Row,
  Table,
  Tooltip
} from 'antd'
import { ColumnProps } from 'antd/lib/table'
import { compose } from 'redux'
import request from 'utils/request'
import api from 'utils/api'
import DictDatasModal from 'containers/DataManagerDictionary/components/DictDatasModal'
import { IDictType } from 'containers/DataManagerDictionary/types'
import DictTypeFormModal from 'containers/DataManagerDictionary/components/DictTypeFormModal'

function DataDictionary() {
  const [tableLoading, setTableLoading] = useState(false)
  const [dictTypes, setDictTypes] = useState<IDictType[]>([])

  const [visible, setVisible] = useState(false)
  const [dictType, setDictType] = useState<string>(null)

  const [dictTypeFormVisible, setDictTypeFormVisible] = useState(false)
  const [dictTypeFormLoading, setDictTypeFormLoading] = useState(false)
  const [dictTypeForm, setDictTypeForm] = useState<IDictType>(null)

  const tableColumns: Array<ColumnProps<IDictType>> = [
    {
      title: '字典主键',
      dataIndex: 'dictId'
    },
    {
      title: '字典名称',
      dataIndex: 'dictName'
    },
    {
      title: '字典类型',
      dataIndex: 'dictType'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text) => (
        <>
          {text === 0 && (
            <span
              style={{ padding: '2px 4px', background: 'green', color: '#fff' }}
            >
              正常
            </span>
          )}
          {text === 1 && (
            <span
              style={{ padding: '2px 4px', background: 'red', color: '#fff' }}
            >
              停用
            </span>
          )}
        </>
      )
    },
    {
      title: '备注',
      dataIndex: 'remark'
    },
    {
      title: '创建时间'
      // dataIndex: 'isDefault'
    },
    {
      title: '操作',
      render: (_, data) => (
        <>
          <a
            onClick={() => {
              setDictTypeFormVisible(true)
              setDictTypeForm(data)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setDictType(data.dictType)
              setVisible(true)
            }}
          >
            列表
          </a>

          <Divider type="vertical" />
          <Popconfirm
            title="确定删除？"
            placement="bottom"
            onConfirm={() => handleDeleteDictType(data.dictId)}
          >
            <a>删除</a>
          </Popconfirm>
        </>
      )
    }
  ]

  const queryDictTypes = async () => {
    try {
      setTableLoading(true)
      const data = await request(api.dictTypes, { method: 'GET' })
      // @ts-ignore
      setDictTypes(data?.payload ?? [])
    } finally {
      setTableLoading(false)
    }
  }
  const handleDeleteDictType = async (dictId) => {
    try {
      setTableLoading(true)
      await request(`${api.deleteDictType}/${dictId}`, { method: 'delete' })
      queryDictTypes()
    } finally {
      setTableLoading(false)
    }
  }
  const handleSaveDictType = async (dt: IDictType) => {
    // // 0=正常,1=停用
    try {
      setDictTypeFormLoading(true)
      const url = dictTypeForm?.dictId
        ? `${api.updateDictType}/${dictTypeForm.dictId}`
        : api.createDictType
      const result = await request(url, {
        method: dictTypeForm?.dictId ? 'PUT' : 'POST',
        data: { ...(dictTypeForm ?? {}), ...dt, status: dt.status ? 0 : 1 }
      })
      // @ts-ignore
      if (result.header.code === 200) {
        setDictTypeFormVisible(false)
        queryDictTypes()
      } else {
        // @ts-ignore
        // tslint:disable-next-line:no-unused-expression
        result.header.msg && message.error({ content: result.header.msg })
      }
    } finally {
      setDictTypeFormLoading(false)
    }
  }

  useEffect(() => {
    queryDictTypes()
  }, [])
  return (
    <Container>
      <Helmet title="数据字典" />

      <ContainerBody>
        <Box>
          <Box.Header>
            <Box.Title>
              <Icon type="bars" />
              数据字典列表
            </Box.Title>
            <Box.Tools>
              <Tooltip placement="bottom" title="新增">
                <Button
                  type="primary"
                  icon="plus"
                  onClick={() => {
                    setDictTypeFormVisible(true)
                    setDictTypeForm(null)
                  }}
                />
              </Tooltip>
            </Box.Tools>
          </Box.Header>
          <Box.Body>
            <Row>
              <Col span={24}>
                <Table
                  bordered
                  rowKey="dictId"
                  loading={tableLoading}
                  dataSource={dictTypes}
                  columns={tableColumns}
                  pagination={false}
                  // onChange={this.tableChange}
                />
                <div style={{ height: 20 }} />
              </Col>
            </Row>
          </Box.Body>
        </Box>
      </ContainerBody>
      <DictDatasModal
        visible={visible}
        dictType={dictType}
        onCancel={() => setVisible(false)}
      />
      <DictTypeFormModal
        visible={dictTypeFormVisible}
        loading={dictTypeFormLoading}
        fromView={dictTypeForm}
        onSave={handleSaveDictType}
        onCancel={() => setDictTypeFormVisible(false)}
      />
    </Container>
  )
}

// const mapDispatchToProps = (dispatch: Dispatch<ViewActionType>) => ({
//   onLoadViews: (projectId) => dispatch(ViewActions.loadViews(projectId)),
//   onDeleteView: (viewId, resolve) => dispatch(ViewActions.deleteView(viewId, resolve)),
//   onCopyView: (view, resolve) => dispatch(ViewActions.copyView(view, resolve)),
//   onCheckName: (data, resolve, reject) => dispatch(checkNameUniqueAction('view', data, resolve, reject))
// })
//
// const mapStateToProps = createStructuredSelector({
//   views: makeSelectViews(),
//   currentProject: makeSelectCurrentProject(),
//   loading: makeSelectLoading()
// })
// const withConnect = connect<IViewListStateProps, IViewListDispatchProps, RouteComponentWithParams>(mapStateToProps, mapDispatchToProps)
// const withReducer = injectReducer({ key: 'view', reducer })
// const withSaga = injectSaga({ key: 'view', saga: sagas })

export default compose()(DataDictionary)
// withReducer,
// withSaga,
// withConnect
