import React, { useState, useEffect } from 'react';
import {
  Table,
  Tooltip,
  Spin,
  Modal,
  Form,
  Input,
  Space,
  Button,
  Popconfirm,
  notification,
  message,
} from 'antd';
import { get, CITY_SERVICE, PUBLISH_SERVICE } from '@/services';
import { GetKeyValue, EditKeyValue, DeleteKeyValue, AddKeyValue } from '@/services/dataCenter/api';
import { EditTwoTone, DeleteOutlined, PlusSquareOutlined, SyncOutlined } from '@ant-design/icons';
import styles from './AppDic.less';

const AppDic = () => {
  const [loading, setLoading] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [data, setData] = useState([]); // 表数据
  const [select, setSelect] = useState({}); // 当前选中条目,修改/删除时设置
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();

  const columns = [
    {
      title: '名称',
      dataIndex: 'Label',
      key: 'Label',
    },
    {
      title: '键名',
      dataIndex: 'Key',
      key: 'Key',
    },
    {
      title: '值',
      dataIndex: 'Value',
      key: 'Value',
    },
    {
      title: '描述',
      dataIndex: 'Description',
      key: 'Description',
      render: record => {
        if (!record) {
          return '-';
        }
        return record;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      render: record => (
        <Space>
          <Tooltip title="编辑">
            <EditTwoTone
              onClick={() => {
                setSelect(record);
                setEditVisible(true);
                editForm.setFieldsValue({
                  label: record.Label,
                  key: record.Key,
                  value: record.Value,
                  description: record.Description,
                });
              }}
              style={{ fontSize: '16px' }}
            />
          </Tooltip>
          <Popconfirm
            title="是否删除该数据?"
            okText="确认"
            cancelText="取消"
            onConfirm={submitDelete}
          >
            <Tooltip title="删除">
              <DeleteOutlined
                onClick={() => {
                  setSelect(record);
                }}
                style={{
                  fontSize: '16px',
                  margin: '0px 10px',
                  color: '#e86060',
                }}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    getData('-1');
  }, []);
  const getData = () => {
    setLoading(true);
    // get(`${CITY_SERVICE}/OMS.svc/M_GetKeyValue`, {
    //   _version: 9999,
    //   _dc: new Date().getTime(),
    // })
    //   .then(res => {
    //     if (res) {
    //       if (res.length > 0) {
    //         res.map(item => {
    //           item.key = item.id;
    //           return item;
    //         });
    //       }
    //       setData(res);
    //     } else {
    //       notification.error({
    //         message: '获取失败',
    //         description: res.message,
    //       });
    //     }
    //     setLoading(false);
    //   })
    //   .catch(err => {
    //     setLoading(false);
    //     message.error(err);
    //   });
    GetKeyValue({}).then(resnew => {
      if (resnew.code === 0) {
        let res = resnew.data;
        if (res.length > 0) {
          res.map(item => {
            item.key = item.id;
            return item;
          });
        }
        setData(res);
      } else {
        notification.error({
          message: '获取失败',
          // eslint-disable-next-line no-undef
          description: res.msg,
        });
      }
      setLoading(false);
    });
  };
  // 提交-添加
  const submitAdd = () => {
    const label = addForm.getFieldValue('label');
    const key = addForm.getFieldValue('key');
    const value = addForm.getFieldValue('value');
    const description = addForm.getFieldValue('description');
    if (label && key && value) {
      // get(`${CITY_SERVICE}/OMS.svc/M_AddKeyValue`, {
      //   _version: 9999,
      //   _dc: new Date().getTime(),
      //   label,
      //   key,
      //   value,
      //   desc: description,
      // })
      //   .then(res => {
      //     if (res.success) {
      //       setAddVisible(false);
      //       getData();
      //       notification.success({
      //         message: '提交成功',
      //       });
      //     } else {
      //       notification.error({
      //         message: '提交失败',
      //         description: res.message,
      //       });
      //     }
      //   })
      //   .catch(err => {
      //     message.error(err);
      //   });
      AddKeyValue({
        label,
        key,
        value,
        desc: description,
      }).then(res => {
        if (res.code === 0) {
          setAddVisible(false);
          getData();
          notification.success({
            message: '提交成功',
          });
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      });
    } else {
      notification.error({
        message: '提交失败',
        description: '名称/键名/值不能为空',
      });
    }
  };
  // 提交-重置
  const submitReset = () => {
    get(`${PUBLISH_SERVICE}/DataManger/ResetKeyValue`, {})
      .then(res => {
        if (res.code === 0) {
          getData();
          notification.success({
            message: '重置成功',
          });
        } else {
          notification.error({
            message: '重置失败',
            description: res.message,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };
  // 提交-编辑
  const submitEdit = () => {
    const label = editForm.getFieldValue('label');
    const key = editForm.getFieldValue('key');
    const value = editForm.getFieldValue('value');
    const description = editForm.getFieldValue('description');
    if (label && key && value) {
      // get(`${CITY_SERVICE}/OMS.svc/M_EditKeyValue`, {
      //   _version: 9999,
      //   _dc: new Date().getTime(),
      //   id: select.id,
      //   label,
      //   key,
      //   value,
      //   desc: description,
      // })
      //   .then(res => {
      //     if (res.success) {
      //       setEditVisible(false);
      //       getData();
      //       notification.success({
      //         message: '提交成功',
      //       });
      //     } else {
      //       notification.error({
      //         message: '提交失败',
      //         description: res.message,
      //       });
      //     }
      //   })
      //   .catch(err => {
      //     message.error(err);
      //   });
      EditKeyValue({
        id: select.id,
        label,
        key,
        value,
        desc: description,
      }).then(res => {
        if (res.code === 0) {
          setEditVisible(false);
          getData();
          notification.success({
            message: '提交成功',
          });
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      });
    } else {
      notification.error({
        message: '提交失败',
        description: '名称/键名/值不能为空',
      });
    }
  };

  const submitDelete = () => {
    // get(`${CITY_SERVICE}/OMS.svc/M_DeleteKeyValue`, {
    //   _version: 9999,
    //   _dc: new Date().getTime(),
    //   key: select.Key,
    // })
    //   .then(res => {
    //     if (res.success) {
    //       getData(select.parentID);
    //       notification.success({
    //         message: '删除成功',
    //       });
    //     } else {
    //       notification.error({
    //         message: '删除失败',
    //         description: res.message,
    //       });
    //     }
    //   })
    //   .catch(err => {
    //     message.error(err);
    //   });

    DeleteKeyValue({
      key: select.Key,
    }).then(res => {
      if (res.code === 0) {
        getData(select.parentID);
        notification.success({
          message: '删除成功',
        });
      } else {
        notification.error({
          message: '删除失败',
          description: res.msg,
        });
      }
    });
  };

  const pagination = {
    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
    pageSizeOptions: [10, 20, 50, 100],
    defaultPageSize: 20,
    showQuickJumper: true,
    showSizeChanger: true,
  };
  return (
    <div className={styles.AppDic}>
      <Spin spinning={loading} tip="loading...">
        <div
          style={{
            marginBottom: '10px',
            fontSize: '16px',
            height: 'calc(100vh-200px)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <span>数据字典</span>
          <div>
            <Tooltip title="添加">
              <PlusSquareOutlined
                onClick={() => {
                  setAddVisible(true);
                  addForm.resetFields();
                }}
                style={{
                  color: '#1890FF',
                  fontSize: '20px',
                  marginRight: '22px',
                }}
              />
            </Tooltip>

            <Popconfirm
              title="是否重置默认配置?"
              okText="确认"
              cancelText="取消"
              onConfirm={submitReset}
            >
              <Tooltip title="还原">
                <SyncOutlined
                  style={{
                    color: '#1890FF',
                    fontSize: '20px',
                    marginRight: '30px',
                  }}
                />
              </Tooltip>
            </Popconfirm>
          </div>
        </div>
        <Table
          size="small"
          bordered
          columns={columns}
          dataSource={data}
          scroll={{ x: 'max-content' }}
          pagination={pagination}
        />
      </Spin>

      {/* 添加 */}
      <Modal
        title="添加数据字典"
        visible={addVisible}
        onOk={submitAdd}
        onCancel={() => {
          setAddVisible(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={addForm} labelCol={{ span: 3 }}>
          <Form.Item name="label" label="名称" rules={[{ required: true, message: '不能为空' }]}>
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="key" label="键名" rules={[{ required: true, message: '不能为空' }]}>
            <Input placeholder="请输入键名" />
          </Form.Item>
          <Form.Item name="value" label="值" rules={[{ required: true, message: '不能为空' }]}>
            <Input placeholder="请输入值" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input placeholder="请输入相关描述" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 修改 */}
      <Modal
        title="修改数据字典"
        visible={editVisible}
        onOk={submitEdit}
        onCancel={() => {
          setEditVisible(false);
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form form={editForm} labelCol={{ span: 3 }}>
          <Form.Item name="label" label="名称" rules={[{ required: true, message: '不能为空' }]}>
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="key" label="键名">
            <Input placeholder="请输入键名" />
          </Form.Item>
          <Form.Item name="value" label="值" rules={[{ required: true, message: '不能为空' }]}>
            <Input placeholder="请输入值" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input placeholder="请输入相关描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AppDic;