/*
 * <<
 * Davinci
 * ==
 * Copyright (C) 2016 - 2017 EDP
 * ==
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * >>
 */

import React, { useEffect, useState } from 'react'
import {
  Modal,
  Button,
  Col,
  Table,
  Row,
  Divider,
  Popconfirm,
  message
} from 'antd'
import { IDictData } from '../types'
import { ColumnProps } from 'antd/lib/table'
import ButtonGroup from 'antd/es/button/button-group'
import api from 'utils/api'
import request from 'utils/request'
import DictDataFormModal from 'containers/DataManagerDictionary/components/DictDataFormModal'

interface IDictDatasModalProps {
  visible: boolean
  dictType: string
  onCancel: () => void
}

const DictDatasModal = (props: IDictDatasModalProps) => {
  const { visible, onCancel, dictType } = props

  const [tableLoading, setTableLoading] = useState(false)
  const [dictDatas, setDictDatas] = useState<IDictData[]>([])

  const [ddFormVisible, setDdFormVisible] = useState(false)
  const [ddFormLoading, setDdFormLoading] = useState(false)
  const [ddFormView, setDdFormView] = useState<IDictData>({})

  const tableColumns: Array<ColumnProps<IDictData>> = [
    {
      title: '字典编码',
      dataIndex: 'dictCode'
    },
    {
      title: '字典标签',
      dataIndex: 'dictLabel'
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue'
    },
    {
      title: '字典排序',
      dataIndex: 'dictSort'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text) => (
        <>
          {text === 0 && (
            <span
              style={{ padding: '2px 4px', background: 'green', color: '#fff' }}
            >
              正常
            </span>
          )}
          {(text === 1 || text === '') && (
            <span
              style={{ padding: '2px 4px', background: 'red', color: '#fff' }}
            >
              停用
            </span>
          )}
        </>
      )
    },
    {
      title: '备注',
      dataIndex: 'remark'
    },
    {
      title: '创建时间'
      // dataIndex: 'isDefault'
    },
    {
      title: '操作',
      render: (_, data) => {
        return (
          <>
            <a
              onClick={() => {
                setDdFormVisible(true)
                setDdFormView(data)
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除？"
              placement="bottom"
              onConfirm={() => handleDeleteDictData(data)}
            >
              <a>删除</a>
            </Popconfirm>
          </>
        )
      }
    }
  ]

  const queryDictDatas = async () => {
    if (!dictType) {
      return
    }
    try {
      setTableLoading(true)
      const data = await request(api.dictDatas + `?dictType=${dictType}`, {
        method: 'GET'
      })
      // @ts-ignore
      setDictDatas(data?.payload ?? [])
    } finally {
      setTableLoading(false)
    }
  }

  const handleDeleteDictData = async (data: IDictData) => {
    try {
      setTableLoading(true)
      const result = await request(`${api.deleteDictData}${data.dictCode}`, {
        method: 'delete'
      })
      // @ts-ignore
      if (result.header.code === 200) {
        message.success({ content: '删除成功' })
        queryDictDatas()
      } else {
        // @ts-ignore
        // tslint:disable-next-line:no-unused-expression
        result.header.msg && message.success({ content: result.header.msg })
      }
    } finally {
      setTableLoading(false)
    }
  }

  const handleSaveDDForm = async (form: IDictData) => {
    try {
      setDdFormLoading(true)
      const url = ddFormView?.dictCode
        ? api.updateDictData + ddFormView.dictCode
        : api.createDictData

      const result = await request(url, {
        method: ddFormView?.dictCode ? 'PUT' : 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        data: { ...ddFormView, dictType, ...form, status: form.status ? 0 : 1 }
      })
      // @ts-ignore
      if (result.header.code === 200) {
        message.success({
          content: (ddFormView?.dictCode ? '修改' : '新增') + '成功'
        })
        setDdFormVisible(false)
        queryDictDatas()
      } else {
        // @ts-ignore
        // tslint:disable-next-line:no-unused-expression
        result.header.msg && message.success({ content: result.header.msg })
      }
    } finally {
      setDdFormLoading(false)
    }
  }

  useEffect(() => {
    queryDictDatas()
  }, [dictType])

  return (
    <>
      <Modal
        title="数据字典数据"
        // wrapClassName='ant-modal-small'
        visible={visible}
        footer={null}
        onCancel={onCancel}
        destroyOnClose
        width={'80%'}
      >
        <div style={{ padding: '10px 0' }}>
          <Button
            onClick={() => {
              setDdFormVisible(true)
              setDdFormView({})
            }}
          >
            新增
          </Button>
        </div>
        <Row>
          <Col span={24}>
            <Table
              bordered
              rowKey="dictCode"
              loading={tableLoading}
              dataSource={dictDatas}
              columns={tableColumns}
              pagination={false}
              // onChange={this.tableChange}
            />
          </Col>
        </Row>
      </Modal>
      <DictDataFormModal
        visible={ddFormVisible}
        fromView={ddFormView}
        onSave={handleSaveDDForm}
        onCancel={() => setDdFormVisible(false)}
        loading={ddFormLoading}
      />
    </>
  )
}

export default DictDatasModal
