/* eslint-disable react-hooks/rules-of-hooks */
/*
 * @Description:
 * @Author: leizhe
 * @Date: 2021-05-27 16:31:05
 * @LastEditTime: 2021-11-26 16:43:17
 * @LastEditors: leizhe
 */
import React, { useState, useEffect } from 'react';
import {
  Table,
  Tooltip,
  Spin,
  Modal,
  Form,
  Input,
  Space,
  Popconfirm,
  notification,
  message,
  Button,
  Upload,
  Search,
} from 'antd';
import PageContainer from '@/components/BasePageContainer';
import {
  EditTwoTone,
  RollbackOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import {
  SearchDataDictionaryList,
  EditDataDictionary,
  DeleteDataDictionary,
} from '@/services/dataCenter/api';
import { useHistory } from 'react-router-dom';
import styles from './index.less';

const dictionary = () => {
  const [searchData, setSearchData] = useState([]); // 搜索框表格数据
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [treeLoading, setTreeLoading] = useState(false);
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const [editVisible, setEditVisible] = useState(false); // 编辑二级条目
  const [editVisible1, setEditVisible1] = useState(false); // 编辑一级条目
  const [select, setSelect] = useState({}); // 当前选中条目,可以是一级/二级，修改/删除时设置
  const history = useHistory();
  const [editForm] = Form.useForm();
  const [title, setTitle] = useState('');
  // eslint-disable-next-line no-shadow
  const { Search } = Input;

  const columns2 = [
    {
      title: () => <span className={styles.font}>名称</span>,
      dataIndex: 'nodeName',
      key: 'nodeName',
      width: '45%',
    },
    {
      title: () => <span className={styles.font}>值</span>,
      dataIndex: 'nodeValue',

      key: 'nodeValue',
      render: record => {
        if (!record) {
          return '-';
        }
        return record;
      },
    },
    {
      title: () => <span className={styles.font}>操作</span>,
      key: 'action',
      width: 100,
      align: 'center',
      render: record => (
        <Space>
          <Tooltip title="编辑">
            <EditTwoTone
              onClick={() => {
                setSelect(record);
                if (record.parentID === '-1' || record.parentID === null) {
                  setEditVisible1(true);
                } else {
                  setEditVisible(true);
                }
                editForm.setFieldsValue({
                  nodeName: record.nodeName,
                  nodeValue: record.nodeValue,
                });
              }}
              style={{ fontSize: '16px' }}
            />
          </Tooltip>
          <div onClick={e => e.stopPropagation()}>
            <Tooltip title="删除">
              <Popconfirm
                title={title}
                okText="确认"
                cancelText="取消"
                onConfirm={submitDelete}
                placement="left"
              >
                <DeleteOutlined
                  onClick={() => {
                    setSelect(record);
                    if (record.parentID === '-1' || record.parentID === null) {
                      setTitle(
                        '确认删除一级目录数据,删除一级目录数据会将其二级目录子数据一起删除',
                      );
                    } else {
                      setTitle('确认删除二级条目数据');
                    }
                  }}
                  style={{
                    fontSize: '16px',
                    margin: '0px 10px',
                    color: '#e86060',
                  }}
                />
              </Popconfirm>
            </Tooltip>
          </div>
        </Space>
      ),
    },
  ];

  // 修改
  const submitEdit = () => {
    const nodeName = editForm.getFieldValue('nodeName');
    const nodeValue = editForm.getFieldValue('nodeValue');
    if (nodeName) {
      EditDataDictionary({
        nodeID: select.nodeID,
        nodeName,
        nodeValue,
      }).then(res => {
        if (res.code === 0) {
          setEditVisible(false);
          sumbitSearch();
          // getData(select.parentID === '-1' ? null : select.parentID);
          notification.success({
            message: '提交成功',
          });
          // if (flag1 === 1) {
          //   sumbitSearch()
          // }
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      });
    } else {
      notification.error({
        message: '提交失败',
        description: '名称不能为空',
      });
    }
  };
  const submitEdit1 = () => {
    const nodeName = editForm.getFieldValue('nodeName');
    if (nodeName) {
      EditDataDictionary({
        nodeID: select.nodeID,
        nodeName,
        nodeValue: '-',
      }).then(res => {
        if (res.code === 0) {
          setEditVisible1(false);
          sumbitSearch();
          // getData(select.parentID === '-1' ? null : select.parentID);

          notification.success({
            message: '提交成功',
          });
          // if (flag1 === 1) {
          //   sumbitSearch()
          // }
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      });
    } else {
      notification.error({
        message: '提交失败',
        description: '名称不能为空',
      });
    }
  };

  const sumbitSearch = () => {
    SearchDataDictionaryList({ key: searchWord }).then(res => {
      if (res.code === 0) {
        setSearchData(res.data);
      }
      // else {
      //     notification.error({
      //         message: '提交失败',
      //         description: res.message,
      //     })
      // }
    });
  };

  const submitDelete = () => {
    console.log(select);
    DeleteDataDictionary({
      nodeID: select.nodeID,
    })
      .then(res => {
        if (res.code === 0) {
          // if (flag1 === 1) {
          //     sumbitSearch()
          // }
          sumbitSearch();
          notification.success({
            message: '删除成功',
          });
        } else {
          notification.error({
            message: '删除失败',
            description: res.message,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };
  // 获取搜索框的值
  const handleSearch = e => {
    setSearchWord(e.target.value);
  };

  const pagenation = {
    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
    pageSizeOptions: [10, 20, 50, 100],
    defaultPageSize: '20',
    showQuickJumper: true,
    showSizeChanger: true,
  };
  const back = () => {
    history.push({
      pathname: '/dataCenter/dictionary1',
    });
  };

  return (
    <PageContainer className={styles.dictionaryContainer}>
      <div className={styles.containerBox}>
        <div className={styles.config}>
          <div className={styles.title}>
            <Search
              style={{ width: 500, marginBottom: 25 }}
              placeholder="输入关键字"
              onSearch={sumbitSearch}
              onChange={e => handleSearch(e)}
              enterButton
              value={searchWord}
            />
          </div>
          <div className={styles.btn}>
            <Button
              type="primary"
              icon={<RollbackOutlined />}
              onClick={() => back()}
            >
              返回
            </Button>
          </div>
        </div>
        <Table
          size="small"
          bordered
          key=""
          columns={columns2}
          dataSource={searchData}
          scroll={{ y: 'calc(100vh - 280px)' }}
          pagination={pagenation}
          onRow={record => ({
            onClick: () => {
              setSelect(record);
            },
          })}
        />
      </div>
      {/* 修改一级条目 */}
      <Modal
        title="修改一级条目"
        visible={editVisible1}
        onOk={submitEdit1}
        onCancel={() => {
          setEditVisible1(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={editForm} labelCol={{ span: 3 }}>
          <Form.Item
            name="nodeName"
            label="名称"
            rules={[{ required: true, message: '不能为空' }]}
          >
            <Input placeholder="请输入名称" style={{ width: '90%' }} />
          </Form.Item>
        </Form>
      </Modal>
      {/* 修改二级条目 */}

      <Modal
        title="修改二级条目"
        visible={editVisible}
        onOk={submitEdit}
        onCancel={() => {
          setEditVisible(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={editForm} labelCol={{ span: 3 }}>
          <Form.Item
            name="nodeName"
            label="名称"
            rules={[{ required: true, message: '不能为空' }]}
          >
            <Input placeholder="请输入名称" style={{ width: '90%' }} />
          </Form.Item>
          <Form.Item name="nodeValue" label="值">
            <Input placeholder="请输入值" style={{ width: '90%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default dictionary;
