import React, { useState, useEffect } from 'react';
import {
  Table,
  Tooltip,
  Spin,
  Modal,
  Form,
  Input,
  Space,
  Button,
  Popconfirm,
  notification,
  message,
  Row,
  Col,
} from 'antd';
import { EditTwoTone, DeleteOutlined } from '@ant-design/icons';
import { get, CITY_SERVICE } from '@/services';
import styles from './WebDic.less';

const WebDic = () => {
  const [loading, setLoading] = useState(false);
  const [level, setLevel] = useState(0); // 设置级别,一级1,二级2,添加条目时使用
  const [addVisible, setAddVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [data, setData] = useState([]); // 一级条目数据
  const [subData, setSubData] = useState([]); // 二级条目数据
  const [select, setSelect] = useState({}); // 当前选中条目,可以是一级/二级,修改/删除时设置
  const [selectColor, setSelectColor] = useState({}); // 当前选中一级条目颜色,修改/删除时设置
  const [selectID, setSelectID] = useState('-1'); // 当前选中一级条目的ID,添加二级条目时使用
  const [first, setFirst] = useState(true); // 是否第一次加载
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const columns = [
    {
      title: '名称',
      dataIndex: 'nodeName',
      key: 'nodeName',
      width: 220,
    },
    {
      title: '值',
      dataIndex: 'nodeValue',
      key: 'nodeValue',
      render: record => {
        if (!record) {
          return '-';
        }
        return record;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: record => (
        <Space>
          <Tooltip title="编辑">
            <EditTwoTone
              onClick={() => {
                setSelect(record);
                if (record.parentID === '-1') {
                  setSelectColor(record);
                }
                setEditVisible(true);
                editForm.setFieldsValue({
                  nodeName1: record.nodeName,
                  nodeValue: record.nodeValue,
                });
              }}
              style={{ fontSize: '16px' }}
            />
          </Tooltip>
          <div onClick={e => e.stopPropagation()}>
            <Popconfirm
              title="是否删除该数据?"
              okText="确认"
              cancelText="取消"
              onConfirm={submitDelete}
            >
              <DeleteOutlined
                onClick={() => {
                  setSelect(record);
                  if (record.parentID === '-1') {
                    setSelectColor(record);
                  }
                }}
                style={{
                  fontSize: '16px',
                  margin: '0px 10px',
                  color: '#e86060',
                }}
              />
            </Popconfirm>
          </div>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    getData('-1');
  }, []);
  // 根据父节点nodeID(即parentID)获取数据,一级条目parentID = -1
  const getData = value => {
    setLoading(true);
    get(`${CITY_SERVICE}/OMS.svc/D_GetDataDictionaryList`, {
      _version: 9999,
      _dc: new Date().getTime(),
      nodeID: value,
      key: '',
    })
      .then(res => {
        if (res) {
          if (res.length > 0) {
            res.map(item => {
              item.key = item.nodeID;
              return item;
            });
          }
          // value为 -1 时获取一级条目数据,否则获取二级条目数据
          if (value === '-1') {
            setData(res); // 设置一级条目数据
            if (first) {
              setSelect(res[0]); // 默认当前选中一级条目第一条
              setSelectColor(res[0]);
              setSelectID(res[0].nodeID); // 设置选中的一级条目ID,用于添加二级条目
              setFirst(false);
              // 获取二级条目数据,默认一级条目第一条,递归一次(条件parentID === '-1')
              if (res[0] && res[0].parentID === '-1') {
                getData(res[0].nodeID);
              }
            }
          } else if (value) {
            setSubData(res); // 设置二级条目,res为空[]时也要设置
          }
        } else {
          notification.error({
            message: '获取失败',
            description: res.message,
          });
        }
        setLoading(false);
      })
      .catch(err => {
        setLoading(false);
        message.error(err);
      });
  };
  const setRowClassName = record =>
    record.nodeID === selectColor.nodeID ? styles.clickRowStyle : '';

  // 提交-添加
  const submitAdd = value => {
    const nodeName1 = addForm.getFieldValue('nodeName1');
    const nodeValue = addForm.getFieldValue('nodeValue');
    if (nodeName1) {
      get(`${CITY_SERVICE}/OMS.svc/D_AddDataDictionary`, {
        _version: 9999,
        _dc: new Date().getTime(),
        nodeID: value,
        nodeName: nodeName1,
        nodeValue,
      })
        .then(res => {
          if (res.success) {
            setAddVisible(false);
            if (level === 1) {
              getData('-1');
              getData(res.message); // res.message为添加成功返回的一级条目ID
              // 设置添加二级条目的父级ID及父级ID选中状态
              setSelect({ nodeID: res.message, parentID: '-1' });
              setSelectID(res.message);
              setSelectColor({ nodeID: res.message });
            } else {
              getData(value);
            }
            notification.success({
              message: '提交成功',
            });
          } else {
            notification.error({
              message: '提交失败',
              description: res.message,
            });
          }
        })
        .catch(err => {
          message.error(err);
        });
    } else {
      notification.error({
        message: '提交失败',
        description: '名称不能为空',
      });
    }
  };
  // 提交-修改
  const submitEdit = () => {
    const nodeName1 = editForm.getFieldValue('nodeName1');
    const nodeValue = editForm.getFieldValue('nodeValue');
    if (nodeName1) {
      get(`${CITY_SERVICE}/OMS.svc/D_EditDataDictionary`, {
        _version: 9999,
        _dc: new Date().getTime(),
        nodeID: select.nodeID,
        nodeName: nodeName1,
        nodeValue,
      })
        .then(res => {
          if (res.success) {
            setEditVisible(false);
            getData(select.parentID);
            notification.success({
              message: '提交成功',
            });
          } else {
            notification.error({
              message: '提交失败',
              description: res.message,
            });
          }
        })
        .catch(err => {
          message.error(err);
        });
    } else {
      notification.error({
        message: '提交失败',
        description: '名称不能为空',
      });
    }
  };
  // 提交-删除
  const submitDelete = () => {
    get(`${CITY_SERVICE}/OMS.svc/D_DeleteDataDictionary`, {
      _version: 9999,
      _dc: new Date().getTime(),
      nodeID: select.nodeID,
    })
      .then(res => {
        if (res.success) {
          getData(select.parentID);
          if (select.parentID === '-1') {
            setSubData([]);
          }
          notification.success({
            message: '删除成功',
          });
        } else {
          notification.error({
            message: '删除失败',
            description: res.message,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };
  const setItem = value => {
    setLevel(value);
    setAddVisible(true);
    addForm.resetFields();
    // addForm.setFieldsValue({ nodeName1: '', nodeValue: '' });
  };
  const pagenation = {
    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
    pageSizeOptions: [10, 20, 50, 100],
    defaultPageSize: '20',
    showQuickJumper: true,
    showSizeChanger: true,
  };

  return (
    <div className={styles.WebDic}>
      <Spin spinning={loading} tip="loading...">
        <Row style={{ background: 'white' }}>
          <Col span={12} className={styles.left}>
            <div style={{ marginBottom: '10px', fontSize: '16px' }}>
              <span style={{ padding: '0 10px' }}>一级条目</span>
              <Button type="primary" size="small" onClick={() => setItem(1)}>
                添加
              </Button>
            </div>
            {/* 一级条目 表格 */}
            <Table
              size="small"
              bordered
              columns={columns}
              dataSource={data}
              scroll={{ x: 'max-content' }}
              rowClassName={setRowClassName}
              onRow={record => ({
                onClick: () => {
                  getData(record.nodeID);
                  setSelect(record);
                  setSelectColor(record);
                  setSelectID(record.nodeID);
                },
              })}
              pagination={pagenation}
            />
          </Col>
          <Col span={12}>
            <div style={{ marginBottom: '10px', fontSize: '16px' }}>
              <span style={{ padding: '0 10px' }}>二级条目</span>
              <Button type="primary" size="small" onClick={() => setItem(2)}>
                添加
              </Button>
            </div>
            {/* 二级条目 表格 */}
            <Table
              size="small"
              bordered
              columns={columns}
              dataSource={subData}
              scroll={{ x: 'max-content' }}
              pagination={pagenation}
            />
          </Col>
        </Row>
      </Spin>

      {/* 添加 */}
      <Modal
        title={level === 1 ? '添加一级条目' : '添加二级条目'}
        visible={addVisible}
        onOk={() => {
          if (level === 1) {
            submitAdd('-1');
          } else {
            submitAdd(selectID);
          }
        }}
        onCancel={() => {
          setAddVisible(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={addForm} labelCol={{ span: 3 }}>
          <Form.Item
            name="nodeName1"
            label="名称"
            rules={[{ required: true, message: '不能为空' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="nodeValue" label="值">
            <Input placeholder="请输入值" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 修改 */}
      <Modal
        title={select.parentID === '-1' ? '修改一级条目' : '修改二级条目'}
        visible={editVisible}
        onOk={submitEdit}
        onCancel={() => {
          setEditVisible(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={editForm} labelCol={{ span: 3 }}>
          <Form.Item
            name="nodeName1"
            label="名称"
            rules={[{ required: true, message: '不能为空' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="nodeValue" label="值">
            <Input placeholder="请输入值" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default WebDic;