import React, { useState, useEffect } from 'react';
import {
  Tooltip,
  Spin,
  Modal,
  Input,
  Space,
  Button,
  Popconfirm,
  Table,
  notification,
  Image,
  Tag,
} from 'antd';
import {
  GetIntegratedLogin,
  DelIntegratedLogin,
  SetIntegratedloginSettingSort,
  EditIntegratedLogin,
} from '@/services/integratedLogin/api';
import { DownLoadFiles } from '@/services/common/api';
import {
  EditTwoTone,
  DeleteOutlined,
  PlusOutlined,
  SyncOutlined,
  FilePdfOutlined,
  OrderedListOutlined,
  LockOutlined,
  UnlockOutlined,
} from '@ant-design/icons';
import styles from './integrate.less';
import AddModal from './AddModal';
import Master from './Master';
import SortModal from './SortModal';
import { set } from 'lodash';

const path = require('path');

const Integrate = () => {
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const [flag, setFlag] = useState(0);
  const [addVisible, setAddVisible] = useState(false);
  const [pickItem, setPickItem] = useState('');
  const [type, setType] = useState('');
  const [masterVisible, setMasterVisible] = useState(false);
  const [keepSystemName, setKeepSystemName] = useState([]);
  const [sortVisible, setSortVisible] = useState(false);
  const [groupList, setGroupList] = useState([]); // 分组列表

  const { Search } = Input;

  useEffect(() => {
    getData();
    console.log(tableData, 'tableData');
  }, [flag]);

  const getImg = img => {
    return `/PandaOMS/OMS/FileCenter/DownLoadFiles?module=图库&filePath=${img}`;
  };

  const columns = [
    {
      title: '序号',
      key: 'id ',
      dataIndex: 'id',
      render: (text, record, index) => (
        <Space>
          <span>{index + 1}</span>
        </Space>
      ),
      width: 60,
      align: 'center',
    },
    {
      title: '图标',
      dataIndex: 'showUrl',
      key: 'showUrl',
      align: 'center',
      width: 200,
      render: (text, record) => {
        if (text) {
          return (
            <Image
              // src={`${window.location.origin}/${text}`}
              src={text}
              height="50px"
              style={{ backgroundColor: '#2881a1' }}
            />
          );
        }
      },
    },
    {
      title: '名称',
      dataIndex: 'SystemName',
      key: 'SystemName',
      align: 'center',
      ellipsis: true,
      render: (text, record) => (
        <span>
          <Tooltip placement="top" title={text}>
            {searchStyle(text)}
          </Tooltip>
        </span>
      ),
    },
    // {
    //   title: '副标题',
    //   dataIndex: 'Subtitle',
    //   key: 'Subtitle',
    //   align: 'center',
    //   ellipsis: true,
    //   render: (text, record) => (
    //     <span>
    //       <Tooltip placement="top" title={text}>
    //         {text}
    //       </Tooltip>
    //     </span>
    //   ),
    // },
    // {
    //   title: '外网地址',
    //   dataIndex: 'InternetAddress',
    //   key: 'InternetAddress',
    //   align: 'center',
    //   render: record => {
    //     if (record) {
    //       return (
    //         <Tooltip title={record}>
    //           <span style={{ color: '#50aefc', cursor: 'pointer' }}>已配置</span>
    //         </Tooltip>
    //       );
    //     }
    //     return <span>未配置</span>;
    //   },
    // },
    // {
    //   title: '内网地址',
    //   dataIndex: 'IntranetAddress',
    //   key: 'IntranetAddress',
    //   align: 'center',
    //   render: record => {
    //     if (record) {
    //       return (
    //         <Tooltip title={record}>
    //           <span style={{ color: '#50aefc', cursor: 'pointer' }}>已配置</span>
    //         </Tooltip>
    //       );
    //     }
    //     return <span>未配置</span>;
    //   },
    // },
    // {
    //   title: '账号参数',
    //   dataIndex: 'AccountParamKey',
    //   key: 'AccountParamKey',
    //   align: 'center',
    //   render: (text, record) => (
    //     <span>
    //       <Tooltip placement="top" title={text}>
    //         {text}
    //       </Tooltip>
    //     </span>
    //   ),
    // },
    // {
    //   title: '账号值',
    //   dataIndex: 'AccountParamValue',
    //   key: 'AccountParamValue',
    //   align: 'center',
    //   render: record => {
    //     if (record === 1) {
    //       return <span>熊猫ticket</span>;
    //     }
    //     return <span>熊猫token</span>;
    //   },
    // },
    {
      title: '身份验证',
      dataIndex: 'siteType',
      key: 'siteType',
      align: 'center',
      render: record => {
        if (record === 0) {
          return <Tag color="success">第三方接入</Tag>;
        }
        return <Tag color="processing">集成SaaS平台</Tag>;
      },
    },
    {
      title: '特殊站点',
      dataIndex: 'isMaster',
      key: 'isMaster',
      align: 'center',
      render: record => {
        if (record) {
          return <Tag color="success">是</Tag>;
        }
        return <Tag color="processing">否</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      render: record => (
        <Space size="middle">
          <Tooltip title="编辑">
            <EditTwoTone onClick={() => edit(record)} style={{ fontSize: '16px' }} />
          </Tooltip>
          {record.isHide ? (
            <Tooltip title="停用">
              <Popconfirm
                placement="left"
                title={
                  <p>
                    启用站点
                    <span className={styles.redText}>{record.SystemName}</span>
                  </p>
                }
                okText="确认"
                cancelText="取消"
                onConfirm={() => startUser(record)}
              >
                <LockOutlined style={{ fontSize: '16px', color: '#e86060' }} />
              </Popconfirm>
            </Tooltip>
          ) : (
            <Tooltip title="启用">
              <Popconfirm
                placement="left"
                title={
                  <p>
                    停用站点
                    <span className={styles.redText}>{record.SystemName}</span>
                  </p>
                }
                okText="确认"
                cancelText="取消"
                onConfirm={() => freezeUser(record)}
              >
                <UnlockOutlined style={{ fontSize: '16px', color: '#1890ff' }} />
              </Popconfirm>
            </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 freezeUser = e => {
    let aa = e;
    aa.isHide = true;
    console.log(e);
    EditIntegratedLogin(aa).then(res => {
      if (res.code == 0) {
        setFlag(flag + 1);
        notification.success({
          message: '设置成功',
          description: res.msg,
        });
      } else {
        notification.error({
          message: '设置失败',
          description: res.msg,
        });
      }
    });
  };

  // 启用
  const startUser = e => {
    console.log(e);
    let aa = e;
    aa.isHide = false;
    console.log(e);
    EditIntegratedLogin(aa).then(res => {
      if (res.code == 0) {
        setFlag(flag + 1);
        notification.success({
          message: '设置成功',
          description: res.msg,
        });
      } else {
        notification.error({
          message: '设置失败',
          description: res.msg,
        });
      }
    });
  };

  // 模糊查询匹配的样式
  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 getData = () => {
    setLoading(true);
    GetIntegratedLogin({ isHide: false }).then(resnew => {
      if (resnew.code === 0) {
        console.log(resnew.data);
        let aa = [];
        let list = new Set([]);
        if (resnew.data.length > 0) {
          resnew.data.map((i, j) => {
            aa.push(i.SystemName);
            if (i.GroupName) {
              list.add(i.GroupName);
            }
            resnew.data[j].AccountParamKey = i.AccountParam[0].key;
            resnew.data[j].AccountParamValue = i.AccountParam[0].value;

            if (resnew.data[j].iconUrl && !resnew.data[j].iconUrl.includes('images')) {
              resnew.data[j].showUrl = getImg(resnew.data[j].iconUrl);
            } else {
              resnew.data[j].showUrl = `${window.location.origin}/${resnew.data[j].iconUrl}`;
            }
          });
        }
        console.log([...list], 'faaa');
        setGroupList([...list].map(item => ({ value: item, label: item })));
        console.log(aa);
        setKeepSystemName(aa);
        console.log(resnew.data);
        console.log(resnew.data, 'resnew.dataresnew.dataresnew.data');
        setTableData(resnew.data);
      } else {
        notification.error({
          message: '获取失败',
          description: resnew.msg,
        });
      }
      setLoading(false);
    });
  };

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

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

  const dele = e => {
    console.log(e);
    setPickItem(e);
    setLoading(true);
    DelIntegratedLogin({
      clients: e.clients,
    }).then(res => {
      if (res.code === 0) {
        setFlag(flag + 1);
        notification.success({
          message: '删除成功',
          description: res.msg,
        });
      } else {
        notification.error({
          message: '删除失败',
          description: res.msg,
        });
      }
      setLoading(false);
    });
  };

  const submitSearch = () => {
    setLoading(true);
    GetIntegratedLogin({ searchKey: searchWord, isHide: false }).then(resnew => {
      if (resnew.code === 0) {
        setTableData(resnew.data);
        setShowSearchStyle(true);
        let aa = [];
        if (resnew.data.length > 0) {
          resnew.data.map((i, j) => {
            aa.push(i.SystemName);
            resnew.data[j].AccountParamKey = i.AccountParam[0].key;
            resnew.data[j].AccountParamValue = i.AccountParam[0].value;

            if (resnew.data[j].iconUrl && !resnew.data[j].iconUrl.includes('images')) {
              resnew.data[j].showUrl = getImg(resnew.data[j].iconUrl);
            } else {
              resnew.data[j].showUrl = `${window.location.origin}/${resnew.data[j].iconUrl}`;
            }
          });
        }
        setKeepSystemName(aa);
        setTableData(resnew.data);
      } else {
        notification.error({
          message: '获取失败',
          description: resnew.msg,
        });
      }
      setLoading(false);
    });
  };

  // const getData = () => {
  //   setLoading(true);
  //   GetIntegratedLogin({ isHide: false }).then(resnew => {
  //     if (resnew.code === 0) {
  //       console.log(resnew.data);
  //       let aa = [];
  //       if (resnew.data.length > 0) {
  //         resnew.data.map((i, j) => {
  //           aa.push(i.SystemName);
  //           resnew.data[j].AccountParamKey = i.AccountParam[0].key;
  //           resnew.data[j].AccountParamValue = i.AccountParam[0].value;

  //           if (resnew.data[j].iconUrl && !resnew.data[j].iconUrl.includes('images')) {
  //             resnew.data[j].showUrl = getImg(resnew.data[j].iconUrl);
  //           } else {
  //             resnew.data[j].showUrl = `${window.location.origin}/${resnew.data[j].iconUrl}`;
  //           }
  //         });
  //       }
  //       console.log(aa);
  //       setKeepSystemName(aa);
  //       console.log(resnew.data);
  //       console.log(resnew.data, 'resnew.dataresnew.dataresnew.data');
  //       setTableData(resnew.data);
  //     } else {
  //       notification.error({
  //         message: '获取失败',
  //         description: resnew.msg,
  //       });
  //     }
  //     setLoading(false);
  //   });
  // };

  const handleReset = () => {
    setSearchWord('');
    setShowSearchStyle(false);
    setLoading(true);
    GetIntegratedLogin({ searchKey: '', isHide: false }).then(resnew => {
      if (resnew.code === 0) {
        setTableData(resnew.data);
      } else {
        notification.error({
          message: '获取失败',
          description: resnew.msg,
        });
      }
      setLoading(false);
    });
  };

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

  const onSubmit = () => {
    setFlag(flag + 1);
  };

  const masterStation = () => {
    setType('');
    setMasterVisible(true);
  };

  const sort = () => {
    setSortVisible(true);
  };

  const onOK = () => {
    setSortVisible(false);
    setFlag(flag + 1);
  };

  return (
    <div className={styles.Integrate}>
      <div className={styles.head}>
        <div className={styles.head1}>
          <span>快速搜索：</span>
          <Search
            style={{ width: 260 }}
            placeholder="请输入名称"
            onSearch={submitSearch}
            onChange={e => handleSearch(e)}
            enterButton
            value={searchWord}
          />
          {/* <Button icon={<SyncOutlined />} onClick={handleReset} style={{ marginLeft: '20px' }}>
            重置
          </Button> */}
          <Button
            icon={<PlusOutlined className={styles.icon} />}
            type="primary"
            onClick={add}
            style={{
              verticalAlign: 'middle',
              marginLeft: '20px',
            }}
          >
            子站
          </Button>
          <Button
            icon={<OrderedListOutlined className={styles.icon} />}
            onClick={sort}
            style={{
              marginLeft: '20px',
              verticalAlign: 'middle',
            }}
          >
            <span style={{ marginTop: '-3px' }}>调序</span>
          </Button>
        </div>
        <div>
          <a target="_blank" style={{ marginRight: '20px' }} href={path.join(__dirname, '/center')}>
            快速访问平台
          </a>
          <Tooltip title="点击查看对接文档">
            <a
              style={{ display: 'inline-block', marginTop: '5px', marginRight: '20px' }}
              target="_blank"
              href={path.join(__dirname, '/civmanage/熊猫智慧水务第三方系统接入说明文档.pdf')}
              rel="noopener noreferer"
            >
              <FilePdfOutlined style={{ fontSize: '24px' }} />
            </a>
          </Tooltip>
          <Button onClick={masterStation}>配置集成网站</Button>
        </div>
      </div>
      <Spin spinning={loading} tip="loading">
        <div className={styles.table}>
          <Table
            size="small"
            bordered
            rowKey={record => record.SystemName}
            columns={columns}
            dataSource={tableData}
            scroll={{ y: 'calc(100vh - 200px)', x: 'max-content' }}
            onRow={record => ({
              onDoubleClick: event => {
                event.stopPropagation();
                edit(record);
              }, // 双击
            })}
            pagination={false}
          />
        </div>
      </Spin>
      <AddModal
        visible={addVisible}
        pickItem={pickItem}
        onCancel={() => setAddVisible(false)}
        type={type}
        callBackSubmit={onSubmit}
        groupList={groupList}
        keepSystemName={keepSystemName}
      />
      <Master visible={masterVisible} onCancel={() => setMasterVisible(false)} type={type} />
      <SortModal
        title="调整顺序"
        visible={sortVisible}
        sortData={tableData}
        onCancel={() => setSortVisible(false)}
        callBackSubmit={onOK}
      />
    </div>
  );
};

export default Integrate;
