/* eslint-disable indent */
/* 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,
  Tag,
} from 'antd';
import {
  EditTwoTone,
  DeleteOutlined,
  PlusOutlined,
  SyncOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import styles from './gateWay.less';
import axios from 'axios';
import {
  GetGateWay,
  UpdateGeteWay,
  GetReRoutes,
  GetReRoutesFirst,
  DelRoutes,
  DelRouteByUpUrl,
  GetWayHealthCheck,
} from '@/services/hostmanager/hostmanager';
import { get, PUBLISH_SERVICE } from '@/services/index';
import configuration from '../../../../assets/images/icons/消息.svg';

import AddModal from './AddModal';
import CheckModal from './CheckModal';

const GateConfig = () => {
  const [loading, setLoading] = useState(false); // 加载
  const [allLoading, setAllLoading] = 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 [checkVisible, setCheckVisible] = useState(false);
  const [pickItem, setPickItem] = useState('');
  const [type, setType] = useState('');
  const history = useHistory();
  const [keepData, setKeepData] = useState([]); // 保存内置关键字
  const { Search } = Input;

  const OperateNginx = checked => {
    localStorage.setItem('panda-publish', '');
    console.log(checked);
    if (checked) {
      setAllLoading(true);
      GetWayHealthCheck().then(resData => {
        setAllLoading(false);
        if (resData.code === 0) {
          UpdateGeteWay({ isUsed: checked }).then(res => {
            if (res.code === 0) {
              console.log(localStorage.getItem('token'));
              // localStorage.removeItem('token');
              window.globalConfig = {
                ...window.globalConfig,
                access_token: localStorage.getItem('token'),
                hasGateWay: true,
                apiGatewayDomain: `${window.location.origin}${'/PandaCore/GateWay'}`,
              };
              setFlag(flag + 1);
              message.success('设置成功');
              // const key = 'authrizeFail';
              // notification.warning({
              //   key,
              //   title: '提示',
              //   message: '授权失败，即将跳转到登录页',
              //   duration: 2,
              // });
              // setTimeout(() => {
              //   history.push(`/user/login`);
              // }, 2000);
              const key = 'authrizeFail';
              const btn = (
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    notification.close(key);
                    window.location.href = `/${process.env.PUBLIC_PATH || 'civmanage'}/user/login`;
                  }}
                >
                  确定
                </Button>
              );
              if (!/\/user\/login$/.test(window.location.pathname)) {
                notification.warning({
                  key,
                  title: '提示',
                  message: '授权失败，即将跳转到登录页',
                  duration: 2,
                  btn,
                });
                setTimeout(() => {
                  window.location.href = `/${process.env.PUBLIC_PATH || 'civmanage'}/user/login`;
                }, 2000);
              }
            } else {
              message.error('设置失败');
            }
          });
          setTimeout(() => {
            localStorage.setItem('panda-publish', 'getway');
            setLoading(true);
            GetReRoutes({
              UpstreamPathTemplate: '',
              key: '',
            }).then(res => {
              setLoading(false);
              if (res.code === 0) {
                setTableData(res.data);
              }
            });
          }, 0);
        } else {
          message.warning({
            content: (
              <>
                万能模板下游服务 [<span style={{ color: '#1890ff' }}>{tableData[0].url}</span>]
                检测不通过，请修复后再开启！
              </>
            ),
            style: {
              marginTop: '10vh',
            },
          });
        }
      });
    } else {
      UpdateGeteWay({ isUsed: checked }).then(res => {
        if (res.code === 0) {
          // 关闭网关清空token
          localStorage.setItem('token', '');
          window.globalConfig = {
            ...window.globalConfig,
            access_token: '',
            hasGateWay: false,
            apiGatewayDomain: `${window.location.origin}`,
          };
          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 {
  //     console.log(123333);
  //     localStorage.setItem('panda-publish', '');
  //   }
  // }, [currentConfig]);

  useEffect(() => {
    GetGateWay().then(res => {
      if (res.code === 0) {
        setCurrentConfig(res.data);
        console.log(currentConfig);
      }
    });
    // .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);
    //     }
    //   });
    // });
    // if (res.data) {
    GetReRoutes({
      UpstreamPathTemplate: '',
      key: '',
    }).then(resdata => {
      setLoading(false);
      if (resdata.code === 0) {
        console.log(resdata.data);
        let data = [];
        resdata.data.map(i => {
          data.push(i.key);
        });
        setKeepData(data);
        setTableData(resdata.data);
      }
    });
    // }
  }, [flag]);

  const columns = [
    {
      title: '关键字',
      dataIndex: 'key',
      key: 'key',
      align: 'center',
      width: 150,
      render: (text, record) => {
        if (record.remark) {
          return (
            <Tooltip placement="top" title={text}>
              <span>
                {searchStyle1(text)}{' '}
                <Tag color="cyan" style={{ marginRight: '0px' }}>
                  {record.remark}
                </Tag>
              </span>
            </Tooltip>
          );
        } else {
          return (
            <span>
              <Tooltip placement="top" title={text}>
                {searchStyle1(text)}
              </Tooltip>
            </span>
          );
        }
      },
    },
    {
      title: '上游服务地址',
      dataIndex: 'upstreamPathTemplate',
      key: 'upstreamPathTemplate',
      align: 'center',
      render: (text, record) => {
        let str = window.location.origin + `/PandaCore/GateWay${text}`;
        let list = str.split(':');
        list[0] = record.downstreamScheme;
        let data = record.downstreamScheme;
        list.forEach((i, j) => {
          if (j > 0) {
            data = data + ':' + i;
          }
        });
        return (
          <span>
            <Tooltip placement="top" title={`上游路由模板：${text}`}>
              {data}
            </Tooltip>
          </span>
        );
      },
    },
    // {
    //   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,
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={`下游路由模板：${record.downstreamPathTemplate}`}>
            {`${text}${record.downstreamPathTemplate}`}
          </Tooltip>
        </span>
      ),
    },
    // {
    //   title: '下游路由模板',
    //   dataIndex: 'downstreamPathTemplate',
    //   key: 'downstreamPathTemplate',
    //   ellipsis: true,
    //   width: 150,
    //   align: 'center',
    //   render: (text, record) => (
    //     <span>
    //       <Tooltip placement="top" title={text}>
    //         {text}
    //       </Tooltip>
    //     </span>
    //   ),
    // },
    {
      title: '开启身份认证',
      dataIndex: 'isAuthentication',
      key: 'isAuthentication',
      align: 'center',
      width: 120,
      render: (text, record) => {
        if (text == true) {
          return <Tag color="#87d068">是</Tag>;
        } else {
          return <Tag color="#2db7f5">否</Tag>;
        }
      },
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      align: 'center',
      width: 100,
      render: (text, record) => {
        console.log(text);
        return (
          <span>
            <Tooltip placement="top" title={text}>
              {text}
            </Tooltip>
          </span>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      fixed: 'right',
      render: record => {
        // if (record.key != 'CityServer') {
        return (
          <Space size="middle">
            <Tooltip title="编辑">
              <EditTwoTone onClick={() => edit(record)} style={{ fontSize: '16px' }} />
            </Tooltip>
            {!record.remark && (
              <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>
        );
        // } else {
        //   return (
        //     <Space size="middle">
        //       <Tooltip title="查看">
        //         <SearchOutlined onClick={() => look(record)} style={{ fontSize: '16px' }} />
        //       </Tooltip>
        //     </Space>
        //   );
        // }
      },
    },
  ];

  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      const escapedSearchValue = searchWord.replace(/\\/g, '\\\\');
      const regex = new RegExp(escapedSearchValue, 'g');
      n = val.replace(
        regex,
        `<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 look = e => {
    setPickItem(e);
    setCheckVisible(true);
  };

  const dele = e => {
    setPickItem(e);
    let data = [];
    data.push(e.id);
    console.log(data);
    if (e.id == 1) {
      notification.error({
        message: '删除失败',
        description: '默认数据无法删除',
      });
    } else {
      DelRouteByUpUrl({
        upTemplate: e.upstreamPathTemplate,
      }).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}>
      <Spin spinning={allLoading} tip="loading">
        <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();
                    // if (record.key == 'CityServer') {
                    //   look(record);
                    // } else {
                    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}
            keepData={keepData}
            onCancel={() => setAddVisible(false)}
            type={type}
            callBackSubmit={onSubmit}
          />
          <CheckModal
            visible={checkVisible}
            pickItem={pickItem}
            onCancel={() => setCheckVisible(false)}
          />
        </Card>
      </Spin>
    </div>
  );
};
export default GateConfig;
