/* eslint-disable no-unused-expressions */
/* eslint-disable no-else-return */
import React, { useEffect, useState } from 'react';
import {
  Card,
  Form,
  Switch,
  message,
  Divider,
  Row,
  Col,
  Spin,
  Tooltip,
  Input,
  Space,
  Button,
  Popconfirm,
  Table,
  notification,
} from 'antd';
import {
  EditTwoTone,
  DeleteOutlined,
  PlusOutlined,
  SyncOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import styles from './gateWay.less';
import {
  GetGateWay,
  UpdateGeteWay,
  GetReRoutes,
  GetReRoutesFirst,
  DelRoutes,
} from '@/services/hostmanager/hostmanager';
import configuration from '../../../../assets/images/icons/消息.svg';

import AddModal from './AddModal';

const GateConfig = () => {
  const [loading, setLoading] = useState(false); // 加载
  const [form] = Form.useForm();

  const [flag, setFlag] = useState(1);
  const [currentConfig, setCurrentConfig] = useState();
  const [tableData, setTableData] = useState([]);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const [searchWord1, setSearchWord1] = useState(''); // 关键字
  const [addVisible, setAddVisible] = useState(false);
  const [pickItem, setPickItem] = useState('');
  const [type, setType] = useState('');
  const { Search } = Input;

  const OperateNginx = checked => {
    console.log(checked);
    UpdateGeteWay({ isUsed: checked }).then(res => {
      if (res.code === 0) {
        setFlag(flag + 1);
        message.success('设置成功');
      } else {
        message.error('设置失败');
      }
    });
  };
  useEffect(() => {
    if (currentConfig) {
      localStorage.setItem('panda-publish', 'getway');
      GetReRoutes({
        UpstreamPathTemplate: '',
        key: '',
      }).then(res => {
        setLoading(false);
        if (res.code === 0) {
          setTableData(res.data);
        }
      });
    } else {
      localStorage.setItem('panda-publish', '');
    }
  }, [currentConfig]);

  useEffect(() => {
    GetGateWay().then(res => {
      if (res.code === 0) {
        setCurrentConfig(res.data);
        console.log(currentConfig);
      }
    });
    setLoading(true);

    // .catch(err => {
    //   setLoading(false);
    //   GetReRoutes({
    //     UpstreamPathTemplate: '',
    //     key: '',
    //   }).then(resdata => {
    //     setLoading(false);
    //     if (resdata.code === 0) {
    //       console.log(resdata.data);
    //       setTableData(resdata.data);
    //     } else {
    //       console.log(123);
    //     }
    //   });
    // });
  }, [flag]);

  const columns = [
    {
      title: '上游路由模板',
      dataIndex: 'upstreamPathTemplate',
      key: 'upstreamPathTemplate',
      align: 'center',
      ellipsis: true,
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={text}>
            {searchStyle(text)}
          </Tooltip>
        </span>
      ),
    },
    {
      title: '上游请求方式',
      dataIndex: 'methods',
      key: 'methods',
      align: 'center',
      ellipsis: true,
      width: 200,
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={text}>
            {text}
          </Tooltip>
        </span>
      ),
    },
    {
      title: '下游服务地址',
      dataIndex: 'url',
      key: 'url',
      align: 'center',
      ellipsis: true,
      width: 250,
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={text}>
            {text}
          </Tooltip>
        </span>
      ),
    },
    {
      title: '下游路由模板',
      dataIndex: 'downstreamPathTemplate',
      key: 'downstreamPathTemplate',
      ellipsis: true,
      align: 'center',
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={text}>
            {text}
          </Tooltip>
        </span>
      ),
    },
    {
      title: '关键字',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      width: 100,
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={text}>
            {searchStyle1(text)}
          </Tooltip>
        </span>
      ),
    },
    {
      title: '开启身份认证',
      dataIndex: 'isAuthentication',
      key: 'isAuthentication',
      align: 'center',
      width: 120,
      render: (text, record) => {
        if (text == true) {
          return <span>是</span>;
        } else {
          return <span>否</span>;
        }
      },
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      align: 'center',
      render: (text, record) => {
        console.log(text);
        return (
          <span>
            <Tooltip placement="top" title={text}>
              {text}
            </Tooltip>
          </span>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      render: record => (
        <Space size="middle">
          <Tooltip title="编辑">
            <EditTwoTone onClick={() => edit(record)} style={{ fontSize: '16px' }} />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              placement="bottomRight"
              title={
                <p>
                  即将删除 <span>{record.loginName}</span>
                  ，是否确认删除？
                </p>
              }
              okText="确认"
              cancelText="取消"
              onConfirm={() => dele(record)}
            >
              <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(new RegExp(searchWord, 'g'), `<span style='color:red'>${searchWord}</span>`);
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  // 模糊查询匹配的样式
  const searchStyle1 = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(
        new RegExp(searchWord1, 'g'),
        `<span style='color:red'>${searchWord1}</span>`,
      );
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  const handleReset = () => {
    setSearchWord('');
    setSearchWord1('');
    setShowSearchStyle(false);
    setLoading(true);
    GetReRoutes({
      UpstreamPathTemplate: '',
      key: '',
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setTableData(res.data);
      }
    });
  };

  const handleSearch = e => {
    setSearchWord(e.target.value);
  };

  const handleSearch1 = e => {
    setSearchWord1(e.target.value);
  };

  const submitSearch = () => {
    setLoading(true);
    GetReRoutes({ UpstreamPathTemplate: searchWord, Key: searchWord1 }).then(resnew => {
      setLoading(false);
      if (resnew.code === 0) {
        setTableData(resnew.data);
        setShowSearchStyle(true);
      } else {
        notification.error({
          message: '查询失败',
          description: resnew.msg,
        });
      }
    });
  };

  const add = () => {
    setType('add');
    setAddVisible(true);
  };

  const edit = e => {
    setType('edit');
    setPickItem(e);
    setAddVisible(true);
  };

  const dele = e => {
    setPickItem(e);
    let data = [];
    data.push(e.id);
    console.log(data);
    if (e.id == 1) {
      notification.error({
        message: '删除失败',
        description: '默认数据无法删除',
      });
    } else {
      DelRoutes({
        Ids: e.id,
      }).then(res => {
        if (res.code === 0) {
          GetReRoutes({
            UpstreamPathTemplate: '',
            key: '',
          }).then(res => {
            setLoading(false);
            if (res.code === 0) {
              setTableData(res.data);
            }
          });
          notification.success({
            message: '删除成功',
            description: res.msg,
          });
        } else {
          notification.error({
            message: '删除失败',
            description: res.msg,
          });
        }
      });
    }
  };

  const onSubmit = () => {
    GetReRoutes({
      UpstreamPathTemplate: '',
      key: '',
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setTableData(res.data);
      }
    });
  };

  return (
    <div className={styles.gateWay_container}>
      <Card style={{ width: '100%', height: 'calc(100vh - 130px)' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginTop: '10px' }}>
          <img src={configuration} style={{ height: '16px' }} alt="" />
          <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>网关配置</span>
        </div>
        <Divider />
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div
              style={{
                marginLeft: '35px',
              }}
            >
              网关开启
              <Switch
                checkedChildren="开启"
                unCheckedChildren="关闭"
                checked={currentConfig}
                onChange={OperateNginx}
                style={{ marginLeft: '35px' }}
              />
            </div>
            {console.log(currentConfig)}
          </div>
          {currentConfig ? (
            <div className={styles.head1}>
              <span>快速搜索上游路由模板：</span>
              <Input
                value={searchWord}
                placeholder="请输入上游路由模板"
                style={{ width: 200 }}
                onChange={handleSearch}
              />
              <span style={{ marginLeft: '20px' }}>快速搜索关键字：</span>
              <Input
                value={searchWord1}
                placeholder="请输入键值"
                style={{ width: 200 }}
                onChange={handleSearch1}
              />
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={submitSearch}
                style={{ marginLeft: '20px' }}
              >
                搜索
              </Button>
              <Button icon={<SyncOutlined />} onClick={handleReset} style={{ marginLeft: '20px' }}>
                重置
              </Button>
              <Button
                icon={<PlusOutlined className={styles.icon} />}
                onClick={add}
                style={{
                  verticalAlign: 'middle',
                  marginTop: '-3px',
                  marginLeft: '20px',
                }}
              >
                新增
              </Button>
            </div>
          ) : (
            <></>
          )}
        </div>
        {currentConfig ? (
          <Spin spinning={loading} tip="loading">
            <div className={styles.table}>
              <Table
                size="small"
                bordered
                rowKey={record => record.Id}
                columns={columns}
                dataSource={tableData}
                scroll={{ y: 'calc(100vh - 380px)', x: 'max-content' }}
                onRow={record => ({
                  onDoubleClick: event => {
                    event.stopPropagation();
                    edit(record);
                  }, // 双击
                })}
                pagination={{
                  showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                  pageSizeOptions: [10, 20, 50, 100],
                  defaultPageSize: 20,
                  showQuickJumper: true,
                  showSizeChanger: true,
                }}
              />
            </div>
          </Spin>
        ) : (
          <></>
        )}

        <AddModal
          visible={addVisible}
          pickItem={pickItem}
          onCancel={() => setAddVisible(false)}
          type={type}
          callBackSubmit={onSubmit}
        />
      </Card>
    </div>
  );
};
export default GateConfig;
